Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time select form helper with 12 hour format for Rails 3?

Is there a user-friendly time_select for Rails 3? The default time_select form helper gives you hours[00-23], minutes[00-59] and optionally seconds[00-59]. A dropdown list of hours 0-23 is pretty frustrating for those of us who aren't on military time. A user-friendly solution would display hours 1-12 and an extra am/pm dropdown list.

Is there an option or a separate plugin to handle this? I can't be the first person to want this, but I haven't found any solutions.

Thanks!

like image 551
swese44 Avatar asked Mar 24 '11 06:03

swese44


2 Answers

You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.

time_select 'game', 'game_time', {:ampm => true}

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_select

like image 184
arturtr Avatar answered Nov 15 '22 13:11

arturtr


I don't know of a build in helper for exactly what you want. I suggest you build one, and share it! You likely don't want the first item in the dropdown to be 12am either, so that should be a config option.

Also, if 12am is 0 or 24 should be configurable too.

Here's a base using vanilla select_tag:

<%= f.select :your_attribute, [ 
     ["6am", 6], ["7am", 7], ["8am", 8], ["9am", 9], ["10am", 10], ["11am", 11], ["12pm", 12], ["1pm", 13], ["2pm", 14], ["3pm", 15], ["4pm", 16], ["5pm", 17], ["6pm", 18], ["7pm", 19], ["8pm", 20], ["9pm", 21], ["10pm", 22], ["11pm", 23], ["12am", 24], ["1am", 1], ["2am", 2], ["3am", 3], ["4am",4 ], ["5am", 5]
], class:''%>

It displays 12hour time to your user, and posts a 24 hour integer to your server.

Update

I needed one anyway, so I went ahead a wrote it.... In the view:

<%= am_pm_hour_select f, :your_method, start:3 %>

(Note the syntax is not f.helper, but helper f, other_options)

In app/helpers/am_pm_form_helper.rb:

module AmPmFormHelper
  #pass start:Fixnum in the options hash to set the first drop down selection
  def am_pm_hour_select(object, method, options = {}, html_options = {})
    select_options = [ ["6am", 6], ["7am", 7], ["8am", 8], ["9am", 9], ["10am", 10], ["11am", 11], ["12pm", 12], ["1pm", 13], ["2pm", 14], ["3pm", 15], ["4pm", 16], ["5pm", 17], ["6pm", 18], ["7pm", 19], ["8pm", 20], ["9pm", 21], ["10pm", 22], ["11pm", 23], ["12am", 24], ["1am", 1], ["2am", 2], ["3am", 3], ["4am",4 ], ["5am", 5]]
    unless options[:start].nil?
      shift_if_needed = Proc.new{|hour, start| hour<start ? hour+24 : hour}
      select_options.sort!{|x, y| shift_if_needed.call(x.last,options[:start]) <=> shift_if_needed.call(y.last, options[:start]) }
    end

    object.select(method, select_options, options = {}, html_options = {})
  end
end
like image 38
SooDesuNe Avatar answered Nov 15 '22 11:11

SooDesuNe