0

How would you create an array that contains values, one for each hour, including AM/PM, starting at 12 AM ending on 11 PM in javascript?

Derek Adair
  • 21,846
  • 31
  • 97
  • 134

3 Answers3

5

Frankly, this is the most efficient way:

var hours = [ '12 AM',  '1 AM', '2 AM', '3 AM',  '4 AM',  '5 AM',
               '6 AM',  '7 AM', '8 AM', '9 AM', '10 AM', '11 AM',
              '12 PM',  '1 PM', '2 PM', '3 PM',  '4 PM',  '5 PM',
               '6 PM',  '7 PM', '8 PM', '9 PM', '10 PM', '11 PM'  ];
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 2
    Yeah but what happens when the speed of the rotation of the earth changes and we suddenly have 25 hours in a day? WHAT THEN?? – glomad Feb 03 '10 at 22:02
  • True, this isn't something that needs to be dynamic, since it's not going to change, after all. No reason for it to be computed each time. – JAL Feb 03 '10 at 22:04
  • +1 for being more efficient, however for what I need itchy's answer is what I'm looking for. – Derek Adair Feb 03 '10 at 22:05
  • I'm actually pairing data and it's beneficial to have it running in a loop. – Derek Adair Feb 03 '10 at 22:06
  • 2
    @Jordan: OK, meet you back here on February 32 at 16 PM. – glomad Feb 03 '10 at 22:18
4

there are a million ways to do this. here's one:

var theHours = [];
for (var i=0; i<= 23; i++) {
    theHours[i] = (i == 0) ? "12 AM" : ((i <12) ? i + " AM" : (i-12 || 12) + " PM");
}

returns

["12 AM", "1 AM", "2 AM", "3 AM", "4 AM", "5 AM", "6 AM", "7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 PM", "1 PM", "2 PM", "3 PM", "4 PM", "5 PM", "6 PM", "7 PM", "8 PM", "9 PM", "10 PM", "11 PM"]

glomad
  • 5,539
  • 2
  • 24
  • 38
  • thanks for the accept, but Jordan's is actually the better answer if you're not looking for a mental exercise. – glomad Feb 03 '10 at 22:04
0

This is a method I used before:

var hour,meridien;
cow=['12 am'];
for(i=0;i<23;i++){
  if(i>11){hour=i-11;meridien=(hour==12)?'am':'pm';}
  else{hour=i+1;meridien=(hour==12)?'pm':'am';}
  cow.push(hour+' '+meridien);
  }

returns

["12 am", "1 am", "2 am", "3 am", "4 am", "5 am", "6 am", "7 am", "8 am", "9 am", "10 am", "11 am",
 "12 pm", "1 pm", "2 pm", "3 pm", "4 pm", "5 pm", "6 pm", "7 pm", "8 pm", "9 pm", "10 pm", "11 pm"]
JAL
  • 21,295
  • 1
  • 48
  • 66