Skip to content

Instantly share code, notes, and snippets.

@rewinfrey
Last active September 11, 2015 14:23
Show Gist options
  • Save rewinfrey/fad932d9093a91dd534e to your computer and use it in GitHub Desktop.
Save rewinfrey/fad932d9093a91dd534e to your computer and use it in GitHub Desktop.
Daylight Savings Time Finder
def daylight_savings_time_starts(year)
date = Date.new(year, 3, 1)
return Date.new(year, 3, 8) if date.wday == 0
return Date.new(year, 3, (7 - date.wday + 7 + 1))
end
def daylight_savings_time_stops(year)
date = Date.new(year, 11, 1)
return date if date.wday == 0
return Date.new(year, 11, (7 - date.wday + 1))
end
# Daylight Saving Time (United States) 2013 began at 2:00 AM on
# Sunday, March 10
# and ended at 2:00 AM on
# Sunday, November 3
daylight_savings_time_starts(2013) # => #<Date: 2013-03-10 ((2456362j,0s,0n),+0s,2299161j)>
daylight_savings_time_stops(2013) # => #<Date: 2013-11-03 ((2456600j,0s,0n),+0s,2299161j)>
#Daylight Saving Time (United States) 2014 began at 2:00 AM on
#Sunday, March 9
#and ended at 2:00 AM on
#Sunday, November 2
daylight_savings_time_starts(2014) # => #<Date: 2014-03-09 ((2456726j,0s,0n),+0s,2299161j)>
daylight_savings_time_stops(2014) # => #<Date: 2014-11-02 ((2456964j,0s,0n),+0s,2299161j)>
# Daylight Saving Time (United States) 2015 began at 2:00 AM on
# Sunday, March 8
# and ends at 2:00 AM on
# Sunday, November 1
daylight_savings_time_starts(2015) # => #<Date: 2015-03-08 ((2457090j,0s,0n),+0s,2299161j)>
daylight_savings_time_stops(2015) # => #<Date: 2015-11-01 ((2457328j,0s,0n),+0s,2299161j)>
def calculate_offset_for_dst(epoch_time)
date = Time.at(epoch_time).to_date
if daylight_savings_time_starts(date.year) <= date && date < daylight_savings_time_stops(date.year)
"-06:00"
else
"-05:00"
end
end
epoch = 1425811100
Time.at(epoch).to_date # => #<Date: 2015-03-08 ((2457090j,0s,0n),+0s,2299161j)>
calculate_offset_for_dst(epoch) # => "-06:00"
epoch = 1446411111
Time.at(epoch).to_date # => #<Date: 2015-11-01 ((2457328j,0s,0n),+0s,2299161j)>
calculate_offset_for_dst(epoch) # => "-05:00"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment