Rails 3: How to get today's date in specific timezone?

前端 未结 9 1246
清酒与你
清酒与你 2021-01-30 06:21

To get today\'s date I do:

Date.today    # => Fri, 20 May 2011

I would like to get today\'s date in a specific timezone, say \'Melbour

9条回答
  •  感动是毒
    2021-01-30 07:06

    If you want to get "today" in some specified time zone without having to change Time.zone, I would do something like fl00r and Dylan Markow suggested:

    Time.now.in_time_zone('Melbourne').to_date
    

    or this:

    Time.find_zone!('Melbourne').today
    

    I wrote a little helper method Date.today_in_zone that makes getting a "today" Date for a time zone even easier:

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

    I think it reads a little nicer than Time.find_zone!('Melbourne').today...

    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
    

提交回复
热议问题