time zone in rails

17
Time zone in Rails Shinjuku.rb #34 Yuki Matsukura

Upload: yuki-matsukura

Post on 13-Apr-2017

1.121 views

Category:

Internet


1 download

TRANSCRIPT

Page 1: Time zone in Rails

Time zone in RailsShinjuku.rb #34

Yuki Matsukura

Page 2: Time zone in Rails

Today’s topic

• gem “zonebie”• Understanding time zone issues• Case study

Page 3: Time zone in Rails

https://spike.cc/

• DB– UTC

• Program– UTC

• View– Multi time zone.

Page 4: Time zone in Rails

Software stack

1. config.active_record.default_timezone2. config.time_zone3. View

Page 5: Time zone in Rails

Approach 1

Page 6: Time zone in Rails

Approach 2(Seems standard)

Page 7: Time zone in Rails

CASE STUDY

Page 8: Time zone in Rails

> require 'timecop’

> Timecop.freeze(Time.utc(2015, 12, 31, 23, 0, 0))

> Time.zone = 'Tokyo’

> Time.zone.now.utc.month == Date.today.month=> false

Page 9: Time zone in Rails

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

Page 10: Time zone in Rails

Special time zones, > 12

Page 11: Time zone in Rails

Be careful with birthday handling.

• 1982-06-04 +13:00– Physically born on 6/5– Logically born on 6/4

Page 12: Time zone in Rails

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)

Page 13: Time zone in Rails

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

Page 14: Time zone in Rails

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’)

Page 15: Time zone in Rails

CODING RULE

Page 16: Time zone in Rails

Programming issue

• 1. Ruby and Rails time zone– http://qiita.com/joker1007/items/2c277cca5bd50

e4cce5e

• 2. Coding rule

Page 17: Time zone in Rails

Time zone coding rule

• Convert time zone to UTC• Avoid to convert to numeric.

– xxx.year, xxx.month