Matt Huggins
Matt Huggins

Reputation: 83289

How can I make my rails time input fields respect server timezone?

I have a date_select and time_select for a date/time field in my Rails app, which I am running locally in development mode. My problem is that the date/time I enter does not align with the timezone of the server instance.

As an example, my computer's clock currently says it's 5:34pm on Sept. 19, 2013. (I am in Central time zone in case it has any bearing.) If I fill out my form with values equating to "September 19, 2013 5:34 PM", I am seeing this parsed as "2013-09-19 17:34:00 UTC". However, Time.now returns "2013-09-19 17:38:00 -0600", and Time.current returns "2013-09-19 23:38:58 UTC". Basically, the form is assuming the time in UTC, but is not aligning it with my server's UTC time (6 hour difference).

How can I ensure the form's inputs get converted to the proper zone offset?

Upvotes: 4

Views: 648

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

The form isn't assuming the time is UTC. It's using whatever you've set your Rails app to (which defaults to UTC). Play around with this until you've got it figured out. The below is from my machine. The OS is in PST (-700). The Rails app is set to UTC.

> Time.now
 => 2013-09-19 20:16:40 -0700
> Time.zone.now
 => Fri, 20 Sep 2013 03:16:42 UTC +00:00
> Time.parse("September 19, 2013 5:34 PM")
 => 2013-09-19 17:34:00 -0700
> Time.zone.parse("September 19, 2013 5:34 PM")
 => Thu, 19 Sep 2013 17:34:00 UTC +00:00
> Time.use_zone('America/Chicago') {Time.zone.parse("September 19, 2013 5:34 PM")}
 => Thu, 19 Sep 2013 17:34:00 CDT -05:00

Upvotes: 4

Related Questions