vue中增加月份的计算中,会考虑到增加月份加一的情况,在js中,使用split()方法按分割,时间再分别将取得的年份乘以12,得到年份的月数,再加上当前日期的月数,便可得到某年某月的总月数。下面讲解js如何计算两个日期的月份差。
/**
* @description: 增加月份
* @param {*} dateTar 原来的日期
* @param {*} offset 需要增减的数目
* @return {*} 返回处理后的日期
* @Date: 2022-05-07 17:35:26
*/
addMonth(dateTar, offset) {
var date = new Date(dateTar);
if (date instanceof Date && !isNaN(offset)) {
let givenMonth = date.getMonth();
let newMonth = givenMonth + offset;
date.setMonth(newMonth);
return this.getCurrentDate(date);
}
}
/**
* @description: 日期格式转换yyyy-MM-DD
* @param {*} date
* @return {*}
* @Date: 2022-05-07 17:36:26
*/
getCurrentDate(date) {
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate;
}