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


当前回答

var timestamp = Number(new Date()); // current time as number

其他回答

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

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

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

(new Date).getTime() / 1000

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

我必须创建一个TIMESTAMP,尽管我的DB映射上的类型是String,为此我使用了

new Date().toISOString();

输出类似于“2023-01-09T14:11:31.931Z”

/**
 * 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()
}

我还没见过

Math.floor(Date.now() / 1000); // current time in seconds

另一个我还没看到的是

var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();

对于微秒分辨率的时间戳,有性能。现在:

function time() { 
  return performance.now() + performance.timing.navigationStart;
}

例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。