2017-06-20 60 views
1

我想下面的日期和时间的组合,以UTC红宝石:日期时间为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** 

上述的转换应该给 “星期二,2017年6月20日03:00:00 +0000” 代替。

回答

0
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 

虽然你也可以指定时区不使用字符串,做这种方式偏移处理夏令时。

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

请检查我的回答,我认为这是更短,更好。 – Thanh

0

我觉得这是更短:

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