Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When MongoDB inserts a date, it is converting it to UTC

I have a date in string format, that I am trying to get into MongoDB as a DateTime type. The date-string is already in UTC, and is in the format 2017-11-30 19:41:00:677.

When inserting into MongoDB, I am inserting the data:

{
    "timestamp": new Date("2017-11-30 19:41:00:677"),
    ...
}

However, when I do this, the date is thought to be local time (it seems), and Mongo converts it to UTC by adding 4 hours. Yet the 19:41 is already in UTC.

How can I tell Mongo that the timezone is already in UTC?

like image 446
Brett Avatar asked Nov 30 '17 22:11

Brett


People also ask

Does MongoDB convert date to UTC?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

Is new date () UTC or local?

getTime() returns the number of milliseconds since 1970-01-01. If you create a new Date using this number, ex: new Date(Date. getTime()); it will be UTC, however when you display it (ex: through the chrome dev tools console) it will appear to be your local timezone.

What is the format of date in MongoDB?

These functions accept the following formats: 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.

What is UTC in date format?

UTC() takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between 0 and 99 are converted to a year in the 20th century (1900 + year) . For example, 95 is converted to the year 1995 .


1 Answers

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/

like image 126
user9036266 Avatar answered Oct 19 '22 11:10

user9036266