我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
前几天,我从JQueryCookie的源代码中学习了一种将给定的Date对象转换为Unix时间戳的非常酷的方法。
下面是一个示例:
var date = new Date();
var timestamp = +date;
其他回答
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()
/**
* 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()
}
要分别获得时间、月、日、年,这将起作用
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
建议的正确方法是Number(new Date()),就代码可读性而言,
此外,UglifyJS和Google闭包编译器将降低已解析代码逻辑树的复杂性(如果您使用其中一个来隐藏/缩小代码)。
对于时间分辨率较低的Unix时间戳,只需将当前数字除以1000,保持整数。