Rails - time zone conversion

2019-07-23 06:31发布

I'm trying to convert a datetime with an external timezone field into UTC. Can someone explain to me why this doesn't work?

time_str = '2016-03-01 00:00'
zone_str = 'Pacific Time (US & Canada)'

Time.use_zone(zone_str) { Time.parse(time_str).in_time_zone('UTC') }

What I'm expecting:

'2016-03-01 08:00'

What I'm getting:

'2016-03-01 06:00'

Basically, it's ignoring my use_zone call and just using my local time zone, which is Central.

What should I be doing instead?

-- edit --

Note that I am NOT trying to set the time zone across the entire application. I am ONLY trying to take a single set of inputs (time and time zone in separate form fields) and convert those to UTC.

3条回答
Deceive 欺骗
2楼-- · 2019-07-23 06:33

Try this solution:

 time = ActiveSupport::TimeZone.new(zone_str).parse(time_str)
 time.in_time_zone('UTC')
 #=> Tue, 01 Mar 2016 08:00:00 UTC +00:00
查看更多
Root(大扎)
3楼-- · 2019-07-23 06:44

Try this:

time_str = '2016-03-01 00:00'
zone_str = 'Pacific Time (US & Canada)'
Time.zone = zone_str
Time.zone.parse(time_str).in_time_zone("UTC")
查看更多
干净又极端
4楼-- · 2019-07-23 07:00
time_str = '2016-03-01 00:00'
zone_str = 'Pacific Time (US & Canada)'
time = ActiveSupport::TimeZone.new(zone_str).parse(time_str)
time.in_time_zone('UTC')

use this above code.

查看更多
登录 后发表回答