日期格式: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

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐