我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
建议的正确方法是Number(new Date()),就代码可读性而言,
此外,UglifyJS和Google闭包编译器将降低已解析代码逻辑树的复杂性(如果您使用其中一个来隐藏/缩小代码)。
对于时间分辨率较低的Unix时间戳,只需将当前数字除以1000,保持整数。
其他回答
简单来说,这里有一个函数可以在Javascript中返回时间戳字符串。示例:下午15:06:38
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
var my_timestamp=~~(Date.now()/1000);
var timestamp = Number(new Date()); // current time as number
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
时间戳(毫秒)
要获取自Unix纪元以来的毫秒数,请调用Date.now:
Date.now()
或者,使用一元运算符+调用Date.prototype.valueOf:
+ new Date()
或者,直接调用valueOf:
new Date().valueOf()
要支持IE8和更早版本(请参阅兼容性表),请为Date.now创建一个垫片:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
或者,直接调用getTime:
new Date().getTime()
时间戳(秒)
要获取自Unix纪元以来的秒数,即Unix时间戳:
Math.floor(Date.now() / 1000)
或者,使用逐位或逐层稍快,但可读性也较低,将来可能会中断(参见解释1、2):
Date.now() / 1000 | 0
以毫秒为单位的时间戳(分辨率更高)
使用performance.now:
var isPerformanceSupported=(窗口.性能&&窗口.性能.当前&&窗口.性能.计时&&窗口.性能.计时.导航开始);var timeStampInMs=(是否支持性能?window.performance.now()+窗口.性能.计时.导航开始:日期.now());console.log(timeStampInMs,Date.now());
推荐文章
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- 在Android应用程序中显示当前时间和日期
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何转换日期时间?将日期时间
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?