Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@guntidheerajkumar
Last active September 12, 2018 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guntidheerajkumar/9fd2812461df6bf1cb2f to your computer and use it in GitHub Desktop.
Save guntidheerajkumar/9fd2812461df6bf1cb2f to your computer and use it in GitHub Desktop.
setInterval(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;
$("#clock").html(currentTimeString);
}, 1000);
<div id="clock"></div>
@jerrywham
Copy link

To avoid depending on framework, it should be rewrite like this :

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;
   document.querySelector('#clock').innerHTML = currentTimeString;
}
updateClock(); // To load the timer immediately
setInterval(updateClock, 1000); //To update it
<div id="clock"></div>

Thank you for this snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment