【问题标题】:How to get current date in a specific time zone in Mongodb Aggregate 3.2如何在 Mongodb Aggregate 3.2 中获取特定时区的当前日期
【发布时间】:2020-11-04 00:16:09
【问题描述】:

我正在尝试根据日期条件评估聚合查询,因为我想要一个状态变量来告诉系统是打开还是关闭。如果日期、时间结束,则状态为关闭,否则为打开状态。

我正在尝试获取可以使用 new Date() 获取的当前日期。但是我怎样才能转换到特定的时区。我在更高版本的 mongodb 中找到了 dateToString。

但我的数据库版本是 3.2

db.getCollection('testCollection').aggregate([
{"$project":{
    "_id":1,
    "startDate":1,
    "endDate":1,
   "currentDate":new Date()
}}
])

我能够获取日期,但无法将其转换为时区。 有没有类似的东西

"currentDate":new Date("Asia/Kolkata")

【问题讨论】:

  • 您能否稍微细化这个问题,以更清楚地了解您希望如何查询数据与如何格式化/查看数据?在您的帖子中,您似乎想查询,但您的 agg 中没有 $match,只有 $project

标签: mongodb mongodb-query


【解决方案1】:

由于它是旧版本,您必须进行一些计算才能将其转换为您的timezone。下面是示例聚合查询,其中'x'UTC 和您的timezone 之间以小时为单位偏移。

db.getCollection('testCollection').aggregate([
    {"$project":{
        "_id":1,
        "startDate":1,
        "endDate":1,
        "currentDate":new Date(),
        "day": { "$dayOfMonth": {"$add": [ new Date(), x * 60 * 60 * 1000 ]}},
        "month": { "$month": { "$add": [ new Date(), x * 60 * 60 * 1000 ]}},
        "year": { "$year": { "$add": [ new Date(), x * 60 * 60 * 1000 ]}}
        "hour": { "$hour": {"$add": [ new Date(), x * 60 * 60 * 1000 ]}},
        "minute": { "$minute": { "$add": [ new Date(), x * 60 * 60 * 1000 ]}},
        "second": { "$second": { "$add": [ new Date(), x * 60 * 60 * 1000 ]}}
    }}
])

【讨论】:

  • 我现在只有这种格式的时区,这是表中的一个字段.. 'America/New_York' 或 'Asia/Kolkata'
【解决方案2】:

不,没有。 MongoDB 严格以“Z”模式存储、获取和查询日期时间:自 GMT 纪元以来的毫秒数。无论您的本地程序如何解释它,您插入的任何日期都将被解释为 Z 日期。

【讨论】:

猜你喜欢
  • 2016-09-27
  • 2021-12-16
  • 2011-12-21
  • 2019-10-01
  • 2020-05-27
  • 2022-11-24
  • 2014-09-08
  • 1970-01-01
相关资源
最近更新 更多