jpw
jpw

Reputation: 19247

rails 3: how create a time from hash, like Time.local, except interpret the hash as being in a different time zone?

Given a hash containing time and day, how do I create a time object that is UTC when the hash is some other time zone?

For example, my User is EST and specifies "15:04 8/25/2012" (via a select_datetime in a view) so the time is implicitly EST.

When they submit the form, time_hash = {"day"=>"25", "month"=>"8", "year"=>"2012", "hour"=>"15", "minute"=>"04"}

If I set

the_time = Time.local params[:date][:year], params[:date][:month], params[:date][:day], params[:date][:hour], params[:date][:minute]

it creates a time object that is 15:04 8/25/2012 -- BUT in the SERVER's local time (Pacific), not the User's local time (Eastern).

Note: I DO have Time.zone set to Eastern earlier in the same method, so I thought Time.local would interpret the hash as Eastern time, but it doesn't. I also tried Time.zone.local but that throws an error.

Upvotes: 0

Views: 476

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84132

Time.zone.local

should work fine. It's a little picker than Time.local and will only accept integers as its arguments, whereas Time.local doesn't mind strings. Sprinkle some calls to to_i in there and you should be ok.

Upvotes: 2

jpw
jpw

Reputation: 19247

One trick seems to be: use Time.zone.parse and which also means manually converting the hash to the "YYYY-MM-DD HH:MM:00" format.

the_time = Time.zone.parse("#{params[:date][:year]}-#{params[:date][:month]}-#{params[:date][:day]} #{params[:date][:hour]}:#{params[:date][:minute]}:00")

Upvotes: 0

Related Questions