如何使用Ruby和MongoId正确保存时区? [英] How to save a timezone correctly with Ruby and MongoId?

查看:52
本文介绍了如何使用Ruby和MongoId正确保存时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个菜鸟问题,请原谅:

Please excuse me if this is a bit of a noob issue:

我有一个应用程序,用户可以在其个人资料中设置自己的时区.

I have an app where users can set their own Timezones in their profile.

当有人添加阵容(应用特定术语)时,我将执行以下操作:

When someone adds a Lineup (app specific terminology), I do the following:

time = ActiveSupport::TimeZone.new(user.timezone).parse(
  "Wednesday, 26 October, 2011 13:30:00"
)

# This outputs: 2011-10-26 13:30:00 +0200 - valid according to the user selected TZ

然后我保存阵容:

Lineup.create({
   :date => time.gmtime,
   :uid  => user._id,
   :pid  => product._id
})

(理论上)这应该将日期另存为gmtime,但是在查看记录时会得到以下信息:

This should (in theory) save the date as gmtime, but I get the following when viewing the record:

{
  "_id": ObjectId("4e9c6613e673454f93000002"),
  "date": "Wed, 26 Oct 2011 13: 30: 00 +0200",
  "uid": "4e9b81f6e673454c8a000001",
  "pid": "4e9c6613e673454f93000001",
  "created_at": "Mon, 17 Oct 2011 19: 29: 55 +0200"
}

如您所见,日期字段是错误的-它仍保持用户时区,应为GMT,而不是时区特定.

As you can see the date field is wrong - it still maintaining the user timezone, it should be GMT, not timezone specific.

如果我输出time.gmtime,我会得到正确的时间(应该保存):

If I output time.gmtime, I get the right time (that should be saved):

2011-10-26 11:30:00 UTC (correct)

有什么主意如何保存格林尼治标准时间,以便它实际上保存格林尼治标准时间?

Any ideas how to save the GMT date so that it actually saves the GMT date?

推荐答案

您似乎需要指定date属性的字段类型.如果您想让Mongoid正确处理区域,则可以使用时间"字段.

It looks like you need to specify the field type of your date attribute. I would use a Time field if you want mongoid to handle the zones properly.

class Lineup
  include Mongoid::Document
  field :date, type: Time
end

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

You will also probably want to set the following in config/mongoid.yml

defaults: &defaults
  use_utc: false
  use_activesupport_time_zone: true

这听起来有悖常理,但这是使蒙古族使用UTC作为默认时区的当前方法.

This sounds counterintuitive, but this is the current way to make mongoid use UTC as the default timezone.

最后,看看 mongoid-metastamp 宝石.它将为您提供对跨多个时区的查询的更好支持,同时仍可以像本机时间"字段一样无缝地工作.

Finally, have a look at the mongoid-metastamp gem. It will give you much better support for querying across multiple timezones, while still seamlessly working like a native Time field.

这篇关于如何使用Ruby和MongoId正确保存时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆