Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Date.yesterday counts as Date.today also?

I have the following model and methods:

class UserPrice < ActiveRecord::Base
  attr_accessible :price,  :purchase_date,    

  def self.today
    where(:purchase_date => Date.today)
  end

  def self.yesterday
    where(:purchase_date => Date.yesterday)
  end

Why on my form if I give my date_select field :purchase_date 1/4/2012(yesterday method) it also counts as today(today method) and if I give it 1/5/2012 (today) it is nil?

P.S. I am using Rails 3.0.10 with PostgreSQL.


Update

This is my console returns:

$ rails console --s
Loading development environment in sandbox (Rails 3.0.10)
Any modifications you make will be rolled back on exit
irb(main):001:0> Date.today
=> Wed, 04 Jan 2012
irb(main):002:0> Time.now
=> 2012-01-04 21:28:07 -0500
irb(main):003:0> Time.zone.now
=> Thu, 05 Jan 2012 02:28:18 UTC +00:00
irb(main):004:0> Date.yesterday
=> Wed, 04 Jan 2012
irb(main):005:0>

Now yesterday is screwed up, makes no sense....

like image 958
LearningRoR Avatar asked Jan 05 '12 01:01

LearningRoR


1 Answers

This is happening because calculations.rb is calling the "current" method of the Date class for the configured timezone (Defaults to UTC).

If you open the rails console you can see the date at which "Date.yesterday" is calculating on by doing:

Time.zone.today

This will probably show you tomorrow's date. So Date.yesterday for what rails sees as today, is today. ;)

You can work with the Date library more directly by doing:

Date.today.advance(:days => -1)

This will give you yesterday's date like you expect whereas active_support is returning:

Date.current.advance(:days => -1) 
like image 106
josephrider Avatar answered Oct 09 '22 12:10

josephrider