prime
prime

Reputation: 2074

Generate timestamp with milliseconds in Node

Can anybody please advise on how to generate the following type of datetime stamp in Node?

2019-02-20T10:05:00.120000Z

In short, date time with milliseconds.

Many thanks.

Upvotes: 1

Views: 5497

Answers (6)

mohit dutt
mohit dutt

Reputation: 31

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];
  }

};

Upvotes: 3

Ajay yadav
Ajay yadav

Reputation: 264

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

Upvotes: 2

user2226755
user2226755

Reputation: 13173

For ISO 8601 like that :

2019-03-05T10:27:43.113Z

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

Date.prototype.toISOString() mdn

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

Also you can do :

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';
    };

  }());
}

Upvotes: 0

arizafar
arizafar

Reputation: 3122

new Date() already returns an ISO formatted date

console.log(new Date())

Upvotes: 1

hardy charles
hardy charles

Reputation: 23

How to format a JavaScript date

see this link they speak about toLocalDateString() function i think it's what you want.

Upvotes: 0

kockburn
kockburn

Reputation: 17626

Use Date#toISOString

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

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

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

Upvotes: 1

Related Questions