代码之家  ›  专栏  ›  技术社区  ›  prime

在节点中生成毫秒时间戳

  •  1
  • prime  · 技术社区  · 7 年前

    有人能告诉我如何在Node中生成以下类型的日期时间戳吗?

    2019-02-20T10:05:00.120000Z
    

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

    5 回复  |  直到 7 年前
        1
  •  1
  •   kockburn    7 年前

    使用 Date#toISOString

    const res = (new Date()).toISOString();
    
    console.log(res); // i.e 2019-03-05T10:15:15.080Z
        2
  •  2
  •   Ajay yadav    7 年前
    new Date("2019-02-20T10:05:00.120000").getTime()
    
        3
  •  2
  •   OllysCoding    7 年前
    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];
      }
    
    };
    
        4
  •  0
  •   hardy charles    7 年前

    How to format a JavaScript date

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

        5
  •  0
  •   arizafar    7 年前

    console.log(new Date())
        6
  •  0
  •   user2226755    7 年前

    为了 ISO 8601 就像这样:

    2019-03-05T10:27:43.113Z

    console.log((new Date()).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';
        };
    
      }());
    }