Ruby :tzinfo: localtime for other jurisdictions including time zone offset & daylight savings policy

StackOverflow https://stackoverflow.com/questions/9883636

  •  26-05-2021
  •  | 
  •  

Question

From my last question, I now know how to get access to the tzinfo gem. However I don't know how to use it for my purposes.

Suppose I need to send an email to a person in Bujumbura, Burundi every morning at 8:00 AM in whatever combination of timezone and daylight savings that applies to Bujumbura every day. My understanding is that tzinfo "knows" the information. Is it possible to convert 8:00 AM Bujumbura time (including daylight savings) into UTC for every day of the year? I would like to do something like:

require 'tzinfo'
bz = TZInfo::Timezone.get('Africa/Bujumbura')
#bujumbura_time=????
bujumbura_utctime=tz.local_to_utc(bujumbura_time)

How do I encode "bujumbura_time" to reflect that it is 8:00 AM in Bujumbura time?

Was it helpful?

Solution

I don't believe you need to make bujumbura_time aware of a specific time zone. Instead, you create a local time which can then be converted to UTC in conjunction with the time zone:

require 'tzinfo'
bz = TZInfo::Timezone.get('Africa/Bujumbura')
bujumbura_time = Time.local(2012, 3 ,27, 8, 0, 0)
bujumbura_utctime = bz.local_to_utc(bujumbura_time)

Note that converting from local time to UTC can be awkward due to daylight savings - when the clocks go forward, an hour (typically) of local time is skipped entirely, and when the clocks go back, a portion of local time occurs twice. You should work out what you want to happen in those situations. (The local_to_utc documentation explains your options.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top