Rails 3: 如何在特定的时区获取今天的日期?

为了得到今天的日期,我这样做:

Date.today    # => Fri, 20 May 2011

我想得到今天的日期在一个特定的时区,说 'Melbourne'

我的 application.rb有以下设置:

config.time_zone = 'Melbourne'

我设定:

Time.zone = 'Melbourne'

在我的应用程序控制器每个操作之前。

但是,它没有帮助(我猜是因为这些设置只影响存储在数据库中的日期)。

我怎样才能在 'Melbourne'中得到今天的日期?

69189 次浏览

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.

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
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

use DateTime class

DateTime.now.in_time_zone 'Melbourne'

In Rails 3 you can simply do this by calling to_time_in_current_zone on a Date object.

Date.today.to_time_in_current_zone

It seems Time.zone.today also works.

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

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