Rails 3: How do I get today at a specific time zone?

To get today's date, I:

Date.today # => Fri, 20 May 2011 

I want to get the date today in a specific time zone, say 'Melbourne' .

I have the following setting in my application.rb :

 config.time_zone = 'Melbourne' 

and I installed:

 Time.zone = 'Melbourne' 

in my application controller before each action.

However, this does not help (I think because these settings only affect the dates that are stored in the database).

How can I get today's date at 'Melbourne' ?

+58
date timezone ruby-on-rails ruby-on-rails-3
May 19 '11 at 14:43
source share
9 answers

You should be able to do this: Time.current . This will show the current time in Melbourne if Time.zone .

+51
May 19 '11 at 14:46
source share

Date objects do not necessarily have time intervals, but Time objects are executed. You can try it as Time and then convert back to Date :

 Time.now.to_date # => Thu, 19 May 2011 Time.now.in_time_zone('Melbourne').to_date # => Fri, 20 May 2011 
+48
May 19 '11 at 14:48
source share

Date.current is probably the most clear and concise way: http://apidock.com/rails/v3.2.13/Date/current/class

+22
Jul 08 '13 at 16:45
source share

Time.zone.today seems to work.

+14
Nov 02 2018-11-11T00:
source share

If you want to get β€œtoday” in a specific time zone without changing Time.zone , I would do something like fl00r, and Dylan Markow suggested:

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

or that:

 Time.find_zone!('Melbourne').today 

I wrote a small helper method, Date.today_in_zone , which makes it easy to get the β€œtoday's” Date for the 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('Melbourne') => Sat, 27 Oct 2012 

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

To use it, just drop it into a file, for example, '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 
+10
Oct 26 '12 at 18:20
source share

use DateTime class

 DateTime.now.in_time_zone 'Melbourne' 
+5
May 19 '11 at 14:48
source share
 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 
+2
May 19 '11 at 14:48
source share
+2
Sep 21 '12 at 12:57
source share

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 
+1
Jun 22 2018-11-11T00:
source share



All Articles