Reputation: 12007
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?
Upvotes: 17
Views: 36527
Reputation: 1
try
new \MongoDB\BSON\UTCDateTime($your_datetime)
or
new \MongoDB\BSON\UTCDateTime((new Datetime())->getTimestamp()*1000)
refer to this, I used this already.
Upvotes: 0
Reputation: 9407
The date-string is already in UTC
You might think your date is in UTC, as opposed to a local date time requiring a UTC offset. But it does not conform to the ISO 8601 international standard when dealing with time zones. When you want to specify a time zone, you must use a time zone designator. MongoDB stores dates in UTC format, and ISO requires a time zone designator of "Z" to represent UTC time.
To clarify things for you, in terms of ISO 8601, the time below is not stored in UTC time. This is stored in Paris, France local time with UTC offset of + 1 Hour.
1997-07-16T19:20:30.45+01:00
This below is stored in UTC time as specified by the Z. Thus, no + offset is required.
2019-08-01T23:00:34.655Z
MongoDB stores dates as follows:
ISODate("2019-08-05T02:50:49.637Z")
ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object.
Upvotes: 9
Reputation: 81
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/
Upvotes: 8