我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
Date.getTime()方法可以稍微调整一下:
getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。
将结果除以1000得到Unix时间戳,必要时为floor:
(new Date).getTime() / 1000
Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。
其他回答
/**
* 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 timestamp=new Date().getTime();console.log(时间戳);
以获取当前时间戳。不需要做任何额外的事情。
要分别获得时间、月、日、年,这将起作用
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
有很多方法可以做到这一点。
Date.now()
new Date().getTime()
new Date().valueOf()
要获取以秒为单位的时间戳,请使用以下方法进行转换:
Math.floor(Date.now() / 1000)
对于lodash和下划线用户,请使用_.now。
var timestamp = _.now(); // in milliseconds