Create Account
Sign In

Display Date and Time in Javascript - real-time clock javascript date time


Display Date and Time in Javascript - real-time clock javascript date time Display Date and Time in Javascript - real-time clock javascript date time The 09/08/2010 at 19:35:24
Rating: 4/5
Keywords: display date time javascript real-time clock date javascript time getDate

Hi,
In this script, I will show you how to display the date and time in real time in a web page using Javascript. You can see the final result here:
Display Date and Time in Javascript

The script is simple, we will use the Javascript Object Date to get the date and the time. We will display the month in words(January, February...).

This is the code:
date_time.js
function date_time(id)
{
        date = new Date;
        year = date.getFullYear();
        month = date.getMonth();
        months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December');
        d = date.getDate();
        day = date.getDay();
        days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        h = date.getHours();
        if(h<10)
        {
                h = "0"+h;
        }
        m = date.getMinutes();
        if(m<10)
        {
                m = "0"+m;
        }
        s = date.getSeconds();
        if(s<10)
        {
                s = "0"+s;
        }
        result = ''+days[day]+' '+months[month]+' '+d+' '+year+' '+h+':'+m+':'+s;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("'+id+'");','1000');
        return true;
}
date_time.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Display Date and Time in Javascript</title>
        <script type="text/javascript" src="date_time.js"></script>
    </head>
    <body>
            <span id="date_time"></span>
            <script type="text/javascript">window.onload = date_time('date_time');</script>
    </body>
</html>
Test

I hope this script will be useful.

Similar Scripts and Tutorials

Javascript redirection with a timeout - timed redirect js timeout Javascript redirection with a timeout - timed redirect js timeout Javascript Calendar - (X)html calendar js script Javascript Calendar - (X)html calendar js script Simple PHP Forum Script - php forum easy simple script code download free php forum mysql Simple PHP Forum Script - php forum easy simple script code download free php forum mysql Go to previous and next page in Javascript - history object Go to previous and next page in Javascript - history object Javascript Calculator - Buttons calculator keyboard support operations modulo Javascript Calculator - Buttons calculator keyboard support operations modulo