The Set Up
Let’s start by creating our HTML. We don’t need much, just a <span> tag with an ID of “clock” will do.
<span id="clock"> </span>
Update your project with the following code:
// 1. Created the function
function updateClock ( )
// 2. Created some variables
var Time = new Date ( );
var Hours = Time.getHours ( );
var Minutes = Time.getMinutes ( );
var Seconds = Time.getSeconds ( );
//3. If needed, add Zeros to single intergers
Minutes = ( Minutes < 10 ? "0" : "" ) + Minutes;
Seconds = ( Seconds < 10 ? "0" : "" ) + Seconds;
//4. IF Else logic for choosing "AM" or "PM"
var timeOfDay = ( Hours < 12 ) ? "AM" : "PM";
//5. Change from Military time to 12-hour format
Hours = ( Hours > 12 ) ? Hours - 12 : Hours;
//6. If Hour time is 0, change it to 12
Hours = ( Hours == 0 ) ? 12 : Hours;
//7. Final Clock output
var currentTimeString = Hours + ":" + Minutes + ":" + Seconds + " " + timeOfDay;
//8. Function to display current time
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
<!---9. Update clock every 1000ms or one second--->
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
<span id="clock"> </span>
As you can see, we had to do a little work around to get the clock the way we want. Let’s go over each comment and the logical steps we had to take:
- First we created a function called updateClock.
- We created some reusable variables with the methods used to retrieve the data.
- Performed an If/Else statement to check the hours and if less than 12, output AM, if not output PM.
- Another If/Else statement that checks for any numbers above 12 and performs the proper math to display as 12-hour time instead of Military time.
- That last IF/Else statement that changes the 0 hour to the number 12.
- We create a variable called currentTimeString that displays the values of each statement put together.
- Created a function that calls the currentTimeString statement and places it in the element with the ID of “clock” (which would be in the <span>.
- In order for the clock to update and display the results every second, we tied a method to the <body> tag that set’s a check interval every 1000ms (or one second).
Adding Some Style
Since our clock has an ID, that means that we can target the text and style it with some CSS. If you’d like, use the css below to style the colors, size and font of your clock. We used an external font from Google Fonts and the provided link to spice up our font style. This should all be placed within the <head> tag.
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
font-family: 'Open Sans', sans-serif;
border:8px solid #666;
Wrapping It Up