Pages

Sunday, 17 February 2013

How to format and update datetime in Javascript?

How to format and update datetime in Javascript?

There are a lot of datetime formats in which you can display the date and time on your webpage using javascript. There are a lot of javascript datetime functions available. In this javascript datetime tutorial, I will show you how to display the date on your webpage and keep on updating datetime every minute.

I have to show the javascript datetime in following format:

Monday, February 18, 2013 12:18

I will keep this time updating every minute without refreshing my webpage.

For this, I will make two arrays. One array will contain the names of the months and other array will contain the names of the days. I will use setInterval function which will keep on calling myDateTimer function after every minute.

Lets look at this javascript datetime code:
 
var myVar=setInterval(function(){myDateTimer()},1000);
  
function makeArray()
{
 for (i = 0; i<makeArray.arguments.length; i++)
 this[i + 1] = makeArray.arguments[i];
}
  
function myDateTimer()
{
 var months = new makeArray('January','February','March','April','May',
 'June','July','August','September','October','November','December');
 var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
 var date = new Date();
 var day = date.getDate();
 var month = date.getMonth() + 1;
 var yy = date.getYear();
 var year = (yy < 1000) ? yy + 1900 : yy;
 var hours = date.getHours();
 var minutes = date.getMinutes();
 var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
 document.getElementById("showDateTime").innerHTML=finaldate;
}

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.