JSFiddle - React, Tailwind, and code Playground
by ashu_mdu
HTML
<div style="clear: both;"> </div>
<h1>The JavaScript clock in action</h1>
<p>View the source of this page to see how it works. Feel free to use the JavaScript in your own Web pages!</p>
<div style="width: 10em; text-align: center; margin: 20px auto;">
<span id="clock"></span>
</div>
<p><a href="https://www.elated.com/articles/creating-a-javascript-clock/">Return to the article</a></p>
<p><small>All code in this page is copyright 2007 <a href="http://www.elated.com/">Elated Communicatons Ltd</a></small></p>
CSS
#clock { font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; color: white; background-color: black; border: 2px solid purple; padding: 4px; }
JavaScript
function init ()
{
timeDisplay = document.createTextNode ("");
document.getElementById("clock").appendChild (timeDisplay);
}
function updateClock ()
{
var currentTime = new Date ();
var currentHours = currentTime.getHours ();
var currentMinutes = currentTime.getMinutes ();
var currentSeconds = currentTime.getSeconds ();
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}