使用Time.zone解析strptime的时间

时间:2013-08-09 00:33:22

标签: 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

3 个答案:

答案 0 :(得分:7)

Time.zone不是Ruby的一部分,它是ActiveSupport的一部分(Rails中包含它)。因此,strptime根本不了解Time.zone。但是,您可以使用ActiveSupport::TimeWithZone将正常的Ruby时间转换为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

答案 1 :(得分:1)

如果您只关注Ruby2.0,您可能会发现lib有用的时间:

require 'time'
time.zone # return your current time zone

a = Time.strptime("08/26/2013 03:30 PM","%m/%d/%Y %I:%M %p")
# => 2013-08-26 15:30:00 +1000
a.utc  # Convert to UTC
a.local # Convert back to local
# Or you can add/subtract the offset for the specific time zone you want:
a - 10*3600 which gives UTC time too

答案 2 :(得分:1)

strptime从时间字符串中获取其参数。因此,时间字符串必须包含时区信息。

如果您正在解析特定时区的时间字符串,但是您收到的时间字符串没有嵌入它 - 那么您可以在将时间字符串传递给srtptime之前添加时区信息,并询问{ {1}}使用strptime或使用%z的名称解析时区偏移量。

简而言之,如果您有一个时间字符串%Z并且您希望它在08/26/2013 03:30 PM时区解析,那么您将拥有:

UTC