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


当前回答

JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。

这将为您提供Unix时间戳(以秒为单位):

var unix = Math.round(+new Date()/1000);

这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):

var milliseconds = new Date().getTime();

其他回答

时间戳(毫秒)

要获取自Unix纪元以来的毫秒数,请调用Date.now:

Date.now()

或者,使用一元运算符+调用Date.prototype.valueOf:

+ new Date()

或者,直接调用valueOf:

new Date().valueOf()

要支持IE8和更早版本(请参阅兼容性表),请为Date.now创建一个垫片:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

或者,直接调用getTime:

new Date().getTime()

时间戳(秒)

要获取自Unix纪元以来的秒数,即Unix时间戳:

Math.floor(Date.now() / 1000)

或者,使用逐位或逐层稍快,但可读性也较低,将来可能会中断(参见解释1、2):

Date.now() / 1000 | 0

以毫秒为单位的时间戳(分辨率更高)

使用performance.now:

var isPerformanceSupported=(窗口.性能&&窗口.性能.当前&&窗口.性能.计时&&窗口.性能.计时.导航开始);var timeStampInMs=(是否支持性能?window.performance.now()+窗口.性能.计时.导航开始:日期.now());console.log(timeStampInMs,Date.now());

您只能使用

var timestamp=new Date().getTime();console.log(时间戳);

以获取当前时间戳。不需要做任何额外的事情。

如果想要一种在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中最简单的方法。

var time = Date.now || function() {
  return +new Date;
};

time();
function getTimeStamp() {
    var now = new Date();
    return ((now.getMonth() + 1) + '/' +
            (now.getDate()) + '/' +
             now.getFullYear() + " " +
             now.getHours() + ':' +
             ((now.getMinutes() < 10)
                 ? ("0" + now.getMinutes())
                 : (now.getMinutes())) + ':' +
             ((now.getSeconds() < 10)
                 ? ("0" + now.getSeconds())
                 : (now.getSeconds())));
}