43

I have an object attribute of the DateTime class.

How would I understand if the saved date is today, tomorrow or else later?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

3 Answers3

81

Here are some useful ways to achieve it:

datetime = DateTime.now  => Sun, 26 Oct 2014 21:00:00

datetime.today? # => true
datetime.to_date.past? # => false (only based on date)
datetime.to_date.future? # => false  (only based on date)

datetime.to_date == Date.tomorrow # => false
datetime.to_date == Date.yesterday # => false
Alireza
  • 2,641
  • 17
  • 18
  • 4
    This was probably in the context of a loaded ActiveSupport gem. There is no `today?` in the standard library. – ian Feb 05 '19 at 05:50
  • This is from Active Support but can also be used outside of Rails: `require 'active_support/core_ext/time/calculations'` (see https://guides.rubyonrails.org/active_support_core_extensions.html) – Ralf Ebert Nov 12 '19 at 16:02
8

Something like...

datetime = Time.now.to_datetime
=> Sun, 26 Oct 2014 16:24:55 -0600 

datetime >= Date.today
=> true

datetime < Date.tomorrow
=> true

datetime += 1.day
=> Mon, 27 Oct 2014 16:25:12 -0600

datetime >= Date.today
=> true

datetime >= Date.tomorrow
=> true 

datetime < (Date.tomorrow + 1.day)
=> false

?

Bob Mazanec
  • 1,121
  • 10
  • 18
4

yesterday? & tomorrow? (Rails 6.1+)

Rails 6.1 adds new #yesterday? and #tomorrow? methods to Date and Time classes.

As a result, now, your problem can be solved as:

datetime = DateTime.current
# => Mon, 16 Nov 2020 20:50:16 +0000


datetime.today?
# => true

datetime.yesterday?
# => false

datetime.tomorrow?
# => false

It is also worth to mention that #yesterday? and #tomorrow? are aliased to #prev_day? and #next_day?.

Here is a link to the corresponding PR.

Marian13
  • 7,740
  • 2
  • 47
  • 51