在 Rails 3 中将 UTC 转换为本地时间 [英] Convert UTC to local time in Rails 3
问题描述
我在 Rails 3 中将 UTC Time
或 TimeWithZone
转换为本地时间时遇到问题.
I'm having trouble converting a UTC Time
or TimeWithZone
to local time in Rails 3.
说 moment
是 UTC 中的一些 Time
变量(例如 moment = Time.now.utc
).我如何将 moment
转换为我的时区,注意 DST(即使用 EST/EDT)?
Say moment
is some Time
variable in UTC (e.g. moment = Time.now.utc
). How do I convert moment
to my time zone, taking care of DST (i.e. using EST/EDT)?
更准确地说,如果时间对应于美国东部时间今天上午 9 点,我想打印3 月 14 日星期一上午 9 点";如果时间是美国东部时间上周一上午 9 点,我想打印3 月 7 日星期一上午 9 点".
More precisely, I'd like to printout "Monday March 14, 9 AM" if the time correspond to this morning 9 AM EDT and "Monday March 7, 9 AM" if the time was 9 AM EST last monday.
希望有另一种方式吗?
编辑:我首先想到EDT"应该是一个公认的时区,但EDT"并不是一个实际的时区,更像是一个时区的状态.例如,要求 Time.utc(2011,1,1).in_time_zone("EDT")
没有任何意义.这有点令人困惑,因为EST"是一个实际的时区,在一些不使用夏令时并且是 (UTC-5) 一年的地方使用.
Edit: I first thought that "EDT" should be a recognized timezone, but "EDT" is not an actual timezone, more like the state of a timezone. For instance it would not make any sense to ask for Time.utc(2011,1,1).in_time_zone("EDT")
. It is a bit confusing, as "EST" is an actual timezone, used in a few places that do not use Daylight savings time and are (UTC-5) yearlong.
推荐答案
Rails 有自己的名字.通过以下方式查看它们:
Rails has its own names. See them with:
rake time:zones:us
您还可以为所有时区运行 rake time:zones:all
.要查看更多与区域相关的 rake 任务:rake -D time
You can also run rake time:zones:all
for all time zones.
To see more zone-related rake tasks: rake -D time
因此,要转换为 EST,自动适应 DST:
So, to convert to EST, catering for DST automatically:
Time.now.in_time_zone("Eastern Time (US & Canada)")
这篇关于在 Rails 3 中将 UTC 转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!