Rails 12 hour AM/PM range for a day

前端 未结 3 1558
眼角桃花
眼角桃花 2021-02-05 13:43

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

相关标签:
3条回答
  • 2021-02-05 13:49

    Rails does this built in

       <%= f.time_select :start,  {ampm: true} %>  
    

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

    0 讨论(0)
  • 2021-02-05 13:49

    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}
    
    0 讨论(0)
  • 2021-02-05 14:14

    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?

    0 讨论(0)
提交回复
热议问题