2010/07/29

Find out when Daylight Savings Time (DST) starts and ends using Ruby (on Rails)

Recently encountered a requirement to find out whether a particular date falls within daylight savings time. After banging my head on the wall for a few hours trying to figure it out, I found that the ruby TimeWithZone object makes this quite simple.
@mytime = Time.zone.now.in_time_zone("London")
# Creates a TimeWithZone instance (instead of just a Time instance)

@mytime.period.local_start = 2010-03-28T02:00:00+00:00 Local Standard Time 
# This is when daylight savings time starts

@mytime.period.local_end = 2010-10-31T02:00:00+00:00 Local DST 
# This is when dst ends

---------------------------------- 
@sometime = Time.parse('2010-3-27 01:00:00').in_time_zone("London") 
# 2010-03-26 16:00:00 +0000 
@sometime.period.std_offset 
# 0 
@mytime.period.local_after_start?(@sometime) 
# false 
@mytime.period.local_before_end?(@sometime) 
# true 
---------------------------------- 
@sometime = Time.parse('2010-3-29 05:00:00').in_time_zone("London") 
# 2010-03-28 21:00:00 +0100 
@sometime.period.std_offset 
# 3600 << Note that std_offset now holds the offset time for daylight savings in seconds
@mytime.period.local_after_start?(@sometime) 
# true 
@mytime.period.local_before_end?(@sometime) 
# true 
---------------------------------- 
@sometime = Time.parse('2010-12-29 05:00:00').in_time_zone("London") 
# 2010-12-28 20:00:00 +0000 
@sometime.period.std_offset 
# 0 
@mytime.period.local_after_start?(@sometime) 
# true 
@mytime.period.local_before_end?(@sometime) 
# false 

0 件のコメント: