当MongoDB插入日期时,它会将其转换为UTC [英] When MongoDB inserts a date, it is converting it to UTC
问题描述
我有一个字符串格式的日期,我试图以 DateTime
类型进入 MongoDB .日期字符串已经在 UTC 中,并且格式为 2017-11-30 19:41:00:677
.
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
.
当插入MongoDB时,我正在插入数据:
When inserting into MongoDB, I am inserting the data:
{
"timestamp": new Date("2017-11-30 19:41:00:677"),
...
}
但是,当我这样做时,日期似乎被认为是当地时间,而Mongo通过添加4小时将其转换为UTC.但是 19:41 已经在UTC中.
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.
如何告诉Mongo时区已经在UTC中?
推荐答案
日期字符串已经使用UTC
The date-string is already in UTC
您可能会认为您的日期使用UTC,而不是需要UTC偏移的本地日期时间.但是在处理时区时,它不符合ISO 8601国际标准.当您想要指定时区时,必须使用时区指示符.MongoDB以UTC格式存储日期,ISO要求使用时区标记"Z"来表示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.
为便于您进行说明,根据ISO 8601,以下时间未存储在UTC时间中.该时间存储在法国巴黎的当地时间,UTC时间为+ 1小时.
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
以下将其存储在Z指定的UTC时间中.因此,不需要+偏移.
This below is stored in UTC time as specified by the Z. Thus, no + offset is required.
2019-08-01T23:00:34.655Z
MongoDB存储日期如下:
MongoDB stores dates as follows:
ISODate("2019-08-05T02:50:49.637Z")
ISODate()是MongoDB内置的一个辅助函数,它包装了本机JavaScript Date对象.
ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object.
这篇关于当MongoDB插入日期时,它会将其转换为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!