public
Last active

Initializer to add am/pm support to time_select helpers in Rails 3 (3.1 has an option, use it!)

  • Download Gist
am_pm_time_select.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
# modified from Bruno Miranda's original found here: http://brunomiranda.com/past/2007/6/2/displaying_12_hour_style_time_select/
 
# usage: <%= form.time_select :the_time, { :twelve_hour => true } %>
 
module ActionView
module Helpers
class DateTimeSelector
def select_hour_with_twelve_hour_time
datetime = @datetime
options = @options
return select_hour_without_twelve_hour_time unless options[:twelve_hour].eql? true
 
if options[:use_hidden]
build_hidden(:hour, hour)
else
val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : ''
hour_options = []
0.upto(23) do |hr|
ampm = hr <= 11 ? ' AM' : ' PM'
ampm_hour = case hr
when 0, 12 then 12
when 1..11 then hr
when 13..23 then hr - 12
end
hour_options << ((val == hr) ?
%(<option value="#{hr}" selected="selected">#{ampm_hour}#{ampm}</option>\n) :
%(<option value="#{hr}">#{ampm_hour}#{ampm}</option>\n)
)
end
 
build_select(:hour, hour_options.join)
end
end
alias_method_chain :select_hour, :twelve_hour_time
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.