RailsLearner
RailsLearner

Reputation: 1

Why Time.now returns PST if my TIme.zone is UTC?

In my Rails app I do the following:

Time.zone.name #=> 'UTC'

Why when I do:

Time.parse('2014-12-19').end_of_day.to_datetime

I get: Fri, 19 Dec 2014 23:59:59 -0800

And when I do:

Time.use_zone('Pacific Time (US & Canada)') { Time.parse('2014-12-19').end_of_day.to_datetime }

I get the exact same thing: Fri, 19 Dec 2014 23:59:59 -0800

Why is the zone not being applied?

Upvotes: 0

Views: 511

Answers (3)

Chloe
Chloe

Reputation: 26274

You are probably on Windows, which has a bug in Rails and Rails will always return your local time zone. See How does Rails know my timezone?

You can also use

zone = ActiveSupport::TimeZone['Hawaii']
zone.at(Time.now)
=> Tue, 16 Jun 2015 09:22:53 HST -10:00

But I rather like Pamio's idea

Time.now.in_time_zone('Hawaii')
=> Tue, 16 Jun 2015 09:43:17 HST -10:00

Upvotes: 0

Zero Fiber
Zero Fiber

Reputation: 4465

You need to use Time.zone.parse to make it use the proper timezone.

2.1.3 (main):0 > Time.zone.name
=> "UTC"
2.1.3 (main):0 > Time.zone.parse('2014-12-19').end_of_day.to_datetime
=> Fri, 19 Dec 2014 23:59:59 +0000

Upvotes: 2

Pramod Solanky
Pramod Solanky

Reputation: 1700

Are you looking for this

Time.use_zone('Pacific Time (US & Canada)') { Time.parse('2014-12-19').end_of_day.to_datetime.in_time_zone}

This would give you the correct time zone. For more information on this have a look at THIS SO QUESTION

Upvotes: 0

Related Questions