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?
+3
A:
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"]
ithcy
2010-02-03 21:56:25
looks good, testing it right now =)
Derek Adair
2010-02-03 21:57:29
wait... got a slight error in there... fixed now.
ithcy
2010-02-03 21:59:07
thanks for the accept, but Jordan's is actually the better answer if you're not looking for a mental exercise.
ithcy
2010-02-03 22:04:31
+4
A:
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
2010-02-03 22:00:37
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??
ithcy
2010-02-03 22:02:44
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.
Alex JL
2010-02-03 22:04:15
+1 for being more efficient, however for what I need itchy's answer is what I'm looking for.
Derek Adair
2010-02-03 22:05:25
I'm actually pairing data and it's beneficial to have it running in a loop.
Derek Adair
2010-02-03 22:06:43
A:
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"]
Alex JL
2010-02-03 22:10:01