6

In Rails 3, is there a way to use datetime_select and display hours showing 12 hour am/pm options rather than 24-hour options?

3 Answers 3

8

In case anyone stumbles upon this question, the answer for rails 3.2 is:

<%= f.datetime_select :attribute_name,  
                       ampm: true %>  
3
  • 1
    This is the correct, Rails-supported way, but the output is an hour select with options labeled 01 AM, 02 AM, etc. which makes the set time read like "01 AM:30" which is really wonky from a user POV - almost as bad as 24-hour time.
    – pjmorse
    Commented Apr 6, 2015 at 15:01
  • I am bewildered as to why someone would program it that way. Makes no sense. The norm is 3 boxes "9 : 15 : PM"
    – Greg Blass
    Commented Dec 3, 2015 at 15:49
  • 1
    @GregBlass, we should instead switch to a 24-hour clock. ;-)
    – Tass
    Commented Dec 3, 2015 at 17:06
2

Here's the method I added to my helper class:

def am_pm_hour_select(field_name)
select_tag(field_name,options_for_select([
  ["1 AM", "01"],["2 AM", "02"],["3 AM", "03"],["4 AM", "04"],["5 AM", "05"],["6 AM", "06"],
  ["7 AM", "07"],["8 AM", "08"],["9 AM", "09"],["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"],["12 AM", "0"]]))
end

Then I plugged that method into my view:

<%= am_pm_hour_select "eventtime[start(4i)]" %>  

It seemed to do the trick, but if there's a more idiomatic way of doing this, I'd be interested to hear.

(update: fixed bugs found by thucydides)

2

The code below treats midnight and noon incorrectly: it calls noon '12 AM,' which is midnight; it calls midnight '12 PM,' which is noon.

Also, the code should use 0:00 as midnight, which is the international standard.

Fixed:

def am_pm_hour_select(field_name)
select_tag(field_name,options_for_select([
    ["1 AM", "01"],["2 AM", "02"],["3 AM", "03"],["4 AM", "04"],["5 AM", "05"],["6 AM", "06"],
    ["7 AM", "07"],["8 AM", "08"],["9 AM", "09"],["10 AM", "10"],["11 AM", "11"],["Noon", "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"],["Midnight", "0"]]))
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.