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


当前回答

前几天,我从JQueryCookie的源代码中学习了一种将给定的Date对象转换为Unix时间戳的非常酷的方法。

下面是一个示例:

var date = new Date();
var timestamp = +date;

其他回答

我还没见过

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

另一个我还没看到的是

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

var my_timestamp=~~(Date.now()/1000);

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

在JavaScript中获取时间戳

在JavaScript中,时间戳是自1970年1月1日以来经过的毫秒数。如果您不打算支持<IE8,可以使用

new Date().getTime(); + new Date(); and Date.now();

直接获取时间戳,而无需创建新的Date对象。

返回所需的时间戳

new Date("11/01/2018").getTime()

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

+new Date

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

Date.now()