Rails - time zone conversion

倾然丶 夕夏残阳落幕 提交于 2020-01-06 02:56:05

问题


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.


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/35482356/rails-time-zone-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!