如何在特定时区(最好是我的应用的默认时区而不是UTC)中创建新的DateTime对象? [英] How to create a new DateTime object in a specific time zone (preferably the default time zone of my app, not UTC)?

查看:99
本文介绍了如何在特定时区(最好是我的应用的默认时区而不是UTC)中创建新的DateTime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在 /config/application.rb 中设置了时区,并且我希望应用程序中生成的所有时间默认情况下都处于该时区。我创建了一个新的 DateTime 对象(使用 .new ),它在 GMT 。如何使其处于应用程序所在的时区?

I have set the time zone in /config/application.rb, and I expect all times generated in my app to be in this time zone by default, yet when I create a new DateTime object (using .new), it creates it in GMT. How can I get it to be in my app's time zone?

/config/application.rb

config.time_zone = 'Pacific Time (US & Canada)'

irb

irb> DateTime.now
=> Wed, 11 Jul 2012 19:04:56 -0700 

irb> mydate = DateTime.new(2012, 07, 11, 20, 10, 0)
=> Wed, 11 Jul 2012 20:10:00 +0000                    # GMT, but I want PDT

使用 in_time_zone 不起作用,因为这只是将GMT时间转换为PDT时间,这是错误的时间:

Using in_time_zone doesn't work because that just converts the GMT time to PDT time, which is the wrong time:

irb> mydate.in_time_zone('Pacific Time (US & Canada)')
=> Wed, 11 Jul 2012 13:10:00 PDT -07:00               # wrong time (I want 20:10)


推荐答案

您可以使用ActiveSupport的 TimeWithZone Time.zone )对象来创建和解析应用程序时区中的日期:

You can use ActiveSupport's TimeWithZone (Time.zone) object to create and parse dates in the time zone of your application:

1.9.3p0 :001 > Time.zone.now
 => Wed, 11 Jul 2012 19:47:03 PDT -07:00 
1.9.3p0 :002 > Time.zone.parse('2012-07-11 21:00')
 => Wed, 11 Jul 2012 21:00:00 PDT -07:00 

这篇关于如何在特定时区(最好是我的应用的默认时区而不是UTC)中创建新的DateTime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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