Using nested if/else statements, this example has defined the value of a new variable that prints "AM", "PM", "Noon" or "Midnight", depending on the time of day.

The first step is to divide the value of hours into two parts: hours less than 12 and all other hours.
var when;

if(hours < 12) {
when = "AM"
}
else {
when = "PM"
}
Technically, AM and PM should not be used for 12 noon and 12 midnight when minutes equal 0. So we need a way to script Noon and Midnight values for hours "0" (midnight) and "12" (noon) when minutes equals "00".

Since those hours fall within the range set by the above if/else statements, all we need to do is test once more for hour 0 AND minute 0 and hour 12 AND minute 0 by using nested if/else statements:
var when;

if(hours < 12) {

    if(hours == 0 && minutes == 0){
    when = "Midnight"
    }
    else {
    when = "AM"
    }


}
else {

    if(hours == 12 && minutes == 0){
    when = "Noon"
    }
    else{
    when = "PM"
    }


}
Take a look at the source to see the 3 arrays created to re-assign values to the integers returned for getHours(), getMinutes() and getSeconds() methods used print the time to the form field. We needed to re-assign the hours values to make them meaningful, but you may be wondering why do the same for minutes and seconds values. It is because we needed to add a zero in front of seconds and minutes 0 through 9 to make our script print the time like a digital clock. In other words, we wanted, "9:05" instead of "9:5".

"Isn't there a better way?" you might ask. Why certainly! Repeat after me: Loops are our friends. Loops are our friends....

View the Source