This is a really simple question, and it\'s probably been asked and answered before, but I haven\'t been able to find anything.
Anyway, I need a range/array for 12 hour
Rails does this built in
<%= f.time_select :start, {ampm: true} %>
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_select
I know this has already been answered awhile ago with the built in. But I needed a custom function to get these values and wrote this:
times = {"12 AM" => 0}.merge!(1.upto(11).collect { |n| {"#{n} AM" => n} }.reduce(Hash.new, :merge)).merge!({"12 PM" => 12}).merge!(1.upto(11).collect { |n| {"#{n} PM" => n + 12} }.reduce(Hash.new, :merge))
This yields:
{"12 AM"=>0, "1 AM"=>1, "2 AM"=>2, "3 AM"=>3, "4 AM"=>4, "5 AM"=>5, "6 AM"=>6, "7 AM"=>7, "8 AM"=>8, "9 AM"=>9, "10 AM"=>10, "11 AM"=>11, "12 PM"=>12, "1 PM"=>13, "2 PM"=>14, "3 PM"=>15, "4 PM"=>16, "5 PM"=>17, "6 PM"=>18, "7 PM"=>19, "8 PM"=>20, "9 PM"=>21, "10 PM"=>22, "11 PM"=>23}
I agree with @MrYoshi's comment, the easiest way of formatting a date is .strftime()
,
see RubyDoc for all possible options
Example:
Time.now.strftime("%I:%M %p")
output: HH:MM AM
Or what you literally asked for:
Time.now.strftime("%I:00")
output: HH:00
As you mentioned time_select
I assume you want to offer time as a user selectable range, so try these options for time_select
(more options):
time_select 'game', 'game_time', {:minute_step => 60, :ampm => true}
also this previous question: Time select form helper with 12 hour format for Rails 3?