Rails Postgres 时区处理
我想要的简单的事情是将 UTC 格式的 DateTime 存储在数据库中,并再次以 UTC 格式检索它,但 Rails 似乎假设我将 DateTime 存储在本地时区并添加 8 小时差(PST)。我的模型中有一个日期时间字段。如果我发送请求 (PUT) 在模型的特定实例中更新此字段,则时区会因某种原因而混淆:
通过 PUT 发送到 Rails:2012-02-17T03:46:58Z
通过后续 GET 返回:2012 -02-17T11:46:58Z
时差正好是 8 小时,可以用我的时区(太平洋标准时间)来解释(-08:00)。
我在 Rails 3.1.3 上使用 Datamapper 1.2。
我将应用程序配置时区明确设置为 UTC。
我还尝试使用 dm-zone-types。没有为我改变任何东西。
我的存储库上的 git-bisect 显示,当我将数据库从原始 sqlite 切换到 postgres 时,引入了这种不当行为。此提交仅更改了database.yml和gemfile。没有别的了。
有什么想法吗?
The simple thing I want is to store a DateTime in UTC in the database and retrieve it in UTC again, but rails seems to assume I stored the DateTime in my local time zone and adds the 8 hours difference (PST). I have a DateTime field in my model. If I send a request (PUT) to update this field in a particular instance of my model, somehow timezones get mixed up for whatever reason:
Sending to rails via PUT: 2012-02-17T03:46:58Z
Returned via subsequent GET: 2012-02-17T11:46:58Z
The time difference is exactly 8 hours and could be explained by my timezone which is PST (-08:00).
I am using Datamapper 1.2 on Rails 3.1.3.
I set my application config timezone to UTC explicitly.
I also tried to use dm-zone-types. Did not change anything for me.
A git-bisect on my repo revealed, that this misbehavior was introduced as I switched the database to postgres from the original sqlite. This commit only changed the database.yml and the gemfile. Nothing else.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己找到了一个 hacky 解决方案:
将环境变量 TZ 中的服务器时区设置为“UTC”。为了保留这个配置选项,我决定将环境变量设置放在 config/boot.rb 中:
我仍然觉得很脏,这个解决方案仍然让我心烦意乱。因此,任何更好/更清洁的解决方案都将受到高度赞赏!
I have found a hacky solution myself:
Set the servers timezone in the environment variable TZ to 'UTC'. In order to persist this configuration option, I decided to put the environment variable setting in config/boot.rb:
I still feel dirty and this solution still gives me the willies. So any better/cleaner solution is highly appreciated!