Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 807
Misha Moroshko Avatar asked May 19 '11 14:05

Misha Moroshko


Video Answer


3 Answers

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 
like image 161
Dylan Markow Avatar answered Oct 20 '22 09:10

Dylan Markow


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.

like image 69
Ryan Bigg Avatar answered Oct 20 '22 09:10

Ryan Bigg


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

like image 44
Josh Avatar answered Oct 20 '22 08:10

Josh