ubuntu7788
ubuntu7788

Reputation: 115

How to convert mongodb timestamps to an actual date?

I have createdAt propery like this: 2020-03-30T12:44:20.221+00:00. Now, I want something like 30 march 2020. Is it possible? I don't need the time and timezone, just the date. Thanks.

Upvotes: 0

Views: 4551

Answers (2)

RobG
RobG

Reputation: 147343

You say "I don't need the time and timezone, just the date", however 2020-03-30T12:44:20.221+00:00 has a zero offset so is effectively UTC. Depending on the time in the timestamp and host timezone offset, using non–UTC methods may produce a date that is a day either side of the UTC date if it's within the local timezone offset of midnight.

E.g.

let formatLocal = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit'});
let formatUTC   = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit', timeZone:'UTC'});

// Timestamps
['2020-03-30T12:44:20.221+00:00', // from OP
 '2020-03-30T00:04:00.000+00:00', // Just after midnight UTC
 '2020-03-29T23:54:00.000+00:00'  // Just before midnight UTC
].forEach(s => {
  let d = new Date(s);
  console.log(
   `${s}\nLocal: ${formatLocal.format(d)}\nUTC  : ${formatUTC.format(d)}`
  );
});

The local date for either the 2nd or 3rd example above should be offset by a day from the UTC date.

Upvotes: 0

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Use the Date constructor:

var createdAt = "2020-03-30T12:44:20.221+00:00"
var date = new Date(createdAt)
console.log(date.getDate() +  " " + date.toLocaleString('default', { month: 'long' }) + " " + date.getFullYear())

// Or even more concise (Thanks @RobG)
console.log(date.toLocaleString('en-GB', {day:'numeric', month: 'long', year:'numeric'}))

Upvotes: 1

Related Questions