Loading Image

Almost there...

Loading Image

Loading...

JavaScript 12 and 24 hour Clock

This is a simple JavaScript function that gets the current time of your PC and displays it either in a 12 hour or 24 hour style.
14 March 2017 - 10:00
Downloads: 489
Category: JavaScript
JavaScript 12 and 24 hour Clock
Overview

This is a simple JavaScript function that gets the current time of your PC and displays it either in a 12 hour or 24 hour style.

12 Hour Code:
<html>
<head>
<title>12 Hour Clock</title>
<script type="text/javascript">

function updateClock ( )
{
  //GET CURRENT DATE-TIME
  var currentTime = new Date ( );

  //GET THE CURRENT TIME
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );

  //APPEND A ZERO(0) IF MINUTES OR SECONDS ARE LESS THAN 10
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  //CHOOSE AM IF HOUR IS LESS THAN 12 AND PM IF HOUR IS BIGGER THAN 12
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  //CHANGE TO 12 HOUR FORMAT BY SUBTRACTING 12 IF HOUR IS BIGGER THAN 12.
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  //CHANGE HOUR OF 0 (MIDNIGHT) TO 12.
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

  //CREATE STRING OF TIME
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

  //DISPLAY TIME IN DIV
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
</script>
</head>

<!-- REFRESHES CLOCK EVERY SECOND-->
<body onLoad="updateClock(); setInterval('updateClock()', 1000 )">

<!-- DSIPLAYS CLOCK IN HERE -->
<span id="clock">&nbsp;</span>

</body>
</html>
24 Hour Code:
<html>
<head>
<title>24 Hour Clock</title>

<script type="text/javascript">
function updateClock ( )
{
  //GET CURRENT DATE-TIME
  var currentTime = new Date ( );
  
  //GET THE CURRENT TIME
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );

  //APPEND A ZERO(0) IF MINUTES OR SECONDS ARE LESS THAN 10
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  //CREATE STRING OF TIME
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;

  //DISPLAY TIME IN DIV
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
</script>

</head>

<!-- REFRESHES CLOCK EVERY SECOND-->
<body onLoad="updateClock(); setInterval('updateClock()', 1000 )">

<!-- DSIPLAYS CLOCK IN HERE -->
<span id="clock">&nbsp;</span>

</body>
</html>