JS计算两个日期之间的月份差_Sarah无敌的博客-CSDN博客_js计算两个日期相差的月数

日期格式:202210,202207,计算月份差

//计算两个 月份差
    reduMonths(startMonth, endMonth) {
      let startY = startMonth.slice(0, 4),
        startM = startMonth.slice(4),
        endY = endMonth.slice(0, 4),
        endM = endMonth.slice(4);
      startMonth = startY + startM;
      endMonth = endY + endM;
      if (startMonth > endMonth) {
        let reduY = startY - endY,
          reduM = startM - endM;
        return reduY * 12 + reduM;
      } else if (startMonth < endMonth) {
        let reduY = endY - startY,
          reduM = endM - startM;
        return reduY * 12 + reduM;
      } else {
        return 0;
      }
    },

console.log("月份差:",reduMonths("202210","202207"));

日期格式:2022-06,2001-03,计算月份差

function reduMonths(startMonth,endMonth){ 
  let startY = startMonth.split("-")[0],
      startM = startMonth.split("-")[1],
      endY = endMonth.split("-")[0],
      endM = endMonth.split("-")[1];
      startMonth = startY + startM
      endMonth = endY + endM
  if(startMonth > endMonth){
    let reduY = startY - endY,
        reduM = startM - endM;
    return reduY*12+reduM + "个月"
  }else if(startMonth < endMonth){
    let reduY = endY - startY,
        reduM = endM - startM;
      
    return reduY*12+reduM + "个月"
  }else{
    return 0 + "个月"
  }
}
 
console.log("月份差:",reduMonths("2020-10","2022-01"));
 
//取月份
let date = "2022-03-21"
console.log("格式化月份:", date.split("-")[0] + "-" +  date.split("-")[1]);

Logo

前往低代码交流专区

更多推荐