Rails 3: How to get today's date in specific timezone?
Ruby on-RailsRuby on-Rails-3DateTimezoneRuby on-Rails Problem Overview
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 'Melbourne'
.
I have the following setting in my application.rb
:
config.time_zone = 'Melbourne'
and I set:
Time.zone = 'Melbourne'
in my application controller before each action.
However, it doesn't help (I guess because these settings affects only dates that are stored in the database).
How could I get today's date in 'Melbourne'
?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
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
Solution 2 - Ruby on-Rails
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.
Solution 3 - Ruby on-Rails
Date.current
Date.current
is probably the most clear and succinct way, and was added in Rails 3.
$ Date.current
#=> Sat, 14 Jul 2018
Solution 4 - Ruby on-Rails
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
Solution 5 - Ruby on-Rails
It seems Time.zone.today
also works.
Solution 6 - Ruby on-Rails
use DateTime
class
DateTime.now.in_time_zone 'Melbourne'
Solution 7 - Ruby on-Rails
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
Solution 8 - Ruby on-Rails
For valid timezone names, checkout: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
Solution 9 - Ruby on-Rails
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