In ruby, how can I get current time in a given timezone? I know the offset from UTC, and want to get the current time in the timezone with that offset.
A simpler, more lightweight solution:
Time.now.getlocal('-08:00')
Well documented here.
Update 2017.02.17: If you've got a timezone and want to turn that into an offset you can use with #getlocal inclusive of DST, here's one way to do it:
require 'tzinfo'
timezone_name = 'US/Pacific'
timezone = TZInfo::Timezone.get(timezone_name)
offset_in_hours = timezone.current_period.utc_total_offset_rational.numerator
offset = '%+.2d:00' % offset_in_hours
Time.now.getlocal(offset)
If you want to do this for moments other than #now
, you should study up on the Ruby Time class, particularly Time#gm and Time#local, and the Ruby TZInfo classes, particularly TZInfo::Timezone.get and TZInfo::Timezone#period_for_local