Is Time.zone.now.to_date equivalent to Date.today?

前端 未结 4 1475
栀梦
栀梦 2020-12-28 12:47

Is Time.zone.now.to_date equivalent to Date.today?

Another way to put it: will Time.zone.now.to_date == Date.today always be <

4条回答
  •  长情又很酷
    2020-12-28 13:35

    Even easier: Time.zone.today

    I also wrote a little helper method Date.today_in_zone that makes it really easy to get a "today" Date for a specific time zone without having to change Time.zone:

     # Defaults to using Time.zone
     > Date.today_in_zone
    => Fri, 26 Oct 2012
    
     # Or specify a zone to use
     > Date.today_in_zone('Sydney')
    => Sat, 27 Oct 2012
    

    To use it, just throw this in a file like 'lib/date_extensions.rb' and require 'date_extensions'.

    class Date
      def self.today_in_zone(zone = ::Time.zone)
        ::Time.find_zone!(zone).today
      end
    end
    

提交回复
热议问题