javascript live date and time

Now, you know that we can display the date and time easily with Date() method. Lets transform it into our desired format and make it run live on the webpage with the seconds value changing each second.

<span id="time"></span> 
<span id="day"></span>
  function time(){
    var date = new Date();    
    var time = date.toLocaleTimeString();
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    var day = date.toLocaleDateString('en-US',options);
    document.getElementById('time').innerHTML = time;
    document.getElementById('day').innerHTML = day;

To get the job done, we'll need to separate the date and time values. So, we added two different ids to display them.

Then, we stored the date and time value derived from javascript Date() method in a variable named date.

date.toLocaleTimeString() retrieves the time value only from the string.

date.toLocaleDateString() retrieves the date value only from the string where we added the parameters from language and value display.

We created another variable options that holds the format in which we want to display the day, date, month and year. The value numeric will make the corresponding date value display numbers while value long will make the corresponding date value display in text strings.

Parameters (language,options) are needed to be passed to the method to get it done.

Then, we displayed the value in their corresponding HTML elements.

To make the script run live, we need to reload the script. So, we added the function setInterval() that triggers the time function each second.

In this way, you can easily add a live date and time script in your pages.