Skip to content

Instantly share code, notes, and snippets.

@litch
Last active December 29, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litch/7660412 to your computer and use it in GitHub Desktop.
Save litch/7660412 to your computer and use it in GitHub Desktop.
Ruby/Rails Time vs Datetime
☺ ~% irb
>> Time.now.to_s
=> "2013-11-26 09:33:52 -0600"
>> "2013-11-26 09:33:52 -0600".to_datetime
NoMethodError: undefined method `to_datetime' for "2013-11-26 09:33:52 -0600":String
from (irb):2
from /Users/litch/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'
>> "2013-11-26 09:33:52 -0600".to_time
NoMethodError: undefined method `to_time' for "2013-11-26 09:33:52 -0600":String
from (irb):3
from /Users/litch/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'
>> Time.zone.now.to_s
NoMethodError: undefined method `zone' for Time:Class
from (irb):4
from /Users/litch/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'
☺ ~/code/project[master]% rails c
Loading development environment (Rails 3.0.20)
>> Time.now.to_s
=> "2013-11-26 09:28:49 -0600"
>> "2013-11-26 09:28:49 -0600".to_datetime
=> Tue, 26 Nov 2013 09:28:49 -0600
>> "2013-11-26 09:28:49 -0600".to_time
=> 2013-11-26 09:28:49 UTC
>> Time.zone.now.to_s
=> "2013-11-26 15:30:06 UTC"
>> Time.zone.now.to_s.to_time
=> 2013-11-26 15:30:12 UTC
>> Time.now.to_s.to_time
=> 2013-11-26 09:30:18 UTC
#Note that Time.now.to_s.to_time is wrong. Just wrong.
>> Time.now.to_s.to_time - Time.now
=> -21600.656513
#So is DateTime.now.to_s.to_time
>> DateTime.now.to_s.to_time - DateTime.now
=> -21600.799295902252
#Time.zone.now.to_s.to_time is better
>> Time.zone.now.to_s.to_time - Time.now
=> -0.046646
#Also, note that they're both OMGWTFBBQ SLOOOOOOW
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment