保存Rails中的时区 [英] Preserving timezones in Rails

查看:105
本文介绍了保存Rails中的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个来自客户端的时间字符串形式Wed,22 Jun 2011 09:43:58 +0200,我希望存储它时区保留。这很重要,因为它不仅仅是绝对的UTC时间是重要的,而且是时区。

If I have a time string of the form "Wed, 22 Jun 2011 09:43:58 +0200" coming from a client, I wish to store it with the time zone preserved. This is important because it's not just the absolute UTC time that is important but also the timezone.

Time.zone.parse(t) code>将把时间转换为当时正在使用的 Time.zone 的区域,丢失源时区。

Time.zone.parse(t) will convert the time to whatever the zone that Time.zone is using at the time, losing the source timezone.

我是否必须从上述字符串中手动提取时区,或者是否有惯用的方法来执行此操作?

Do I have to manually extract the timezone from the above string or is there an idiomatic way to do this?

推荐答案

DateTime字段只能存储YYYY-MM-DD HH:MM:SS( MySQL ),没有时区信息。

A DateTime field can only store 'YYYY-MM-DD HH:MM:SS' (MySQL), no Time Zone info.

您应该将datetime存储在UTC中,并将时区存储在不同的字段中,最好是一个整数,指定UTC的偏移量,以分钟为单位。

You should store the datetime in UTC, and the Timezone in a different field, preferably as an integer specifying the offset from UTC in minutes.

您可以像这样提取偏移量:

You can extract the offset like this:

ruby-1.9.2-p180:001:0>> require 'active_support/all' # included by Rails by default
# => true
ruby-1.9.2-p180:002:0>> dt = DateTime.parse "Wed, 22 Jun 2011 09:43:58 +0200"
# => Wed, 22 Jun 2011 09:43:58 +0200
ruby-1.9.2-p180:003:0>> dt.utc_offset
# => 7200
ruby-1.9.2-p180:004:0>> dt.utc
# => Wed, 22 Jun 2011 07:43:58 +0000

编辑:

和往返行程

ruby-1.9.2-p180 :039 > u.utc.new_offset(u.offset)
=> Wed, 22 Jun 2011 09:43:58 +0500 
ruby-1.9.2-p180 :040 > u
=> Wed, 22 Jun 2011 09:43:58 +0500 

这篇关于保存Rails中的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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