Skip to content

Instantly share code, notes, and snippets.

@duncan
Created September 23, 2010 02:06
Show Gist options
  • Save duncan/592942 to your computer and use it in GitHub Desktop.
Save duncan/592942 to your computer and use it in GitHub Desktop.
Orbiter:dailyshoot duncan$ rails c
Loading development environment (Rails 3.0.0)
# To set up this discussion, here's the time I'm running these examples at.
# It's almost 7PM Pacific on Weds, Sept 22.
ruby-1.9.2-p0 > Time.now
=> 2010-09-22 18:56:57 -0700
# Date.today is a Ruby core method. It does what you'd think
ruby-1.9.2-p0 > Date.today
=> Wed, 22 Sep 2010
# Here's where things go weird. Date.tomorrow is a Rails method.
# This method is defined in active_support/core_ext/date/calculations.rb
ruby-1.9.2-p0 > Date.tomorrow
=> Fri, 24 Sep 2010
# That's messed up, isn't it?
# Now, if you dig in to the Rails code, it's doing what it thinks is right.
# It's getting the date of tomorrow --UTC--. See Time.now above? Since it's
# 7PM here in PDT land, it's tomorrow in UTC-land.
# Here's the crux of the problem, illustrated. Right now, my system Ruby thinks
# the time zone is:
ruby-1.9.2-p0 > Time.now.zone
=> "PDT"
# Rails is set to UTC by default.
# This method is defined in active_support/core_ext/time/zones.rb
ruby-1.9.2-p0 > Time.zone
=> (GMT+00:00) UTC
# So, the Ruby code is playing according to a PDT playbook, the Rails code is
# playing on a UTC playbook. The part that makes it hard on the head is that
# since Rails is mixing in code into Ruby's core classes, we're getting variable
# behavior IN THE SAME OBJECT.
# Let's drop back to Ruby core only methods. This makes sense:
ruby-1.9.2-p0 > Date.today + 1
=> Thu, 23 Sep 2010
# If you combine Ruby's .today with Rail's tomorrow, it works out just fine.
# This little behavior made tracking this interaction down --hard--. It makes
# things feel really psycho until you know what's what.
ruby-1.9.2-p0 > Date.today.tomorrow
=> Thu, 23 Sep 2010
# And of course, it's all good when you work with Time objects. A Time object
# always has it's sense of zone, while a Date object doesn't.
ruby-1.9.2-p0 > Time.now.tomorrow
=> 2010-09-23 18:57:15 -0700
# Presumably, this little issue of Date objects getting weird got out into
# the world because Time works just peachy. Time objects carry their zone info
# with them and will convert out just fine. Date objects don't.
# The moral of this story:
# If you want to have a Date object that is really tomorrow in your local (non-UTC)
# reference of days, you'll want to use the following:
ruby-1.9.2-p0 > Date.today.tomorrow
=> Thu, 23 Sep 2010
# On the other hand--as pointed out by @koz after he read this, if you want the
# UTC flavor of today's Date no matter where you are, you can use this:
ruby-1.9.2-p0 > Time.zone.today
=> Thu, 23 Sep 2010
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment