在 Rails 3中将 UTC 转换为本地时间

在 Rails 3中,我在将 UTC TimeTimeWithZone转换为本地时间时遇到了麻烦。

假设 moment是 UTC 中的某个 Time变量(例如 moment = Time.now.utc)。如何转换 moment到我的时区,照顾 DST (即使用 EST/EDT) ?

更准确地说,如果时间对应于美国东部时间今天上午9点,我想打印出“3月14日星期一上午9点”; 如果时间是美国东部时间上周一上午9点,我想打印出“3月7日星期一上午9点”。

希望还有别的办法?

编辑 : 我一开始以为,“ EDT”应该是一个可识别的时区,但是“ EDT”不是一个实际的时区,更像是一个时区的状态。例如,要求 Time.utc(2011,1,1).in_time_zone("EDT")是没有任何意义的。这有点令人困惑,因为“ EST”是一个实际的时区,在一些不使用夏令时并且(UTC-5)一年长的地方使用。

113390 次浏览

Time#localtime will give you the time in the current time zone of the machine running the code:

> moment = Time.now.utc
=> 2011-03-14 15:15:58 UTC
> moment.localtime
=> 2011-03-14 08:15:58 -0700

Update: If you want to conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is EDT or EST:

> Time.now.utc.in_time_zone("Eastern Time (US & Canada)")
=> Mon, 14 Mar 2011 11:21:05 EDT -04:00
> (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)")
=> Sat, 14 Jan 2012 10:21:18 EST -05:00

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

There is actually a nice Gem called local_time by basecamp to do all of that on client side only, I believe:

https://github.com/basecamp/local_time

Don't know why but in my case it doesn't work the way suggested earlier. But it works like this:

Time.now.change(offset: "-3000")

Of course you need to change offset value to yours.

It is easy to configure it using your system local zone, Just in your application.rb add this

config.time_zone = Time.now.zone

Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime

Post.created_at.localtime

If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb.

Like this:

Rails, by default, will save your time record in UTC even if you specify the current timezone.

config.time_zone = "Singapore"

So this is all you have to do and you're good to go.