【问题标题】:MongoDB: how come these Date objects are differentMongoDB:这些 Date 对象为什么不同
【发布时间】:2014-03-19 17:17:54
【问题描述】:

我有兴趣在我的 MongoDB 日期字段中获取时区偏移量。在一台机器上使用MongoDB 2.4.9,我看到以下内容,这是我希望存储日期的方式:

NOVUSNYCLK67(mongod-2.4.9) test_salat> db.scala_date_test_1.find().toArray()
[
  {
    "_id": ObjectId("5329bf52e4b089adba4e75ec"),
    "_typeHint": "com.novus.salat.test.model.Neville",
    "ennui": true,
    "asOf": ISODate("2014-03-19T12:01:22.355-0400")
  }
]

请注意此处ISODate()-0400 片段。在另一台机器上,它看起来像以下(错误的方式):

> db.scala_date_test_1.find().toArray()
[
    {
        "_id" : ObjectId("5329c755c026b6d16dc5972b"),
        "_typeHint" : "com.novus.salat.test.model.Neville",
        "ennui" : true,
        "asOf" : ISODate("2014-03-19T16:35:33.474Z")
    }
]

我使用Mongoid 来保留这些日期(Ruby gem),但我只想知道如何在我的日期中获取时区偏移量,因此它们的格式如下:

"asOf": ISODate("2014-03-19T12:01:22.355-0400")

不喜欢:

"asOf" : ISODate("2014-03-19T16:35:33.474Z")

【问题讨论】:

标签: ruby mongodb mongoid


【解决方案1】:

来自documentation

配置选项

Mongoid 目前支持以下配置选项,或者 在mongoid.yml 中提供或以编程方式提供(默认为 括号)。

...剪辑...

  • use_activesupport_time_zone(true):当在 Rails 应用程序中时,会告诉 Mongoid 将应用程序中的所有时间转换为本地定义的 Active Support 中的时区。
  • use_utc(false):指示 Mongoid 在所有情况下都将所有时间转换为 UTC 时间。

使用您的mongoid.yml 来配置适合您的选项。另外,请参阅此问题:How to save a timezone correctly with Ruby and MongoId?:

您可能还想在 config/mongoid.yml 中设置以下内容

defaults: &defaults
  use_utc: false
  use_activesupport_time_zone: true

这听起来违反直觉,但这是目前的制作方法 mongoid 使用 UTC 作为默认时区。

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多