Jack Nilan         Javascript Tutorial        EMail : jacknilan@yahoo.com



Lesson 2 - JavaScript - Printing Date and Time - Continued




Now lets take a look at the time.

var day; day = new Date(); var hour = day.getHours();
var minute = day.getMinutes();
document.write("The time is " + hour + ":" + minute);


The function above will print the hour and minutes but it will be in military time. If it is 2:05Pm it will say 14:5. We need to fix this.

var day;
day = new Date();
var hour = day.getHours();
var minute = day.getMinutes();
if (hour ==0) hour = 12;
if (hour > 12)
hour = hour - 12;
document.write("The time is " + hour + ":" + minute);


The about will convert from military time to regular time.

To fix the minutes so it says 2:08 instead of 2:8 we can use the following code.

if (minute < 10)
minute = "0"+minute;


We can also print out the am or pm. Use the following code before you subtract 12 from the hours.

var st;
if (hour > 12)
st = "pm";
else
st = "am";


then just document.print(st); after you print the time.