In Rails, what's the nicest way to create a specific time (not now) in a particular time zone?

Solution 1:

I think you're looking for

Time.find_zone('Alaska').local(2011,1,1)
=> Sat, 01 Jan 2011 00:00:00 AKST -09:00

Time.find_zone('Amsterdam').local(2011,1,1)
=> Sat, 01 Jan 2011 00:00:00 CET +01:00 

Time.find_zone('Sydney').local(2011,1,1)
=> Sat, 01 Jan 2011 00:00:00 EST +11:00  

Time.find_zone('Wellington').local(2011,1,1)
=> Sat, 01 Jan 2011 00:00:00 NZDT +13:00

This also works with parse

Time.find_zone('Sydney').parse('2011-04-12 2pm')
=> Tue, 12 Apr 2011 14:00:00 EST +10:00 

Solution 2:

For parsing a date within a specific time zone, you can use ActiveSupport::TimeZone

> ActiveSupport::TimeZone["Sydney"].parse("2011-04-12 2pm")
=> Tue, 12 Apr 2011 14:00:00 EST 10:00

TimeZone API documentation is here: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-c-5B-5D

Solution 3:

This is what I use:

Time.zone.local(2011, 4, 12, 14, 0)

Solution 4:

As said above, to create a time in a specific timezone (e.g., 4/10/2014 1:30pm New York):

@event.start_time = Time.find_zone('Eastern Time (US & Canada)').local(2014,4,10,13,30)
=> Thu, 10 Apr 2014 13:30:00 EDT -04:00 

@event.start_time.utc
=> 2014-04-10 17:30:00 UTC

When it is saved to your db, it will be converted to UTC (in Postgres at least if using a timestamp type in your migration), and on future access it will be displayed relative to the application timezone set in config/application.rb

To properly display the local time, we also store the timezone name (e.g., 'Eastern Time (US & Canada)' ) in our database. So, when we want to print the time in our views, we do...

@event.start_time.in_time_zone(@event.timezone)
 => Thu, 10 Apr 2014 13:30:00 EDT -04:00 

To get the abbreviated timezone (e.g., EST)

@event.start_time.in_time_zone(@event.timezone).zone
=> "EDT"