FAQ: calculate number of days between two dates in javascript

From today onwards I am introducing a new category FAQ. It will contain quick solutions and code for common problems developers face daily in javascript and php. Browser compatibility issues specially (Firefox and IE) will also be taken care of.
So here is the first one.

Q) How can I get the difference(number of days) between two dates in javascript?

A) Date and time operations in javascript can be done through the Date object. Default constructor for Date doesn’t take any argument and returns current date.

var aDate = new Date(); // will give current date

To get a specific date, you can provide year, month and day.

var anotherDate = new Date(yyyy,mm,dd);

Take care of the fact that months are from 0-11 i.e. January is 0 and December 11.
Hence, new Date(2008,10,09) is 9th November 2008 not 9th October.
Since there is not any inbuilt function for calculating date difference in javascript, we will use getTime() function. getTime() returns number of milliseconds since midnight of January 1, 1970.
Below is the code

var oneDay = 24*60*60*1000;	// hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
 
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));

What we did is

Simple, isn’t it???

Related Posts

FAQ, Technology, javascript

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

10 Responses to “FAQ: calculate number of days between two dates in javascript”

Leave Comment

(required)

(required)


10,926 spam comments
blocked by
Akismet