When I use the \"getHour()\" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me
Other answers are indeed very good. But I think, following can be included too.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var fulltime = "";
// create a 24 elements(0-23) array containing following values
const arrayHrs = [12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11];
// since getMinutes() returns 0 to 9 for upto 9 minutes, not 00 to 09, we can do this
if(minute < 10) {
minute = "0" + minute;
}
if( hour < 12) {
// Just for an example, if hour = 11 and minute = 29
fulltime = arrayHrs[hour] + ":" + minute + " AM"; // fulltime = 11:29 AM
}
else {
// similarly, if hour = 22 and minute = 8
fulltime = arrayHrs[hour] + ":" + minute + " PM"; // fulltime = 10:08 PM
}
See what I did there in arrayHrs ;)