Ruby:Datetime到UTC的转换

Ruby:Datetime到UTC的转换,ruby,ruby-on-rails-3,date,datetime,Ruby,Ruby On Rails 3,Date,Datetime,我正在尝试将下面的日期和时间组合转换为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_日期和to_时间组合提供了错误的日期值 输出: Date.p

我正在尝试将下面的日期和时间组合转换为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_日期和to_时间组合提供了错误的日期值

输出:

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**
上述换算应改为“2017年6月20日星期二03:00:00+0000”


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

以下代码行适用于我:

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')

我认为这个比较短:

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

请检查我的答案,我认为它更短更好。
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