Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails timezone and Daylight saving time

for a while I´m trying to understand how this timezone times will work, and I had a question:

Today in my country, we are in Daylight saving time (GMT-2). So the user of my application enter a time, like 11:00AM and post the form. Far as I know, rails will convert this date to UTC and save in the database (mysql in my case), like: 01:00PM UTC.

When I recover that record, I had to convert to local time to display. Ok?

My question is, lets suppose that this date/time represents a date/time in future, when my country gets out from summer time (GMT-3). Rails will save 01:00PM UTC? Today, in Daylight saving time, how will be the local time? And in the future, how will be this local time?

Basically, I always need to display to user 11:00AM.

thanks.

like image 630
Beetlejuice Avatar asked Nov 14 '12 11:11

Beetlejuice


2 Answers

There are several places where timezone can come into play: the operating system (or probably user account) default setting, the database server, Rails environment.rb.

The key is to make sure all dates are stored with UTC time zone, then displayed in whatever your local timezone is. It sounds like you're doing that.

So your question seems to boil down to "if it's Daylight time, I want to offset by -3 hours, else offset by -2 hours". The Rails time extensions let you determine your current offset like Time.zone.now.utc_offset, and Time#dst? tells you if it's Daylight Savings Time with those two you can conditionally subtract the extra hour (3600 hundred seconds).

like image 59
Tom Harrison Avatar answered Sep 22 '22 14:09

Tom Harrison


7 months after you asked, but perhaps skip_time_zone_conversion_for_attributes= will help - it tells AcitveRecord not to convert timezones on storage or retrieval. See ActiveRecord Timestamp which shows the example:

class Topic < ActiveRecord::Base
  self.skip_time_zone_conversion_for_attributes = [:written_on]
end
like image 41
Kip Avatar answered Sep 19 '22 14:09

Kip