Skip to content

Instantly share code, notes, and snippets.

@seanarnold
Last active December 23, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seanarnold/6698768 to your computer and use it in GitHub Desktop.
Save seanarnold/6698768 to your computer and use it in GitHub Desktop.
Rails Date.today problem
Loading development environment (Rails 4.0.0)
2.0.0-p247 :001 > Date.today
=> Thu, 26 Sep 2013
2.0.0-p247 :002 > Date.tomorrow
=> Thu, 26 Sep 2013
@seanarnold
Copy link
Author

This is happening because the Ruby Time.zone is not set.
Date#today does not exist in ActiveSupport so it falls back to Ruby's Date#today

Date#current provides the expected result. I think Date#today should be added to ActiveSupport & alias Date#current

@seanarnold
Copy link
Author

Problem + fix explained here

Loading development environment (Rails 4.0.0)
2.0.0-p247 :001 > Date.today
 => Thu, 26 Sep 2013 
2.0.0-p247 :002 > Date.tomorrow
 => Thu, 26 Sep 2013 
2.0.0-p247 :003 > Date.define_singleton_method(:today) do 
2.0.0-p247 :004 >     Date.current
2.0.0-p247 :005?>   end
 => #<Proc:0x007fd93d051720@(irb):3 (lambda)> 
2.0.0-p247 :006 > Date.today
 => Wed, 25 Sep 2013 
2.0.0-p247 :007 > Date.tomorrow
 => Thu, 26 Sep 2013 
2.0.0-p247 :008 > Time.zone = "Auckland"
 => "Auckland" 
2.0.0-p247 :009 > Date.today
 => Thu, 26 Sep 2013 
2.0.0-p247 :010 > Date.tomorrow
 => Fri, 27 Sep 2013 

@seanarnold
Copy link
Author

This is a known 'issue' and is discussed in the Ruby on Rails guides here:
http://guides.rubyonrails.org/active_support_core_extensions.html

15.1.1 Date.current

Active Support defines Date.current to be today in the current time zone. That's like Date.today, except that it honors the user time zone, if defined. It also defines Date.yesterday and Date.tomorrow, and the instance predicates past?, today?, and future?, all of them relative to Date.current.

When making Date comparisons using methods which honor the user time zone, make sure to use Date.current and not Date.today. There are cases where the user time zone might be in the future compared to the system time zone, which Date.today uses by default. This means Date.today may equal Date.yesterday.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment