How to display a Digital watch with Current Date on a Web page using JavaScript

Sometimes in our web applications we need to display current date and time , there are various ways and methods to display date and time in a web application.
Here I am going to describe one simple method to display Current date and time in a digital watch format.

Here I am using JavaScript and html code to display a digital watch on a web page.

Sample JavaScript Code :
var timerID = null;
var timerRunning = false;

//–Reset the clock before its starts function stoptimer() { if(timerRunning) { clearTimeout(timerID); timerRunning = false; }

}

//–Clear the timerId value to reset the clock. //–Start the timer and display the Date and time function showtime() { //–Retrieve Current Date and Time

var now = new Date();

//–Retrieve Hours from Current Date and Time object
var hours = now.getHours();

//–Retrieve Minutes from Current Date and Time object
var minutes = now.getMinutes();

//–Retrieve Seconds from Current Date and Time object
var seconds = now.getSeconds();

//–Retrive current Date from Current Date and Time object
var date = now.getDate();

//–Retrieve current Date from Current Date and Time object var month = now.getMonth();

var month=(month+1);

//–Retrieve current Date from Current Date and Time object
var year = now.getYear()

//–Append the date,month and year value as digital numbers var dateValue = ((month < 10) ? “0” : “”) + month ; dateValue += ((date < 10) ? “/0” : “/”) + date;

dateValue += “/” + year;

//–Append the hours,minutes and seconds value as digital numbers var timeValue = ((hours < 10) ? “0” : “”) + hours ; timeValue += ((minutes < 10) ? “:0” : “:”) + minutes;

timeValue += ((seconds < 10) ? “:0” : “:”) + seconds ;

//–Append the current date and time
dateValue += ” ” + timeValue ;

//–Display the value in a button control
document.form.btnDisplay.value = dateValue;

//–Set timer to display time at each interval of time.
timerID = setTimeout(“showtime()”,1000);

//–Set the timerrunning is true timerRunning = true;

}

//–Function call for start timer and display the Output function startclock() { stoptimer(); showtime();

}

Sample HTMLCode to call the JavaScript function:

Explanation :
Here I use an html button control to display the Date and time and also I use some optional style property to customize the display of the digital watch.The startclock() function is called on an onload event of body tag . In startclock() function again two functions are called to initialize the clock and display date and time such as stoptimer() and showtime() respectively.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!