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);
});
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


  • 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 :)

  • suranjan mistry

    Great job sir……..

  • Nasser

    Thanks …your script was very helpful for me. and used in my project

  • kumar

    thnaks

  • http://cheekyexperience.com Paolo Broccardo

    Excellent – worked like a charm. Thanks!

  • DaveT

    Had to sign up an account just so I can say thank you :D

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.