Manju
Manju

Reputation: 21

How to convert date in to UTC in mongo DB

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');

Upvotes: 0

Views: 3855

Answers (1)

user14518353
user14518353

Reputation:

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.

Upvotes: 1

Related Questions