In Rails or generally Ruby, how can I know whether a datetime string corresponds to a datetime that has DST or not?

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

Question

My application runs on "Athens" (Greece) time zone. The standard offset is "+02:00". However, during summer, Athens has DST, which means that offset becomes "+03:00" for specific periods within the year. And these periods are not standard. They change.

Given a string "20YY-MM-DDTHH:MI:SS", that represents a date time in "Athens" time zone, I want to be able to convert it to correct DateTime instance using either "+02:00" or "+03:00" offset.

Hence, for example, the string "2013-04-11T20:28:07" is actually "2013-04-11T20:28:07+03:00", whereas the string "2013-11-11T20:28:07" is actually "2013-11-11T20:28:07+02:00".

Do I have any Rails/Ruby code that can help me find out the correct offset, given the time zone and the datetime specification missing actual offset?

Was it helpful?

Solution 2

This seems to work:

Time.parse('2013-04-11T20:28:07').in_time_zone('Athens').utc_offset
#=> 10800

Time.parse('2013-11-11T20:28:07').in_time_zone('Athens').utc_offset
#=> 7200

OTHER TIPS

I think you need the TZInfo library (gem here). The library uses the name of a timezone, as specified in the IANA TimeZone database. This database contains the rules that specify the offsets for each timezone, specified by a name. The database is regularly updated whenever a rule changes.

Using a simple timezone offset to determine the timezone is not enough. Offsets can change simply by passing a law that changes the baseline offset, the date or even the time of switching from summer to winter time. Moscow for example, has changed timezones at least twice in the last 4 years.

A better solution, if you use Rails, is to use in_time_zone, as Stefan notes

http://www.ruby-doc.org/core-1.9.3/Time.html

dst? → true or false Returns true if time occurs during Daylight Saving Time in its time zone.

So if you do Time.local(YYYY, M, D).dst?
and it gives true then the time of that DateTime line fell in Daylight Saving ..

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