开发者

time_select with 12 hour time and Time Zone in Ruby on Rails

开发者 https://www.devze.com 2023-01-21 02:13 出处:网络
I have the need to capture a time and time zone from users of a rails 2.3.8 app, but have been unable to think of a clean solution to create and parse the selections.

I have the need to capture a time and time zone from users of a rails 2.3.8 app, but have been unable to think of a clean solution to create and parse the selections.

Ideally I would have a drop-down menus for the following:

  • hour (1-12)
  • minute (0-59)
  • AM/PM
  • Time Zone

Is there a gem/plugin that accomplishes what I am looking for? Will I need to store both the time and time zone in the database? What is the best strategy for stora开发者_如何转开发ge?

I'll eventually need to spit these values out in UTC, but a user should be able to go back and review the time in the correct time zone.


You can get time zone selects with the appropriate methods:

  • time_zone_options_for_select
  • time_zone_select

Similarly, there's date_select for dates.

Storage:

If the timezone is specific to the user and doesn't change, then store their time zone in their user record and set it when you load the current_user. Rails will convert times to/from UTC and always store UTC in the database and do the automatic convert to that default timezone for you (including daylight savings!). Easiest way to do it.

use_zone(zone) lets you override the default zone for a block, so you can accept a form value and set it with that function and set your value in that block.

UPDATE: I wrote up some Rails timezone examples as a blog entry.


I personally used jQuery to change the display only:

 ampm = ["12 AM","01 AM","02 AM","03 AM","04 AM","05 AM","06 AM","07 AM","08 AM","09 AM","10 AM","11 AM","12 PM","01 PM","12 PM","01 PM","02 PM","01 PM","02 PM","03 PM","04 PM","05 PM","06 PM","07 PM","08 PM","09 PM","10 PM","11 PM"]
    j("#game_start_time_4i option").each(function(index,value){
        j(value).html(ampm[index]);
    });

Rails:

<%= datetime_select('game', 'start_time') %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号