Rails 12 hour AM/PM range for a day

前端 未结 3 1557
眼角桃花
眼角桃花 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

    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}
    

提交回复
热议问题