简体   繁体   中英

Find days between two dates Jquery/JS

I have searched far and wide for this problem and so far none of the codes I have found failed to work and ones I have made also do the same, So I am starting to worry it isnt possible.

We have two dates in mm/dd/yy format not dd/mm/yy so 11/30/2012 for example.

I then use the following script:

if ( jQuery("#book_room_type").val() == "La Maison" ) {
    Date.prototype.DaysBetween = function() {  
        var intMilDay = 24 * 60 * 60 * 1000;  
        var intMilDif = arguments[0] - this;  
        var intDays = Math.floor(intMilDif/intMilDay);  
        return intDays;  
    }  
    var d1 = new Date(jQuery("#dateto").val());  
    var d2 = new Date(jQuery("#datefrom").val());  
    alert("you only have".d1.DaysBetween(d2)); 

    return false;   
}   

This however does not return the ammount of days between the dateto and datefrom fields, it is now driving me crazy, please any suggestions are appreciated.

Thanks, Simon

Ref to kalvins suggestion:

if ( jQuery("#book_room_type").val() == "La Maison" ) {
    alert("test");
    var dategap = (jQuery("#dateto").val().getTime() - jQuery("#datefrom").getTime()) / (1000 * 60 * 60 * 24);
    alert(dategap); 
    alert("test2");
    return false;   
}   

This failed on the second alert and did not alert dates.

I suggest you use datejs - http://www.datejs.com/ - for parsing and computing your dates.

Alternatively, if you want to write plain js

function(date1, date2) {
    return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}

which returns "days" in decimals.

Place the result or simply apply Math.abs() and you will get a positive decimal.

Code works, but you have a concatenation error using dot instead of + in the alert

Demo: http://jsfiddle.net/YgY5c/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM