FAQ: calculate number of days between two dates in javascript
FAQ, Technology, javascript October 24th, 2008From 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
- we took two dates
- got milliseconds for each using getTime() function
- calculated their difference
- and finally divided the difference with the number of milliseconds in one day
Simple, isn’t it???
















Recent Comments