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


当前回答

time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

其他回答

下面是一个生成时间戳的简单函数,格式为: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())));
}

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

Date.now()

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

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

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

Date.now上的MDN文档

您只能使用

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

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

有很多方法可以做到这一点。

 Date.now() 
 new Date().getTime() 
 new Date().valueOf()

要获取以秒为单位的时间戳,请使用以下方法进行转换:

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

这一个有一个解决方案:在js中将unixtime stamp转换为tim

var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();