Tuesday, October 12, 2010

Date Difference In Java Script

By utilizing the "Date" object provided in the JavaScript language, a programmer can call on the current date or create objects that represent past or future dates. Furthermore, a programmer can compare these dates and find the differences between them.


JavaScript Date Object


The Date object works directly with the current date of the system it runs on. Also, the programmer can create date objects that represent future dates by providing initialization arguments to the object when it is created. The programmer can then use the functionality of the date object to pull specific arguments from the date (day, year, etc.) or compare dates to see which date is later.


Getting Today's Date


When a Date object is created, it contains the current date information when it was instantiated. If nothing else is given to the date object when it was created, it will always have that current date and time stored in it. To get the new current time, however, the programmer has to call methods such as "getDate" or "getMonth" to update the date and time.


Creating a New Date


The other way to instantiate date objects is to supply time and date information to the object. When the date object is created, the programmer can supply numerical values to change the date values, such as the year or the month. For example, the following code shows create a date object that represents the date of Christmas in 1999:


var christmas = new Date();








christmas.setFullYear(1999, 11, 25); //December 25, 1999


Getting the Difference


To calculate differences in date is a matter of subtracting the times of one date from the other, represented in milliseconds since a standard date in 1970, and converting to a time unit, such as days. So, in the Christmas example, if a programmer wished to see how much time has passed in days since Christmas 1999, she could subtract the time in milliseconds from today's current time and then convert to days:


var today = new Date();


var day = 1000*60*60*24; //number of milliseconds in a day


document.write(Math.ceil((christmas.getTime()-today.getTime())/(day));

Tags: current date, Christmas 1999, create date, created programmer, current time, date information