0

We are designing online licensing application

I Need to calculate the no of days between the date of event and the date applied The date of event are Sept 16th and Dec 31st.

Java script to count number of days

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
Raj
  • 1
  • 2
  • Please see [this](http://stackoverflow.com/faq) first. Your question is lack of information, no detail, no context.. – Iswanto San Mar 15 '13 at 19:22

2 Answers2

0

With using the Javascript Date Object you can use the following function:

var firstDate = new Date("October 16, 1975 11:13:00");
var secondDate = new Date("October 14, 1975 11:13:00");


function dateDifference(start, end)
{
    return Math.round((start-end)/(1000*60*60*24));
}

alert(dateDifference(firstDate.getTime(), secondDate.getTime()));
  • This doesn't take DST into account, allthough that's not a problem in this case. You should round or floor the result though. – Rudie Mar 15 '13 at 20:14
  • getTime() takes DST into account, see [JavaScript, time zones, and daylight savings time](http://stackoverflow.com/questions/9543580/javascript-time-zones-and-daylight-savings-time) – mschultheiss Mar 15 '13 at 20:19
  • Yeah, but not the difference between dates. `start` might be with DST and `end` without. So your result might be 19.04 or 18.96. That's why you should round it (not floor). – Rudie Mar 15 '13 at 20:29
  • Hm, I can not reproduce a comma value, can you provide an example date in the following jsFiddle: http://jsfiddle.net/yKwF8/ ? – mschultheiss Mar 15 '13 at 20:37
  • Dude all you have to do is cross the DST border: http://jsfiddle.net/rudiedirkx/yKwF8/1/ Do you have DST where you live? If you don't, you'll not see the decimals. – Rudie Mar 15 '13 at 22:54
  • Ok you are right, it should work now :) – mschultheiss Mar 16 '13 at 20:10
0

Another approach is comparing dates until they're the same. Probably a lot slower, so don't use this unless you want to extend the comparison with extra details.

fiddle: http://jsfiddle.net/rudiedirkx/Szvfd/

Date.prototype.getYMD = function() {
    return this.getFullYear() + '-' + (this.getMonth()+1) + '-' + this.getDate();
};

Date.prototype.getDaysDiff = function(d2) {
    var d1 = this,
        delta = d1 < d2 ? +1 : -1;

    var days = 0;
    while (d1.getYMD() != d2.getYMD()) {
        days++;
        d1.setDate(d1.getDate() + delta);
    }
    return delta * days;
}

d1 = new Date('October 16 2012');
d2 = new Date('November 7 2012');

console.log(d1.getDaysDiff(d2)); // 22
console.log(d2.getDaysDiff(d1)); // -22
Rudie
  • 52,220
  • 42
  • 131
  • 173