将时间从Rails中的一个时区转换到另一个时区 [英] Convert Time from one time zone to another in Rails

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

问题描述

我的 created_at 时间戳记以UTC存储:

My created_at timestamps are stored in UTC:

>> Annotation.last.created_at
=> Sat, 29 Aug 2009 23:30:09 UTC +00:00

如何转换他们是东部时间(美国和加拿大)(考虑到夏令时)?如下所示:

How do I convert one of them to 'Eastern Time (US & Canada)' (taking into account daylight savings)? Something like:

Annotation.last.created_at.in_eastern_time


推荐答案

使用DateTime类的in_time_zone方法

Use the in_time_zone method of the DateTime class

Loading development environment (Rails 2.3.2)
>> now = DateTime.now.utc
=> Sun, 06 Sep 2009 22:27:45 +0000
>> now.in_time_zone('Eastern Time (US & Canada)')
=> Sun, 06 Sep 2009 18:27:45 EDT -04:00
>> quit

所以对于你的具体例子

Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)')

这篇关于将时间从Rails中的一个时区转换到另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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