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

我与影子孤独终老i 提交于 2019-12-04 12:31:40

问题


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 storage?

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.


回答1:


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.




回答2:


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') %>


来源:https://stackoverflow.com/questions/3993619/time-select-with-12-hour-time-and-time-zone-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!