0

I am trying to compare the start date field with current date but "new Date()" is converted to local time. Can someone help me to convert new date() into UTC date format since startDate field is stored with UTC dates in the database.


database.Models.EventModel.findOne({
    $and: [
      { 'status': 'Accepted' },
      { 'startDate': { $gte: new Date() } }
 ],
  }).sort('-startDate');

Manju
  • 21
  • 2
  • 9
  • Does this answer your question? [How to get UTC Date object in NodeJS?](https://stackoverflow.com/questions/49646303/how-to-get-utc-date-object-in-nodejs) – ndogac Oct 27 '20 at 21:52
  • Nope. I don't see any difference using new Date(new Date().toUTCString()) VS new Date(). Both rendered the same output. The same is commented in that article as well. – Manju Oct 27 '20 at 22:07
  • 1
    Date's are all UTC internally. The localised formatting is ignored in mongo. You can compare with `Date.now()` and the result will be the same. Can you describe your issue with the query in a bit more detail? Maybe with example data. You might be localising a date on insertion – Matt Oct 27 '20 at 22:09
  • sure. Server is in UTC and our dates are stored in UTC format. I am trying to get all records from database whose start date is greater than or equal to today's date. With the query I mentioned above, new Date() is giving me the local time. EG: If startTime in database is stored as Oct 27 10pm GMT and my query new Date() is returning Oct 27 3:18pm GMT-7. When my query succeeds, it returns the item whose startDate is Oct 27th 10pm which is wrong since Oct 27th 10PM is less than Oct 27th 3:18pm GMT-7 (Oct 27th 10:18PM GMT). Hope I explained my question clearly – Manju Oct 27 '20 at 22:25
  • Can you please use the international ISO date format for the non-americans. Is `startDate` a `Date` object or are they stored as strings? – Wernfried Domscheit Oct 28 '20 at 07:36

1 Answers1

1

As per: When MongoDB inserts a date, it is converting it to UTC

MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.

https://docs.mongodb.com/v3.2/tutorial/model-time-data/

new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date(<integer>) specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.