1

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.

prime
  • 2,004
  • 3
  • 28
  • 45
  • 2
    I am confusing. are you expected to get miliseconds `1550657100120` or iso string `2019-02-20T10:05:00.120000Z` from date object – Ponleu Mar 05 '19 at 10:23
  • Either you mean milliseconds `[...].120Z` or microeconds `[...].120000Z`. Which one is it? – str Mar 05 '19 at 10:37

6 Answers6

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

};
OllysCoding
  • 312
  • 3
  • 11
mohit dutt
  • 31
  • 3
2
new Date("2019-02-20T10:05:00.120000").getTime()
Ajay yadav
  • 264
  • 2
  • 10
1

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
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

new Date() already returns an ISO formatted date

console.log(new Date())
AZ_
  • 3,094
  • 1
  • 9
  • 19
0

How to format a JavaScript date

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

0

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

  }());
}
user2226755
  • 12,494
  • 5
  • 50
  • 73