【问题标题】:How to convert date in to UTC in mongo DB如何在 mongo DB 中将日期转换为 UTC
【发布时间】:2021-02-10 06:11:48
【问题描述】:

我正在尝试将开始日期字段与当前日期进行比较,但“new Date()”被转换为本地时间。有人可以帮我将 new date() 转换为 UTC 日期格式,因为 startDate 字段与 UTC 日期一起存储在数据库中。


database.Models.EventModel.findOne({
    $and: [
      { 'status': 'Accepted' },
      { 'startDate': { $gte: new Date() } }
 ],
  }).sort('-startDate');

【问题讨论】:

  • 这能回答你的问题吗? How to get UTC Date object in NodeJS?
  • 不。我看不出使用 new Date(new Date().toUTCString()) VS new Date() 有什么区别。两者都呈现相同的输出。那篇文章中也有同样的评论。
  • 内部日期均为 UTC。本地化格式在 mongo 中被忽略。你可以和Date.now()比较,结果是一样的。您能否更详细地描述您的查询问题?也许有示例数据。您可能正在本地化插入日期
  • 当然。服务器采用 UTC,我们的日期以 UTC 格式存储。我正在尝试从数据库中获取开始日期大于或等于今天日期的所有记录。通过我上面提到的查询, new Date() 给了我当地时间。 EG:如果数据库中的 startTime 存储为 10 月 27 日 10 pm GMT 并且我的查询 new Date() 返回 10 月 27 日 3:18 pm GMT-7。当我的查询成功时,它返回 startDate 为 Oct 27th 10pm 的项目,这是错误的,因为 Oct 27th 10PM 小于 10 月 27 日 3:18pm GMT-7(10 月 27 日 10:18PM GMT)。希望我清楚地解释了我的问题
  • 您能否为非美国人使用国际 ISO 日期格式。 startDateDate 对象还是存储为字符串?

标签: node.js mongodb mongoose


【解决方案1】:

根据:When MongoDB inserts a date, it is converting it to UTC

MongoDB 默认以 UTC 存储时间,并将转换任何本地时间 时间表示成这种形式。必须运行的应用程序或 报告某些未修改的本地时间值可能会存储时区 在 UTC 时间戳旁边,并计算原始本地时间 他们的应用逻辑。

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2021-11-10
    • 2021-03-26
    相关资源
    最近更新 更多