An introduction to time in Ruby and an explanation of what Rails brings to the party. Also covered are the exceptions, inconsistencies, and edge cases that make working with time so painful.
of a second, and a UTC offset. •Part of the standard library. require 'date' http://www.ruby-doc.org/stdlib-2.0/libdoc/date/rdoc/DateTime.html DateTime
fraction of a second, and a UTC offset or a time zone (only local time or UTC). •Stored as the number of seconds since the Epoch, January 1, 1970 00:00 UTC. •Part of the Ruby core. Time
UTC Offset Support • Small API •Implemented in C (POSIX) •Limited Overall Date Range •UTC Offset Support •Limited Zone Support •Large API vs Time DateTime 1.8.7 Edition
UTC Offset Support • Small API •Implemented in C (POSIX) •Limited Overall Date Range •UTC Offset Support •Limited Zone Support •Large API vs Time DateTime 1.9.2 Edition
UTC Offset Support • Small API •Implemented in C (POSIX) •Limited Overall Date Range •UTC Offset Support •Limited Zone Support •Large API vs Time DateTime 1.9.3+ Edition
clocks and time.[1]” •Formalized in 1963 by the International Radio Consultative Committee in Recommendation 374 •Based on UT1 and kept in sync with leap seconds. UTC 1. ^ Wikipedia “Coordinated Universal Time” Retrieved 29 August 2013
irb> Time.find_zone!('Eastern Time (US & Canada)') # => #<ActiveSupport::TimeZone:0x007fa6f86022b8...> irb> Time.use_zone('Eastern Time (US & Canada)') do Time.zone.now end # => Tue, 03 Sep 2013 20:00:00 EDT -‐4:00 Additions to Time
also available: time:zones:us, time:zones:local -‐-‐ filter with OFFSET parameter, e.g., OFFSET=-‐6 rake -‐D time:zones:all term> What time zones are available?
Configure an application time zone. # config/application.rb: class Application < Rails::Application ... config.time_zone = 'Central Time (US & Canada)' ... end
Add a time zone field to the user table. term> rails generate migration add_time_zone_to_users time_zone:string class AddTimeZoneToUsers < ActiveRecord::Migration def change add_column :users, :time_zone, :string end end
Use the time zone. # app/controllers/application_controller.rb around_filter :user_time_zone private def user_time_zone(&block) Time.use_zone(current_user.time_zone, &block) end
30 Jun 2012 00:00:00 CDT -‐05:00..Sat, 30 Jun 2012 23:59:59 CDT -‐05:00 irb> t.end.usec # => 999999 where(created_at: Time.zone.now.all_day) # => Records created that day relative to the user's time zone. Ranges
assignment is open' do it 'returns false' do Timecop.freeze(assignment.available_at -‐ 1.second) do expect(assignment.open?).to be_false end end end ... end Testing Assignment
} context 'before any assignments are open' do it 'returns no records' do Timecop.freeze(assignment.available_at -‐ 1.second) do expect(assignment.open).to have(0).records end end end ... end Testing Assignment
before { Timecop.freeze(Time.zone.local(1899)) } after { Timecop.return } it '.....' {} it '.....' {} it '.....' {} end context 'after 1900' do ... end end DRY it up.