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;
}

1 comment:

  1. Why call it makeArray, if it doesn't return an array? Why not just use a regular array, with the first element set to empty string, null, undefined etc. Why do you use the arguments property of a function? It is non standard, and is deprecated. Why do you update the innerHTML every second, although you state, that you update every minute? Why do you select the DOM element every time, and not cache it in a variable?

    ReplyDelete