在Node中生成时间戳,以毫秒为单位

问题描述 投票:1回答:6

任何人都可以建议如何在Node中生成以下类型的日期时间戳?

2019-02-20T10:05:00.120000Z

简而言之,日期时间以毫秒为单位。

非常感谢。

javascript node.js
6个回答
1
投票

使用Date#toISOString

toISOString()方法以简化的扩展ISO格式(ISO 8601)返回一个字符串,该字符串的长度始终为24或27个字符(YYYY-MM-DDTHH:mm:ss.sssZ或±YYYYYY-MM-DDTHH:mm:ss。 sssZ,分别)。时区始终为零UTC偏移,由后缀“Z”表示。

const res = (new Date()).toISOString();

console.log(res); // i.e 2019-03-05T10:15:15.080Z

2
投票
new Date("2019-02-20T10:05:00.120000").getTime()

2
投票
const now = (unit) => {

  const hrTime = process.hrtime();

  switch (unit) {

    case 'milli':
      return hrTime[0] * 1000 + hrTime[1] / 1000000;

    case 'micro':
      return hrTime[0] * 1000000 + hrTime[1] / 1000;

    case 'nano':
      return hrTime[0] * 1000000000 + hrTime[1];

    default:
      return hrTime[0] * 1000000000 + hrTime[1];
  }

};

0
投票

How to format a JavaScript date

看到这个链接,他们谈到toLocalDateString()函数,我认为这是你想要的。


0
投票

new Date()已经返回ISO格式的日期

console.log(new Date())

0
投票

对于像这样的ISO 8601

2019-03-05T10:27:43.113Z

console.log((new Date()).toISOString());

Date.prototype.toISOString()mdn

toISOString()方法以简化的扩展ISO格式(ISO 8601)返回一个字符串,该字符串总是24或27个字符(分别为YYYY-MM-DDTHH:mm:ss.sssZ±YYYYYY-MM-DDTHH:mm:ss.sssZ)。时区始终为零UTC偏移,由后缀“Z”表示。

你也可以这样做:

if (!Date.prototype.toISOString) {
  (function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        '-' + pad(this.getUTCMonth() + 1) +
        '-' + pad(this.getUTCDate()) +
        'T' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes()) +
        ':' + pad(this.getUTCSeconds()) +
        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  }());
}
© www.soinside.com 2019 - 2024. All rights reserved.