usha
usha

Reputation: 29359

Time Zone difference between Time.now and 1.day.ago

My app time_zone is set to UTC(default, I didn't change it in config/application.rb).

This is what I see in rails console

1.9.3p194 :004 > Time.now
 => 2014-03-20 14:45:23 -0500 
1.9.3p194 :005 > 1.day.ago
 => Wed, 19 Mar 2014 19:45:48 UTC +00:00

Why do I get the time in central when I do Time.now? It should return time in UTC like 1.day.ago

Upvotes: 1

Views: 2096

Answers (2)

trushkevich
trushkevich

Reputation: 2677

use Time.zone.now - it will take into account your application's time zone:

project with default TZ:

2.0.0-p353 :001 > Time.now
 => 2014-04-01 23:12:06 +0300 
2.0.0-p353 :002 > Time.zone.now
 => Tue, 01 Apr 2014 20:12:11 UTC +00:00 
2.0.0-p353 :003 >

project with custom TZ:

2.1.0 :001 > Time.now
 => 2014-04-01 23:14:23 +0300 
2.1.0 :002 > Time.zone.now
 => Tue, 01 Apr 2014 22:14:27 CEST +02:00 
2.1.0 :003 >

Here you'll find more useful info about working with timezones (especially take a look at DOs and DONTs section):

http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails

Upvotes: 0

Eugene
Eugene

Reputation: 4879

Time.now uses the locale of the machine it is running on. For consistency, you can do Time.now.utc to force UTC:

1.9.3-p484 :001 > Time.now
2014-03-20 16:14:23 -0400
1.9.3-p484 :002 > Time.now.utc
2014-03-20 20:14:26 UTC

Upvotes: 3

Related Questions