time_select form helper interprets new time object

2019-06-22 17:19发布

I am running into what to me seems like a simple issue, but I can't figure out what I am doing wrong. In my app users can add their course through a simple form_for. They can enter a start_time and end_time for the course's lectures, like so:

<div class="field">
  Start Time<br />
  <%= time_select :course, :start_time, { :minute_step => 5, :ampm => true } %>
</div>

<div class="field">
  End Time<br />
  <%= time_select :course, :end_time, { :minute_step => 5, :ampm => true } %>
</div>

I configured my time zone in application.rb to be set to Eastern Time and this seems to work correctly as created_at is returned in the right time zone.

However, the problem I am encountering is that start_time and end_time are entered as UTC into the database. So when a user selects a class to start at 10 AM it is entered as 10 UTC not 10 AM EST / 15:00 UTC. What am I missing here? It seems like what I want to happen should be possible.

2条回答
▲ chillily
2楼-- · 2019-06-22 17:30

I was struggling with the same problem. But then I realized I didn't need the timezone information of the Time object.

As you said, the database stores it as UTC, but the really important thing we need to do with this data is:

course.start_time.hour
course.start_time.min

This is timezone independent. (8 hours is 8 hours from midnight, no matter what midnight you're comparing. 30 minutes is 30 minutes from the minute 0 of the hour. No matter in what timezone is that hour you're using).

So in most applications where the need of a Time storage structure is required, like to know when a recurrent event starts or finish, to store the value of a timer, or a the time of a lap in a race, you can use the UTC Time the database returns with no problem.

查看更多
3楼-- · 2019-06-22 17:38

Summarizing the answer from the comments in order to remove this question from the "Unanswered" filter:

Suggested by Tim Brandes:

Maybe this helps you: Timezone with rails 3 ... I have never used a time_select but always a datetime_select when dealing with timezones, maybe this could be an issue, but it seems rather unlikely.

Solution that worked for Philip V:

My start_time and end_time are not being saved within the time zone but saved as a UTC time. ... I changed the column type for start_time and end_time to datetime and this fixed the issues I had. I guess time columns only allow UTC.

查看更多
登录 后发表回答