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

前端 未结 2 1057
生来不讨喜
生来不讨喜 2021-01-11 15:51

I have the following model and methods:

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

  def self.today
    where(:p         


        
相关标签:
2条回答
  • 2021-01-11 16:16

    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) 
    
    0 讨论(0)
  • 2021-01-11 16:28

    If you use the Time class, you'll have access to UTC (or "zulu") time zone rather than using the environment's time zone in Date class.

    class UserPrice < ActiveRecord::Base
      attr_accessible :price,  :purchase_date,    
    
      def self.today
        where(purchase_date: today_utc_date)
      end
    
      def self.yesterday
        where(purchase_date: today_utc_date.yesterday)
      end
    
      private
    
      def today_utc_date
        @today ||= Time.zone.today
      end
    end
    

    Also, if you need to process an outside date, for example params[:purchase_date]:

    Time.parse(params[:purchase_date]).utc.to_date
    
    0 讨论(0)
提交回复
热议问题