求JS两个日期之间的月份数

如下图,文本框A1和文本框A2分别是开始时间和结束时间,我想要的是选择完A2时间后,在A3里显示A1和A2两个日期之间的月份数

如果只是要这个功能 , 就不要跟日期类打交道了..直接算就好了

function getMonths(date1 , date2){
    //用-分成数组
    date1 = date1.split("-");
    date2 = date2.split("-");
    //获取年,月数
    var year1 = parseInt(date1[0]) , 
        month1 = parseInt(date1[1]) , 
        year2 = parseInt(date2[0]) , 
        month2 = parseInt(date2[1]) , 
        //通过年,月差计算月份差
        months = (year2 - year1) * 12 + (month2-month1) + 1;
    return months;    
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-04
如果只是要这个功能
,
就不要跟日期类打交道了..直接算就好了
12345678910111213function getMonths(date1 , date2){ //用-分成数组 date1 = date1.split("-"); date2 = date2.split("-"); //获取年,月数 var year1 = parseInt(date1[0]) , month1 = parseInt(date1[1]) , year2 = parseInt(date2[0]) , month2 = parseInt(date2[1]) , //通过年,月差计算月份差 months = (year2 - year1) * 12 + (month2-month1) + 1; return months; }
第2个回答  2017-11-27
字符串会错的,2017取的是2
相似回答