time zone in rails
TRANSCRIPT
Time zone in RailsShinjuku.rb #34
Yuki Matsukura
Today’s topic
• gem “zonebie”• Understanding time zone issues• Case study
https://spike.cc/
• DB– UTC
• Program– UTC
• View– Multi time zone.
Software stack
1. config.active_record.default_timezone2. config.time_zone3. View
Approach 1
Approach 2(Seems standard)
CASE STUDY
> require 'timecop’
> Timecop.freeze(Time.utc(2015, 12, 31, 23, 0, 0))
> Time.zone = 'Tokyo’
> Time.zone.now.utc.month == Date.today.month=> false
Both are correct, but different
validates_inclusion_of :birth_day, in: 130.years.ago.utc..20.years.ago.utc
validates_inclusion_of :birth_day, in: 130.years.ago..20.years.ago
Special time zones, > 12
Be careful with birthday handling.
• 1982-06-04 +13:00– Physically born on 6/5– Logically born on 6/4
Meaning is different.
> 60.days.since(Time.utc(2014, 2, 7, 23, 59, 59).in_time_zone('Wellington')).utc
> 60.days.since(Time.utc(2014, 2, 7, 23, 59, 59).in_time_zone('Wellington').utc)
Need to care about time zone conversion
> 60.days.since(Time.utc(2014, 2, 7, 23, 59, 59).in_time_zone('Wellington')).utc=> 2014-04-09 00:59:59 UTC
> 60.days.since(Time.utc(2014, 2, 7, 23, 59, 59).in_time_zone('Wellington').utc)=> 2014-04-08 23:59:59 UTC
Example• Bad
– Time.now– Time.zone.today– Time.parse('2013/10/01’)– Time.utc(2013,10,1)
• Bad (Might work some cases)– Time.zone.now– 1.hour.ago– Time.zone.parse('2013/10/01’)
• Instance’s timezone depends on context.– DateTime.now.utc
• To avoid using DateTime class
• Good– Time.zone.now.utc– 1.year.since.utc– 3.months.ago.utc.to_date
• (Time.zone.now.utc.to_date - 3.months)– Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone('UTC')– Time.zone.parse('2016-02-10T00:00:00+09:00’)
CODING RULE
Programming issue
• 1. Ruby and Rails time zone– http://qiita.com/joker1007/items/2c277cca5bd50
e4cce5e
• 2. Coding rule
Time zone coding rule
• Convert time zone to UTC• Avoid to convert to numeric.
– xxx.year, xxx.month