cr0
cr0

Reputation: 617

How to correctly jsonify a mongoose model with a birthday?

How can I store a birthday like 09/14/1986 with mongoose and convert it to json with toJSON while ignoring the timezone?

Assume you have a schema like

schema = new mongoose.Schema({
  birthday: Date
});

and you store the birthday above, mongoose actually stores it as Date(527032800000). Now when you call toJSON on the model it is converted with JSON.stringify. Dates are converted to a string with toISOString which results in 1986-09-13T22:00:00.000Z (on a machine with a german timezone setting: Europe/Berlin). As you can see, this is not the date we might expect for a birthday because the timezone is interpreted (See a similar problem here).

What to do? I don't want to lose the comfort of parsing various birthdaystrings and the use of mongoose's toJSON.

Upvotes: 1

Views: 1496

Answers (1)

Baradzed
Baradzed

Reputation: 578

The problem is in the way your date gets created. I suggest you use dates in UTC-time for such data as birthdays, which would allow you to use UTC-times throughout the system.

You can either:

  • set the date in UTC in the constructor, supplying to it a string in UTC: new Date('1986-09-14T00:00:00.000Z');
  • use new Date(Date.UTC(year, month, day, 0, 0, 0)); to create a Date-object from an integer year, month and day.

So, the answer is: you should store UTC date in birthday field when you create/update the model.

Upvotes: 1

Related Questions