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

前端 未结 2 1167
生来不讨喜
生来不讨喜 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: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
    

提交回复
热议问题