Rhys Edwards
Rhys Edwards

Reputation: 791

Date object and ISO date object return different dates

I need to capture a date value, parse it to an ISODate and then query a mongoDB collection that stores an object with a date value. The query checks for equality between the date of an event and matches it against a function that determines if the date will fall on a weekend. Everything works, however if the date falls on a Monday, it will also come through on the results.

Something I have noticed is the date object moves back a day when we use toISOString:

Date Obj

Mon Apr 18 2016 00:00:00 GMT+0100 (BST)

toISOString:

2016-04-17T23:00:00.000Z

Notice it now has the 17th as the date?

This inconsistency exists in the DB as well:

{
    "_id" : ObjectId("56fe91afceb044f551dbffce"),
    "url" : "http://www.timeoutshanghai.com/features/Blog-Food__Drink/35271/Baristas-showcase-latte-art-in-Shanghai.html",
    "title" : "Baristas showcase latte art in Shanghai - Blog - Time Out - Shanghai",
    "selectedDate" : ISODate("2016-04-17T23:00:00Z"), 
    "__v" : 0
}

This should give selectedDate" : ISODate("2016-04-17T23:00:00Z")

However if we log the collection to the console, the date is returned as a Monday:

  { _id: 56fe91c5ceb044f551dbffcf,
    url: 'http://www.timeoutshanghai.com/features/Blog-Food__Drink/35271/Baristas-showcase-latte-art-in-Shanghai.html',
    title: 'Baristas showcase latte art in Shanghai - Blog - Time Out - Shanghai',
    selectedDate: Mon Apr 18 2016 00:00:00 GMT+0100 (BST),
    __v: 0 },

This becomes an issue when I query the DB to only return events on a weekend as the Monday's are slipping through.

Upvotes: 0

Views: 634

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

You have 2 different timezones:

  • toISOString() returns the date formatted in UTC+00:00, which is indicated by the Z flag at the end 2016-04-17T23:00:00.000Z.
  • Your date object Mon Apr 18 2016 00:00:00 GMT+0100 (BST) (probably formatted using toString()) is formatted in you current timezone: GMT+01:00.

That's why you get this difference in 1 hour.
Read more about the iso date format.

Upvotes: 4

Related Questions