Javascript,计算月份之间两个日期之间的距离

时间:2014-06-27 14:25:08

标签: javascript html date

我正在尝试使用Javascript计算两个日期之间的距离。现在我发现了一些非常好的代码,但它有一个问题。每当我尝试计算30天而不是31天的月份日期时,它会计算额外的一天(我猜因为它假定每个月有31天)。我想知道是否有办法解决这个问题?

    var from = document.getElementById("from").value;
    var fromdate = from.slice(3, 5);
    fromdate = parseInt(fromdate);
    var frommonth = from.slice(0, 2); 
    frommonth = parseInt(frommonth);
    var fromyear = from.slice(6, 10); 
    fromyear = parseInt(fromyear);
    var to = document.getElementById("to").value;
    var todate = to.slice(3, 5); 
    todate = parseInt(todate);
    var tomonth = to.slice(0, 2); 
    tomonth = parseInt(tomonth);
    var toyear = to.slice(6, 10); 
    toyear = parseInt(toyear);
    var oneDay = 24*60*60*1000;
    var firstDate = new Date(fromyear,frommonth,fromdate);
    var secondDate = new Date(toyear,tomonth,todate);

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    alert(diffDays);

1 个答案:

答案 0 :(得分:1)

使用var difference= Math.abs(firstDate - secondDate)