问题
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