JS两个日期之间计算月数,不足月的天数保留小数

function (s_date, e_date) {

s_date=new Date(s_date);e_date=new Date(e_date);
var a_31month = [1, 3, 5, 7, 8, 10, 12];//31天的月份,2月份也暂时按30天计算
var pl_month = e_date.getMonth() == 0 ? 12 : e_date.getMonth();
var t_prelastmonthdays = a_31month.indexOf(pl_month) >= 0 ? 31 : 30;//结束月上个月的天数
var t_lastmonthdays = a_31month.indexOf(e_date.getMonth()+1) >= 0 ? 31 : 30;//结束月的天数
var predictnum = 0;

var t_year = e_date.getFullYear() - s_date.getFullYear();
var t_month = e_date.getMonth() - s_date.getMonth();
var t_day = (e_date.getDate()+1) - s_date.getDate();//结束日期比开始日期少一天,算一整月
if (t_day < 0) {
t_month = t_month - 1;
predictnum = (t_prelastmonthdays + t_day) / t_lastmonthdays;//多出的不足一个月的天数除以结束月的天数
} else {
predictnum = t_day / t_lastmonthdays;
}
return (t_year * 12) + t_month + predictnum;

}

posted on 2021-09-27 17:03  verylost  阅读(889)  评论(0编辑  收藏  举报