使用Time.zone解析strptime的时间

use*_*674 9 ruby datetime activesupport

我试图用Ruby 2.0中的Time类解析日期时间.我无法弄清楚如何解析日期并在指定的时区得到它.我曾经Time.zone.parse解析过我第一次打电话的日期Time.zone并将其设置为指定的时区.在下面的例子中,我设置了区域,但它没有效果strptime,我已经尝试过,Time.zone.parse(date)但是我无法解析它如下所示的日期.

Time.zone = "Central Time (US & Canada)"
#=> "Central Time (US & Canada)"
irb(main):086:0> Time.strptime("08/26/2013 03:30 PM","%m/%d/%Y %I:%M %p")
#=> 2013-08-26 15:30:00 -0400
Run Code Online (Sandbox Code Playgroud)

And*_*all 8

Time.zone它不是Ruby的一部分,它是ActiveSupport的一部分(它包含在Rails中).因此,strptime根本不知道Time.zone.你可以,但是,将普通的Ruby的时间到的ActiveSupport :: TimeWithZone使用in_time_zone,它使用Time.zone默认的值:

require 'active_support/core_ext/time'
Time.zone = 'Central Time (US & Canada)'

time = Time.strptime('08/26/2013 03:30 PM', '%m/%d/%Y %I:%M %p')
#=> 2013-08-26 15:30:00 -0400
time.in_time_zone
#=> Mon, 26 Aug 2013 14:30:00 CDT -05:00
Run Code Online (Sandbox Code Playgroud)