【问题标题】:Ruby: Datetime to UTC conversionRuby:日期时间到 UTC 的转换
【发布时间】:2017-06-20 14:29:22
【问题描述】:

我正在尝试将以下日期和时间组合转换为 UTC

from_date: "2017-06-19",from_time: "14:00"
to_date: "2017-06-19", to_time: "23:00"
Timezone: EDT

我正在使用下面的代码进行转换

Date.parse(dt).to_datetime + Time.parse(t).utc.seconds_since_midnight.seconds

它为 to_date 和 to_time 组合提供了错误的日期值。

输出:

Date.parse(from_date).to_datetime +
   Time.parse(from_time).utc.seconds_since_midnight.seconds
#⇒ **Mon, 19 Jun 2017 18:00:00 +0000**

Date.parse(to_date).to_datetime +
   Time.parse(to_time).utc.seconds_since_midnight.seconds
#⇒ **Mon, 19 Jun 2017 03:00:00 +0000**

以上转换应改为“Tue, 20 Jun 2017 03:00:00 +0000”。

【问题讨论】:

    标签: ruby ruby-on-rails-3 date datetime


    【解决方案1】:

    下面这行代码对我有用:

    parsed_date = Time.zone.parse(from_date).strftime('%Y-%m-%d')
    parsed_time = Time.zone.parse(from_time).strftime('%T')
    Time.parse(parsed_date + ' ' + parsed_time).utc.strftime('%F %T')
    

    【讨论】:

    • 请检查我的答案,我认为它更短更好。
    【解决方案2】:
    require 'time'
    
    from = Time.parse "2017-06-19 14:00 US/Eastern"
    => 2017-06-19 14:00:00 -0400 
    from.utc
    => 2017-06-19 18:00:00 UTC
    
    to = Time.parse "2017-06-19 23:00 US/Eastern"
    => 2017-06-19 23:00:00 -0400 
    to.utc
    => 2017-06-20 03:00:00 UTC 
    

    虽然您也可以在不使用字符串的情况下指定时区偏移量,但这样做可以处理夏令时。

    【讨论】:

      【解决方案3】:

      我认为这更短:

      from_date = "2017-06-19"
      from_time = "14:00"
      DateTime.strptime("#{from_date}T#{from_time}ZEDT", "%Y-%m-%dT%H:%MZ%z").utc
      => Mon, 19 Jun 2017 18:00:00 +000
      
      to_date = "2017-06-19" 
      to_time = "23:00"
      
      DateTime.strptime("#{to_date}T#{to_time}ZEDT", "%Y-%m-%dT%H:%MZ%z").utc
      => Tue, 20 Jun 2017 03:00:00 +0000
      

      【讨论】:

        猜你喜欢
        • 2013-08-18
        • 2012-07-07
        • 2011-07-11
        • 2019-11-26
        • 2014-01-05
        • 1970-01-01
        • 2021-12-31
        • 2012-10-07
        • 1970-01-01
        相关资源
        最近更新 更多