Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby date today? - unexpected behavior

I'm new to Ruby and am trying to figure out why the following doesn't work as expected:

2.2.1 :010 > user_date = Date.today
 => Sun, 31 May 2015 
2.2.1 :011 > user_date.today?
 => false 

I'm using the Rails console and the commands are executed one after the other (with maybe a second between executions). I'm sure there is nuance that I'm not understanding, but shouldn't the second command return true instead of false? If not, why? Thanks in advance!

Edit #1 - Additional information requested by Arup

 2.2.1 :013 > puts user_date.method(:today?).owner
DateAndTime::Calculations
 => nil 

Edit #2 - So I had a hunch. I'm on US Eastern time and it was coming up to midnight when I ran into the original issue. I waited for the turn of midnight, and now the following works.

2.2.1 :004 > user_date = Date.today
 => Mon, 01 Jun 2015 
2.2.1 :005 > user_date.today?
 => true 
like image 582
JP. Avatar asked Mar 15 '23 20:03

JP.


1 Answers

Date.today belongs to core Ruby while today? belongs to Rails.

Under the hood, today? calls Date.current(Rails as well) instead of Date.today.

Going a bit further, we find that Date.current takes the current Rails time zone into account if one is configured. That should be the source of your mismatch.

like image 58
fylooi Avatar answered Mar 24 '23 03:03

fylooi