Search code examples
javascriptjquerydatedatejs

Find difference between two dates with javascript


I am trying to find the difference between two dates. The dates are got with jquery and I am using datejs too. When using datejs it picks up my date as US thinking it is MM/DD/YYYY instead of dd-mm-yyyy. My result for difference is NaN. How do I work this out. Am I miles out or anywhere near close?

var msMinute = 60*1000, 
    msDay = 60*60*24*1000;

start = $('#reconcile_start_date').val();   // 10-12-2014 | dd-mm-yyyy
end = $('#reconcile_end_date').val();           // 15-12-2014 | dd-mm-yyyy

start = new Date(start);
end   = new Date(end);

console.log(Math.floor((end - start) / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);

if(difference > 30){}

Solution

  • try this:

    $(document).ready(function(){
    
        var msMinute = 60*1000; 
        var msDay = 60*60*24*1000;
    
        var start = '10-12-2014'; // October 12
        var statarr=start.split('-');
    
        var end = '12-15-2014'; // December 15
        var endarr=end.split('-');
    
        var dstart = new Date(statarr[0]+'/'+statarr[1]+'/'+statarr[2]).getTime();
        var dend   = new Date(endarr[0]+'/'+endarr[1]+'/'+endarr[2]).getTime();
    
        var diff = parseInt(dend-dstart);
    
        console.log(Math.floor(diff / msDay) + ' full days between ' + end + ' and ' + start);
        difference = Math.floor((end - start) / msDay);
    
        if(difference > 30){
        }
        });
    

    // for UK formate use this:

    var start = '12-10-2014'; // October 12
        var statarr=start.split('-');
    
        var end = '15-12-2014'; // December 15
        var endarr=end.split('-');
    
        var dstart = new Date(statarr[1]+'/'+statarr[0]+'/'+statarr[2]).getTime();
        var dend   = new Date(endarr[1]+'/'+endarr[0]+'/'+endarr[2]).getTime();
    

    and rest is same.