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

前端 未结 4 1447
栀梦
栀梦 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:17

    They are not always the same. Time.zone.now.to_date will use the applications time zone, while Date.today will use the servers time zone. So if the two lie on different dates then they will be different. An example from my console:

    ruby-1.9.2-p290 :036 > Time.zone = "Sydney"
     => "Sydney" 
    ruby-1.9.2-p290 :037 > Time.zone.now.to_date
     => Wed, 21 Sep 2011 
    ruby-1.9.2-p290 :038 > Date.today
     => Tue, 20 Sep 2011 
    
    0 讨论(0)
  • 2020-12-28 13:19

    I think the best way is to learn the current time through:

    Time.current
    

    This will automatically check to see if you have timezone set then it will call Time.zone.now, but if you've not it will call just Time.now.

    Also, don't forget to set your timezone in application.rb

    0 讨论(0)
  • 2020-12-28 13:27
    # system timezone
    Time.now.to_date == Date.today
    
    # application timezone
    Time.zone.now.to_date == Time.current.to_date == Time.zone.today == Date.current
    

    http://edgeapi.rubyonrails.org/classes/Time.html#method-c-current http://edgeapi.rubyonrails.org/classes/Date.html#method-c-current

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题