Alappin
Alappin

Reputation: 684

Storing dates in mongodb with javascript

Whilst experimenting with mongodb and javascript on the MEAN stack. I came across an issue when it came to dealing with the dates, so I am interested in hearing how others have tackled this kind of scenario.

Lets say I have three dates I want to store in mongodb, a "date of birth", an "account creation" date and "last visit" date.

Now If I save all of these dates as normal Javascript date objects in mongodb, they are saved as UTC. The following then ensues:

  1. "date of birth" is no longer correct if presented to the user as it was recalculated to UTC.

  2. "account creation" is ok since its being used internally as long as its consitently UTC.

  3. "last visit" is no longer correct if presented to the user as it was recalculated to UTC.

So faced with the dilemna of trying to avoid storing dates as strings but at the same time not willing to battle timezone complexities. What would be the best compromise to deal with this scenario in terms capturing, storing and then presenting the dates??

Upvotes: 0

Views: 87

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151220

All date creation is not equal. An example:

What you likely did:

new Date("2014/01/01")
ISODate("2014-01-01T13:00:00Z")

And that factored the timezone difference into the date generated.

What you want to do:

new Date("2014-01-02")
ISODate("2014-01-02T00:00:00Z")

Which is exactly in UTC format.

So make sure you record such things as a UTC format when you create them.

Upvotes: 1

Related Questions