kapso
kapso

Reputation: 11903

Rails timezone does not work as expected

This does not return time in the pacific timezone:

Time.use_zone "Pacific Time (US & Canada)" do
  Time.now
end

This works and returns time in pacific timezone:

Time.now.in_time_zone "Pacific Time (US & Canada)"

I am using gem Rails v4.1.0.rc1

Upvotes: 0

Views: 100

Answers (1)

Hardik
Hardik

Reputation: 3895

Following should work

Time.use_zone "Pacific Time (US & Canada)" do
  p Time.zone.now
end

Why? Time.now is not working

The answer is simple Time.now is Ruby's method and Time.zone.now is Rails method.

Time.now will give you the server time. But Time.zone.now will give you rails application time (which is set in config.time_zone). When you do Time.use_zone giving block and timezone as parameter it will use this timezone as default in the block. But calling Time.now still fetches the time of the operating system which is not changed.

From #use_zone Rails API and #now Ruby API

Upvotes: 1

Related Questions