Skip to content

Instantly share code, notes, and snippets.

@nahurst
Created April 24, 2011 17:17
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 nahurst/939716 to your computer and use it in GitHub Desktop.
Save nahurst/939716 to your computer and use it in GitHub Desktop.
Rails Time
# ActiveSupport::TimeWithZone is a rails construct. Always use it for querying and creating.
# DateTime is an old class and is very Ruby specific (not Rails). Don't use it.
# If you put .utc on the end of something other than a DateTime, it's converted to a Time.
# <class> <to_s>
Time.now # Time Sun Apr 24 13:00:00 -0400 2011
Time.now.utc # Time Sun Apr 24 17:00:00 UTC 2011
Time.now.in_time_zone('UTC') # ActiveSupport::TimeWithZone 2011-04-24 17:00:00 UTC
Time.zone.now # ActiveSupport::TimeWithZone 2011-04-24 17:00:00 UTC
Time.zone.now.utc # Time Sun Apr 24 17:00:00 UTC 2011
User.first.created_at # ActiveSupport::TimeWithZone 2011-04-24 17:00:00 UTC
User.first.created_at.utc # Time Sun Apr 24 17:00:00 UTC 2011
1.second.from_now # ActiveSupport::TimeWithZone 2011-04-24 17:00:00 UTC
1.second.from_now.utc # Time Sun Apr 24 17:00:00 UTC 2011
Chronic.parse('now') # Time Sun Apr 24 13:00:00 -0400 2011
Chronic.parse('now').utc # Time Sun Apr 24 17:00:00 UTC 2011
DateTime.now # DateTime 2011-04-24T13:00:00-04:00
DateTime.now.utc # DateTime 2011-04-24T17:00:00+00:00
DateTime.now.to_date # Date 2011-04-24
# Active record will save a time by converting using in_time_zone('UTC')
user = Factory(:user, :created_at => Time.now) # Time.now is Sun Apr 24 13:00:00 -0400 2011
user.created_at # ActiveSupport::TimeWithZone 2011-04-24 17:00:00 UTC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment