ana
ana

Reputation: 43

How to get specific time in specific timezone in Rails

Let's say I need to get a Time object of 3am in Berlin time zone. I am not able to figure this out.

if I do,

Time.parse("03:00am").in_time_zone('Berlin')

I get the 3am in the current timezone converted to the berlin time zone. But I need the 3am in Berlin's time zone.

Upvotes: 3

Views: 974

Answers (3)

jpw
jpw

Reputation: 19247

I had the same problem and did NOT want to change Time.zone since it persists across multiple requests.

The trick (and safer approach since it does not change any system settings like Time.zone) is to put the time (AND zone) into a format usable by Time.parse. Here is an example for USA Pacific time - insert your desired TZ-format timezone string instead:

Time.parse("2012-10-1 8:00:00 Pacific Time (US & Canada)")

Upvotes: 1

pdpMathi
pdpMathi

Reputation: 775

Try this,

Time.zone = "Berlin"
Time.zone.parse("03:00am")

Upvotes: 0

dimuch
dimuch

Reputation: 12818

Try to use Time.use_zone to set timezone temporary

> Time.use_zone("Berlin") do 
>     t = Time.zone.parse("3:00am")
> end
=> Thu, 09 Aug 2012 03:00:00 CEST +02:00

Upvotes: 8

Related Questions