<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
/**
* 入参:Time 需要过滤的时间 支持 2017-09 or 2017/09 或者其他的间隔符
* symbol 间隔符 必须与第一个参数的间隔符对应
* m_value 月份的差值,支持任意正负数字(不越界就好)
* 示例:
* import formatTime("2017-09","-",-6,) 返回 "2017-04"
* import formatTime("2017-01","-",6,) 返回 "2017-06"
* import formatTime("2017-01","-",-6,) 返回 "2016-08"
* import formatTime("2017-08","-",6,) 返回 "2017-09"
* or
* import formatTime("2017/08","/",6,) 返回 "2017/09"
* **/
let formatTime = (Time,symbol,m_value)=>{
try {
/* 分割传入的时间 */
let arr = Time.split(symbol),
year = arr[0],
month = arr[1];
/* 处理传入的月份差值 */
let n_years = parseInt(m_value/12),
m_months = parseInt(m_value%12);
m_months>0?m_months--:m_months++;
/* 合并差值 */
let newYear = parseInt(year) + n_years,
newMonth = parseInt(month) + m_months;
/* 处理合并后的月份 大于12 小于1 跨年了 */
if(newMonth>12){
newMonth = newMonth%12;
newYear++;
}else if(newMonth < 1){
newMonth = (newMonth + 12)%12;
newYear--;
}
newMonth = newMonth<10?"0"+newMonth:newMonth;
/* 获取现在的年月 */
let nowTime = new Date(),
nowYear = nowTime.getFullYear(),
nowMonth = nowTime.getMonth() + 1;
nowMonth = nowMonth<10?"0"+nowMonth:nowMonth;
/* 对比现在的年月 决定返回值 */
if(parseInt(nowYear) < parseInt(newYear)){
return nowYear + symbol + nowMonth;
}else if(parseInt(nowYear) == parseInt(newYear) && parseInt(nowMonth) < parseInt(newMonth)){
return newYear + symbol + nowMonth;
}else{
return newYear + symbol + newMonth;
}
}catch (e){
console.log(e)
}
}
/* 测试项 */
console.log("2017-01,-24" + " 返回:" + formatTime("2017-01","-",-24,));
console.log("2017-01,6" + " 返回:" + formatTime("2017-01","-",6,));
console.log("2017-08,-6" + " 返回:" + formatTime("2017-08","-",-6,));
console.log("2017-08,6" + " 返回:" + formatTime("2017-08","-",6,));
console.log("2017/08,6" + " 返回:" + formatTime("2017/08","/",6,));
</script>
</html>