我想要一个表示当前日期和时间的数字,比如Unix时间戳。


当前回答

对于lodash和下划线用户,请使用_.now。

var timestamp = _.now(); // in milliseconds

其他回答

Date.getTime()方法可以稍微调整一下:

getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。

将结果除以1000得到Unix时间戳,必要时为floor:

(new Date).getTime() / 1000

Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。

建议的正确方法是Number(new Date()),就代码可读性而言,

此外,UglifyJS和Google闭包编译器将降低已解析代码逻辑树的复杂性(如果您使用其中一个来隐藏/缩小代码)。

对于时间分辨率较低的Unix时间戳,只需将当前数字除以1000,保持整数。

有时我需要在xmlhttp调用的对象中使用它,所以我喜欢这样做。

timestamp : parseInt(new Date().getTime()/1000, 10)

对于lodash和下划线用户,请使用_.now。

var timestamp = _.now(); // in milliseconds
/**
 * 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()
}