我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()
其他回答
下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss
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())));
}
这一个有一个解决方案:在js中将unixtime stamp转换为tim
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
/**
* Equivalent to PHP's time(), which returns
* current Unix timestamp.
*
* @param {string} unit - Unit of time to return.
* - Use 's' for seconds and 'ms' for milliseconds.
* @return {number}
*/
time(unit = 's') {
return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()
}
有很多方法可以做到这一点。
Date.now()
new Date().getTime()
new Date().valueOf()
要获取以秒为单位的时间戳,请使用以下方法进行转换:
Math.floor(Date.now() / 1000)
日期,JavaScript中的原生对象是我们获取所有时间数据的方式。
在JavaScript中要小心,时间戳取决于客户端计算机设置,因此它不是100%准确的时间戳。要获得最佳结果,需要从服务器端获取时间戳。
总之,我更喜欢用香草。这是在JavaScript中实现的常见方法:
Date.now(); //return 1495255666921
在MDN中,如下所述:
Date.now()方法返回自1970年1月1日00:00:00 UTC。因为now()是Date的静态方法,所以您总是将其用作Date.now()。
如果您使用的版本低于ES5,Date.now();不起作用,您需要使用:
new Date().getTime();
推荐文章
- 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中使用钩子强制组件重新渲染?