Reputation: 618
I run a scheduling site that allows users to set a timezone for their account. They can then schedule 'posts' on a calendar for that timezone. In the back-end, I take the time and convert it into UTC time (where a worker processes and picks up those posts on UTC time).
I run the site on Ruby (with Puma/Sinatra), but without Rails, and I'd like to stay away from Rails. There's HTML/ERB/JS in the front and a MYSQL backend.
I thought that simply adding/subtracting UTC offsets will solve all problems. I have a simple list that has TIMEZONE <--> UTCOFFSET
and this worked very well — or so I thought.
And then I realised this does not work when a given timezone (or place) is in DST currently.
Vienna in the summer: UTC offset: +2h
Vienna in the winter: UTC offset: +1h
Is there a simple way to give Ruby (not Rails) a "timezone ID" and receive the correct adjusted UTC offset back?
Like:
user.timezone = "Europe/Vienna"
utc_adjusted_time = post.local_time.to_i + get_utc_offset(user.timezone)
Where get_utc_offset
knows whether it is in DST or not. Any ideas?
I've gone through the IANA database (which is absolute overkill), I've searched through numerous Gists on Github, I've tried to abuse whatever Rails seemed to have, but didn't get very far.
How do you guys handle this? Ideally, as said, each post will be converted and saved to a DST-stripped UTC time. Thanks!
Upvotes: 1
Views: 1060
Reputation: 241603
Just use the Ruby TZInfo gem.
Your use case is exactly the one shown in the readme:
require 'tzinfo'
tz = TZInfo::Timezone.get('America/New_York')
local = tz.utc_to_local(Time.utc(2005,8,29,15,35,0))
utc = tz.local_to_utc(local)
period = tz.period_for_utc(Time.utc(2005,8,29,15,35,0))
id = period.zone_identifier
Looking at the docs for TZInfo::TimePeriod
you can see the other information you asked about:
period.offset
period.dst?
... etc.
FYI - the Rails time zone support is based on this gem anyway. Then Rails goes and puts some funky aliasing over the top (which I advise against using). See the section on Rails in the timezone tag wiki.
Upvotes: 0