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


当前回答

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

new Date().toISOString();

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

其他回答

var d = new Date();
console.log(d.valueOf()); 

任何不支持Date.now的浏览器,您都可以使用它获取当前日期时间:

currentTime = Date.now() || +new Date()

我喜欢这个,因为它很小:

+new Date

我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:

Date.now()

如果想要一种在Node.js中生成时间戳的基本方法,这很好。

var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );

我们的团队正在使用此方法在本地主机环境中破坏缓存。输出是/dist/css/global.css?v=245521377,其中245521377是hrtime()生成的时间戳。

希望这会有所帮助,上面的方法也可以工作,但我发现这是Node.js中最简单的方法。

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