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

前端 未结 9 1073
清酒与你
清酒与你 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 06:42

    You should be able to do this: Time.current. That would display the current time in Melbourne if that's what Time.zone is set to.

    0 讨论(0)
  • 2021-01-30 06:47

    For valid timezone names, checkout: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

    0 讨论(0)
  • 2021-01-30 06:53
    ruby-1.9.2-p0 :004 > Time.now
     => 2011-05-19 15:46:45 +0100 
    ruby-1.9.2-p0 :006 > Time.now.in_time_zone('Melbourne')
     => Fri, 20 May 2011 00:47:00 EST +10:00 
    ruby-1.9.2-p0 :007 > Time.now.in_time_zone('Melbourne').to_date
     => Fri, 20 May 2011
    
    0 讨论(0)
  • 2021-01-30 06:55

    Date.current

    Date.current is probably the most clear and succinct way, and was added in Rails 3.

    $ Date.current
    #=> Sat, 14 Jul 2018
    

    http://apidock.com/rails/v3.2.13/Date/current/class

    0 讨论(0)
  • 2021-01-30 06:56

    use DateTime class

    DateTime.now.in_time_zone 'Melbourne'
    
    0 讨论(0)
  • 2021-01-30 06:57

    Date objects don't necessarily have timezones, but Time objects do. You can try it as a Time, then convert back to a Date:

    Time.now.to_date
    # => Thu, 19 May 2011 
    Time.now.in_time_zone('Melbourne').to_date
    # => Fri, 20 May 2011 
    
    0 讨论(0)
提交回复
热议问题