Sahil Narula
Sahil Narula

Reputation: 1

Change date format in express using mongoose

I stored date in database but whenever i am fetching then its format change

getting date -      2018-07-31T06:48:01.649Z
stored date in db - 2018-07-31 12:18:01.649

here is my code

var timee = result.created;

Upvotes: 0

Views: 462

Answers (1)

Shivam Pandey
Shivam Pandey

Reputation: 3936

By default, dates are stored in UTC in MongoDB so you are seeing the difference in the time zone of stored and retrieved dates.

new Date() returns the current date as a Date object. The mongo shell wraps the Date object with the ISODate helper. The ISODate is in UTC.

You can read the MongoDB specification here.

There are several approaches that you can apply. Either convert the date to UTC timezone before saving it or convert into locale time zone after loading the date.

new Date(ISODate().toString() + 'UTC')

ISODate("2018-08-01T11:39:39Z")

and to replace the T and Z with an empty space using the javascript.

dateString.replace("T", " ").replace("Z", " ");

Upvotes: 1

Related Questions