Reputation: 751
This is an ongoing issue I'm having and I don't know how to work with it.
A user sets their Time.zone
when they create an account. In this case "Pacific Time (US & Canada)".
When they create an object and enter in the date and time it comes in the format of a string with no explicit timezone offset like so "05/31/2017 2:00 PM"
Knowing these two things. I would like to convert the inputted time string into a UTC format and save it.
I've tried the following but it's not taking the pacific time into account:
time = Time.strptime("05/31/2017 2:00 PM Pacific Time (US & Canada)", "%m/%d/%Y %H:%M %p %Z").utc
=> 2017-05-31 14:00:00 UTC
14:00:00 UTC is 7AM pacific. It should be 21:00:00 as it is currently -0800. I would like to find a method to take timezones into account and save them correctly in UTC format.
It however converts correctly if I give it the exact offset like so:
time = Time.strptime("05/31/2017 2:00 PM -0800", "%m/%d/%Y %H:%M %p %Z").utc
=> 2017-05-31 22:00:00 UTC
This problem is killing me. I would simply like to save all date and times in UTC format so all that a user has to do is set their timezone and view times correctly. Also taking into account DST if applicable.
Upvotes: 0
Views: 1811
Reputation: 5684
In Rails you can use ActiveSupport to change a time zone without changing value and convert to utc
#parse time as usual
time = Time.strptime("05/31/2017 2:00 PM", "%m/%d/%Y %H:%M %p")
#convert to utc using timezone that you need
res = ActiveSupport::TimeZone.new('Pacific Time (US & Canada)').local_to_utc(time)
#> 2017-05-31 21:00:00 UTC
Upvotes: 1