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


当前回答

在写这篇文章时,最重要的答案是9年前的事了,从那以后发生了很多变化——最重要的是,我们几乎得到了对非黑客解决方案的普遍支持:

Date.now()

如果你想绝对肯定这不会在某些古老的(ie9之前的)浏览器中出现,你可以将其置于检查之后,如下所示:

const currentTimestamp = (!Date.now ? +new Date() : Date.now());

当然,这将返回自纪元时间以来的毫秒,而不是秒。

Date.now上的MDN文档

其他回答

下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss

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())));
}
var timestamp = Number(new Date()); // current time as number

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

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

如果想要一种在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();