Date difference in Javascript (ignoring time of day)

前端 未结 15 2349
无人共我
无人共我 2020-11-27 15:35

I\'m writing an equipment rental application where clients are charged a fee for renting equipment based on the duration (in days) of the rental. So, basically, (daily fee *

15条回答
  •  渐次进展
    2020-11-27 16:18

    Need date.js, http://code.google.com/p/datejs/

    function CalculateDuration(startDate, endDate) {

    var sdt = Date.parse(startDate);
    var edt = Date.parse(endDate);
    
    var sdtYear = sdt.getYear();
    var edtYear = edt.getYear();
    var sdtMonth = sdt.getMonth();
    var edtMonth = edt.getMonth();
    var sdtDay = sdt.getDate();
    var edtDay = edt.getDate();
    
    var StartDateMonthDays = Date.getDaysInMonth(sdtYear, sdtMonth);
    var EndDateMonthDays = Date.getDaysInMonth(edtYear, edtMonth);
    
    if (edtMonth < sdtMonth) { //Means the ending month is earlier, which invalidates the operation
    
        alert("Ending month cannot be earlier than the starting month")
    
    }
    
    //Months are equal, if month is the next month of the start date month, 
    //the operation fails, thus we need to calculate month difference first
    else if (edtMonth > sdtMonth) {
    
        //Need to count how many days are left to finish the month
        var daysToMonthFinish = StartDateMonthDays - sdtDay;
        var calculatedDuration = daysToMonthFinish + edtDay;
        $("#hdn_duration").val(calculatedDuration);
    
    }
    //If months are the same, it is safe to just calculate the end day minus the start day
    else {
    
        var calcDuration = edtDay - sdtDay;
        $("#hdn_duration").val(calcDuration);
    }
    

提交回复
热议问题