【问题标题】:Take separate time and timezone strings, and convert into UTC采用单独的时间和时区字符串,并转换为 UTC
【发布时间】:2018-04-28 21:08:02
【问题描述】:

我知道很多使用 Ruby 将本地时间转换为 UTC 时间的方法,但是当时间和区域是单独的数据片段时,我不确定如何执行此操作。如果我有类似“12:00 PM -0500”的内容,我可以使用.getutc() 轻松地将其转换为 UTC。但是,如果我有“12:00 PM”和“东部时间(美国和加拿大)”怎么办?如何将这两者结合起来找到 UTC 时间?

【问题讨论】:

  • 我有“12:00 PM”和“东部时间(美国和加拿大)”——那是两个字符串吗?
  • @Stefan 是的,这是两个字符串
  • 这些字符串从何而来?

标签: ruby datetime timezone timezone-offset


【解决方案1】:

如果您使用的是 Rails,或者您不介意需要 ActiveSupport,则可以使用 ActiveSupport::TimeZone 来执行此操作。

>> time_zone = "Eastern Time (US & Canada)"
>> time_without_zone = "12:00 PM"
>> ActiveSupport::TimeZone[time_zone].parse(time_without_zone)
#=> Wed, 15 Nov 2017 12:00:00 EST -05:00

【讨论】:

    【解决方案2】:

    DateTime::parse 方法可能正是您所需要的。

    x = DateTime.parse("12:00 PM Eastern Time (US & Canada)")
    

    将返回结果

    #<DateTime: 2017-11-15T12:00:00-05:00 ((2458073j,61200s,0n),-18000s,2299161j)> 
    

    从那里,有很多方法可以将时间转换为 UTC。例如,

    utc = x.new_offset(0)
    

    将返回结果

    #<DateTime: 2017-11-15T17:00:00+00:00 ((2458073j,61200s,0n),+0s,2299161j)>
    

    【讨论】:

    • 这需要一个标准库require 'datetime'。我也将转换为 Time afterwards to_time
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2016-07-06
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多