Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Time.zone.now.to_date equivalent to Date.today?

Is Time.zone.now.to_date equivalent to Date.today?

Another way to put it: will Time.zone.now.to_date == Date.today always be true?

If not, what's the best way to get a Date object corresponding to "now" in the application time zone?

like image 270
Tom Lehman Avatar asked Dec 20 '09 21:12

Tom Lehman


4 Answers

They are not always the same. Time.zone.now.to_date will use the applications time zone, while Date.today will use the servers time zone. So if the two lie on different dates then they will be different. An example from my console:

ruby-1.9.2-p290 :036 > Time.zone = "Sydney"
 => "Sydney" 
ruby-1.9.2-p290 :037 > Time.zone.now.to_date
 => Wed, 21 Sep 2011 
ruby-1.9.2-p290 :038 > Date.today
 => Tue, 20 Sep 2011 
like image 115
Nada Aldahleh Avatar answered Nov 12 '22 08:11

Nada Aldahleh


Even easier: Time.zone.today

I also wrote a little helper method Date.today_in_zone that makes it really easy to get a "today" Date for a specific time zone without having to change 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('Sydney')
=> Sat, 27 Oct 2012

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
like image 13
Tyler Rick Avatar answered Nov 12 '22 07:11

Tyler Rick


I think the best way is to learn the current time through:

Time.current

This will automatically check to see if you have timezone set then it will call Time.zone.now, but if you've not it will call just Time.now.

Also, don't forget to set your timezone in application.rb

like image 3
Inanc Gumus Avatar answered Nov 12 '22 09:11

Inanc Gumus


# system timezone
Time.now.to_date == Date.today

# application timezone
Time.zone.now.to_date == Time.current.to_date == Time.zone.today == Date.current

http://edgeapi.rubyonrails.org/classes/Time.html#method-c-current http://edgeapi.rubyonrails.org/classes/Date.html#method-c-current

like image 2
kuboon Avatar answered Nov 12 '22 07:11

kuboon