工作中遇到的,记录下来方便日后查看使用!
/*
* 根据生产日期 + 商品有效期 = 有效期至
* 根据有效期至 - 商品有效期 = 生产日期
* startdate 开始时间yyyy-mm-dd
* validity 商品有效期的月数
* flag 通过标识判断是生产日期还是有效期至的方法
*/
function resultData(startdate, validity, flag) {
var year = startdate.split("-")[0];
var month = startdate.split("-")[1];
var day = startdate.split("-")[2];
var dataValidity = parseInt(validity);
// 把月和日中的像"01"这样的改成"1"
if (month.substr(0, 1) == 0) {
month = month.substr(1, 1);
}
if (day.substr(0, 1) == 0) {
day = day.substr(1, 1);
}
// 字符转换成数字
year = parseInt(year);
month = parseInt(month);
day = parseInt(day);
// 计算新的年和月
if (flag == 'add') {
// 判断加
var newmonth = month + dataValidity;
year += parseInt(newmonth / 12);
if (newmonth >= 12) {
if (newmonth % 12 == 0) {
year = year - 1;
month = 12;
} else {
month = parseInt(newmonth % 12);
}
} else {
month += dataValidity;
}
} else {
// 判断减
var newmonth = month - dataValidity;
if (dataValidity > 12) {
var a = parseInt(dataValidity / 12);
if ((dataValidity % 12) >= month) {
a = a + 1
year = year - a;
newmonth = month + 12 - (dataValidity % 12);
} else if ((dataValidity % 12) < month) {
year = year - a;
newmonth = month - (dataValidity % 12)
}
} else {
if (newmonth == 0) {
year = year - 1
month = 12
} else if (newmonth < 0) {
year = year - 1
newmonth = newmonth + 12
}
}
}
// 计算day
// 新日期是2月28日以后的情况
if (month == 2 && day >= 28) {
if (year % 4 == 0 && year % 100 != 0) {
day = 29; //闰年
} else {
day = 28; //平年
}
} else {
// 新日期是除了2月,日是30日以后的情况
if (day >= 30) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
}
}
}
// 构造yyyy-mm-dd的格式
if (flag == 'add') {
return year + "-" + (month.toString().length == 1 ? "0" + month : month) + "-" + (day.toString()
.length == 1 ? "0" + day : day);
} else {
return year + "-" + (newmonth.toString().length == 1 ? "0" + newmonth : newmonth) + "-" + (day
.toString().length == 1 ? "0" + day : day);
}
}
var resultAdd = resultData('2019-10-22', 2, 'add')
var resultSub = resultData('2019-10-22', 4, 'next')
console.log(resultAdd,resultSub)
// 打印出来的效果 2019-12-22 2019-06-22
网友评论