Mel
Mel

Reputation: 27

Time.now not showing the correct time?

I have set my server time on UTC and and my production.rb to config.time_zone = 'Pacific Time (US & Canada)' as my app is using Pacific time.

In ruby console, Time.now is showing UTC and not Pacific!

Is this normal?

How to make sure my app is using PST?

Thanks! Mel

Upvotes: 1

Views: 2630

Answers (1)

Daniel Viglione
Daniel Viglione

Reputation: 9407

I had my own confusion when using timezones in Ruby without Rails and then I discovered an article that shed some clarification. Ruby is packaged with the Date and Time classes. These classes exist without Rails:

require "time"

Time.parse("Dec 8 2015 10:19")
#=> 2015-12-08 10:19:00 -0200
Date.parse("Dec 8 2015")
#=> #<Date: 2015-12-08>
Time.new(2015, 12, 8, 10, 19)
#=> 2015-12-08 10:19:00 -0200
Date.new(2015, 12, 8)

Ruby by default uses the timezone defined in /etc/localtime on Unix-like systems, unless you modify the TZ environmental variable like so:

ENV["TZ"] = 'US/Eastern'

It is recommended to do this if your system time is not UTC time, then you can change the environment to UTC:

Time.now
 => 2018-03-29 20:17:39 -0400 
ENV['TZ']
 => nil 
ENV['TZ'] = 'UTC'
 => "UTC" 
Time.now
 => 2018-03-30 00:17:59 +0000

Now I know that Rails has its own configuration, which you may find in application.rb:

config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local 

Rails will use this time zone configuration in your application, and it will ignore the TZ environment variable or even your system defaults.

But what you need to understand is Ruby will ignore the Rails timezone configuration, even within the context of the Rails environment! So then how do you take advantage of the Rails configuration and not the Ruby configuration? Rails has its own methods defined in ActiveSupport. These methods will generate date and time objects from the ActiveSupport::TimeWithZone. But you need to understand how to use these methods:

  • Use Time.current instead of Time.now.
  • Use Date.current instead of Date.today.

And the example:

rails c
Time.now
 => 2018-03-29 20:20:14 -0400 
ENV['TZ']
 => nil 
ENV['TZ'] = 'UTC'
 => "UTC" 
Time.now
 => 2018-03-30 00:20:35 +0000 
Time.current
 => Thu, 29 Mar 2018 20:20:40 EDT -04:00 

Upvotes: 3

Related Questions