Daylight savings with ruby on rails
Published in
2 min readJun 12, 2020
handling daylight saving, time zone and time with ruby on rails
Knowledge transfer from Surendran Sukumaran
- Time zone select with daylight handling
On Fri, 12 Jun 2020 22:27:45
Daylight saving time in the United States 2020 in Colorado began onSunday,8 March and ends on Sunday,1 November
Daylight saving is skipped in time_zone_select
<%= form.time_zone_select :timezone, nil, { default: 'Chennai' }, { :class => "form-control", required: "required", id: 'match_timezone' } %>
With the help of formatted_offset
<%= form.select :timezone, ActiveSupport::TimeZone.all.sort_by(&:name).map{|e| ["#{e.name}(GMT#{e.now.formatted_offset})", e.name]}, { selected: 'Chennai' }, { :class => "form-control", required: "required", id: 'match_timezone' } %>
2. Building date time object with daylight
date = Date.strptime('06/18/2020', "%m/%d/%Y")start_time = '07:00 AM'Time.zone = "Pacific Time (US & Canada)"
with DateTime.parse
[205] pry(main)> DateTime.parse("#{date.year}-#{date.month}-#{date.day} #{start_time} #{Time.zone}")
=> Thu, 18 Jun 2020 07:00:00 -0800
with Time.zone.parse
[209] pry(main)> Time.zone.parse("#{date.year}-#{date.month}-#{date.day} #{start_time}")
=> Thu, 18 Jun 2020 07:00:00 PDT -07:00
3. Better code
a. method with Time.zone = “Pacific Time (US & Canada)”
recommended
def update
Time.use_zone('Pacific Time (US & Canada)') do
match_reminder_email
end
enddef match_reminder_email
date = Date.strptime('06/18/2020', "%m/%d/%Y")
start_time = '07:00 AM'
start_date = Time.zone.parse("#{date.year}-#{date.month}-# {date.day} #{start_time}")
end
Not recommended
def update
match_reminder_email
enddef match_reminder_email
date = Date.strptime('06/18/2020', "%m/%d/%Y")
start_time = '07:00 AM'
Time.zone = "Pacific Time (US & Canada)"
start_date = Time.zone.parse("#{date.year}-#{date.month}-#{date.day} #{start_time}")
end
b. Between Time.now and Time.current
The difference of .current
and .now
is .now
use the server's timezone, while .current
use what the Rails environment is set to. If it's not set, then .current
will be same as .now
.
[227] pry(main)> Time.now
=> 2020-06-13 00:11:12 +0530
[229] pry(main)> Time.current
=> Fri, 12 Jun 2020 11:41:17 PDT -07:00