Create Your Own jQuery Digital Clock

Sam Deering

This is a pretty cool way to display the time on your web page using jQuery to get the current time and then refresh the clock every 1 second.

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);
   	  	
 }

$(document).ready(function()
{
   setInterval('updateClock()', 1000);
});

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Pingback: 10+ Cool jQuery Clock Tutorials (Analog and Digital) | jQuery4u

  • http://www.facebook.com/felloveragain Dan Smith

    Works a treat, thanks!

  • tumi

    thanks for the tutorial man…really helpful!

  • xxx

    great, thanks

  • Dookerj

    Excellent work!

  • nehali

    I used your clock in my project. Thanks a lot.

  • Elvis

    Excellent script

  • Henry Jahja

    thank you

  • Jose Paulo Lacsinto

    thank you for sharing… i will use this script in my project

  • coldfusion developer

    nice! thank you so much

  • rajwpdeveloper

    great work….

  • Rahul

    thanks bro, i just used your script to my project. thank you very much :)