When the militaryHour variable is set to 0, why does the system print 0 and not the hour (variable) I set it which is 12?

I’m trying to build a program which converts military hours to am or pm time.

I expected the output of 0 to be 12 am, but the actual output is 0 am.

const militaryHour = 0;
    
var hour = 0;
var amOrPm = "am";
    
if (militaryHour < 12) {
    hour = militaryHour;
    console.log(hour + " " + amOrPm);
} else if (militaryHour == 12) {
    amOrPm = "pm";
    hour = 12;
    console.log(hour + " " + amOrPm);
} else if (militaryHour < 24) {
    amOrPm = "pm";
    hour = militaryHour - 12;
    console.log(hour + " " + amOrPm);
} else if (militaryHour == 24){
    hour = 12;
    console.log(hour + " " + amOrPm);
} else {
    hour = 12;
    console.log(hour + " " + amOrPm);
}

Answer

All the code you need

const militaryHour = 0,
    hour = (militaryHour + 11) % 12 + 1,
    amOrPm = militaryHour % 24 < 12 ? 'am' : 'pm';

No if/else required

Leave a Reply

Your email address will not be published. Required fields are marked *