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?
MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.
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.
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.
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 .
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With