Mongoose: Date type returns date-1 (date minus one day)

Created on 1 Mar 2012  路  4Comments  路  Source: Automattic/mongoose

I have the User Schema and the following instance
user = new UsersCollection({
email: "[email protected]",
title: "Mr.",
first_name: "Chuck",
last_name: "Norris",
birthday: "26 August 1983"
});

The date type works perfectly when casting from any input format. The only problem was that the saved date would be moved to one day earlier.

Did not have time to investigate deeper. The solution I made was to change /lib/schema/date.js line 62 to

if (date.toString() != 'Invalid Date')
return date+1;

Most helpful comment

I'm encountering this issue myself, and may be able to help. Consider the following:
> (new Date(Date.parse("2014-10-27"))).toString()
'Sun Oct 26 2014 20:00:00 GMT-0400 (EDT)'
> (new Date(Date.parse("2014-10-27"))).toISOString()
'2014-10-27T00:00:00.000Z'

When entering a date without a time, JavaScript sets the time to midnight, GMT. I'm located in Toronto, so when toString() is called on that Date object, the date object is shifted back in time in time to EDT (which is 4 hours behind GMT).

Explicitly fixing your timezone to the string should solve the problem. For example:
> (new Date(Date.parse("2014-10-27 EDT"))).toString()
'Mon Oct 27 2014 00:00:00 GMT-0400 (EDT)'
> (new Date(Date.parse("2014-10-27 EDT"))).toISOString()
'2014-10-27T04:00:00.000Z'

All 4 comments

without more info i cannot reproduce.

I'm encountering this issue myself, and may be able to help. Consider the following:
> (new Date(Date.parse("2014-10-27"))).toString()
'Sun Oct 26 2014 20:00:00 GMT-0400 (EDT)'
> (new Date(Date.parse("2014-10-27"))).toISOString()
'2014-10-27T00:00:00.000Z'

When entering a date without a time, JavaScript sets the time to midnight, GMT. I'm located in Toronto, so when toString() is called on that Date object, the date object is shifted back in time in time to EDT (which is 4 hours behind GMT).

Explicitly fixing your timezone to the string should solve the problem. For example:
> (new Date(Date.parse("2014-10-27 EDT"))).toString()
'Mon Oct 27 2014 00:00:00 GMT-0400 (EDT)'
> (new Date(Date.parse("2014-10-27 EDT"))).toISOString()
'2014-10-27T04:00:00.000Z'

Same here.
From facebook API I get: birthday: '05/28/1987'
Then when I look into the DB: birthday: '1987-05-27 22:00:00.000Z'

Also the 22:00:00 I cannot understand

@Onheiron time zone issues. Looks like you're in UTC +2. Convert your date string to '1987-05-28 00:00:00.000Z' and you'll get the right date in the db.

Was this page helpful?
0 / 5 - 0 ratings