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


当前回答

如果用于日志记录,则可以使用ISOString

new Date().toISOString()

“2019-05-18T20:02:36.694Z”

其他回答

日期,JavaScript中的原生对象是我们获取所有时间数据的方式。

在JavaScript中要小心,时间戳取决于客户端计算机设置,因此它不是100%准确的时间戳。要获得最佳结果,需要从服务器端获取时间戳。

总之,我更喜欢用香草。这是在JavaScript中实现的常见方法:

Date.now(); //return 1495255666921

在MDN中,如下所述:

Date.now()方法返回自1970年1月1日00:00:00 UTC。因为now()是Date的静态方法,所以您总是将其用作Date.now()。

如果您使用的版本低于ES5,Date.now();不起作用,您需要使用:

new Date().getTime();

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

console.log(newDate().valueOf());//返回自epoch以来的毫秒数

下面是另一个在JavaScript中生成时间戳的解决方案-包括单个数字的填充方法-在结果中使用天、月、年、小时、分钟和秒(jsfiddle的工作示例):

var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();

    timestamp.day = [
        pad(timestamp.getDate()),
        pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
        timestamp.getFullYear()
    ];

    timestamp.time = [
        pad(timestamp.getHours()),
        pad(timestamp.getMinutes()),
        pad(timestamp.getSeconds())
    ];

timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);
var time = Date.now || function() {
  return +new Date;
};

time();