为什么它没有给我正确的总月份?

时间:2015-10-08 00:22:32

标签: javascript

为什么它没有给我正确的总月份? (与当前function get_total_month(mm,yyyy) { // custom inputs var start_date = new Date(yyyy, mm, 01); // current date var today_date = new Date(); var today_year = today_date.getFullYear(); var today_month = today_date.getMonth(); var today_day = today_date.getDate(); var end_date = new Date(new Date(today_year, today_month, today_day)); // compare the given date with current date to find the total months var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth()); return total_months; } alert( get_total_month(01, 2014) ); 相比)

{{1}}

给我: 20 而不是 22

2 个答案:

答案 0 :(得分:1)

那是因为Date.prototype.getMonth方法返回0-11的数字。所以:

January = 0
February = 1
...
December = 11

答案 1 :(得分:1)

我认为这是您正在寻找的,它是您的代码的另一个版本。但我认为更短更容易理解。你觉得怎么样?

(我添加了+2以将结果调整为您期望函数返回的结果)

 function monthDifference(startDate) {
        var months;
        var currentDate = new Date();
        months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
    
        months -= startDate.getMonth() + 1;
        months += currentDate.getMonth();
        return months <= 0 ? 0 : (months + 2);
    }
    
    alert(monthDifference(new Date(2014,0)) );
    alert(monthDifference(new Date(2013,11)) );