0

I found a similar question here but this is not working for my case as my dates are in a specific format "yyyy-MM-dd" i.e. "2014-08-29" and "2014-08-31".
I tried below but not working as expected. "dtpEffectiveFrom" & "dtpEffectiveTo" both are HTML5 date field. For the above date range, output is showing NaN days instead of 3 days.

var effectiveFrom = $("#dtpEffectiveFrom").val();
var effectiveTo = $("#dtpEffectiveTo").val();

function daydiff(first, second) {
    return (second - first) / (1000 * 60 * 60 * 24);
}

var msg = "Are you applying for a " + daydiff(effectiveFrom, effectiveTo) + " day(s) leave?";
alert(msg);
Community
  • 1
  • 1
vpv
  • 920
  • 2
  • 20
  • 46

3 Answers3

2

see this code. You need to convert string to date and use getTime function to get dates in milli seconds.

var effectiveFrom = "2014-08-29";
var effectiveTo = "2014-09-31";

function daydiff(first, second) {
    return (second.getTime() - first.getTime()) / (1000 * 60 * 60 * 24) + 1;
}

var days = daydiff(new Date(effectiveFrom), new Date(effectiveTo));

console.log(days);
Sanjay Sahani
  • 565
  • 4
  • 14
  • I tried your code, but this is showing difference of 2 days, but i need the result to include from date too, as I am expecting the result to display 3 days as output. Can you do something about it? Thanks. – vpv Aug 28 '14 at 05:38
  • If you want to include from date then add 1 into result as 31 - 29 will always be 2. See modified code – Sanjay Sahani Aug 28 '14 at 05:55
1

Try using daydiff function like this:

function daydiff(first, second) {
    first=new Date(first);
    second=new Date(second);
    return (second - first) / (1000 * 60 * 60 * 24);
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ankit Sahrawat
  • 1,306
  • 1
  • 11
  • 24
0

Use the Date object to handle the format...

    var effectiveFrom = new Date($("#dtpEffectiveFrom").val());
    var effectiveTo = new Date($("#dtpEffectiveTo").val());

    function daydiff(first, second) {
        return (second - first) / (1000 * 60 * 60 * 24);
    }

    var msg = "Are you applying for a " + daydiff(effectiveFrom, effectiveTo) + " day(s) leave?";
    alert(msg);

See http://jsfiddle.net/crt2a6xz/

Lucky Edward
  • 136
  • 11