Search code examples
ruby-on-railsrubyruby-on-rails-4timeactivesupport

Why does Time.now.today? return false in my Rails 4 application?


It is 8:04PM in the Eastern Standard Time Zone (US) on February 5, 2016.

When I run this command

Time.now.today?
#=> false

it returns false.

Why, and how can I correct it? Thanks.

Details:

  • Rails 4.0.0
  • Ruby 2.2.1p85
  • Mac OS X El Capitan

Solution

  • One thing that often confuses people is that Time.now and Time.current are rather different objects.

    Time.now returns Ruby library's Time class as it is. It returns the system time.

    Time.current returns Time that's modified by Rails ActiveSupport library. It returns system time modified by Rails time_zone setting.

    today? method is declared in ActiveSupport::TimeWithZone, and it determines if the given object's time is today based on Time.current, not Time.now.

    So if your Time.now and Time.current have different dates, calling Time.now.today? will return false.

    If both represent the same day, Time.now.today? will return true.

    Time.current.today? should always return true.

    Except for some special cases, it'd be better to avoid Time.now and use Time.current all the time in Rails.