js实现月份加减

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nayi_224/article/details/86742154

我想要的规则是

If date is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as date.

简单翻译一下就是:如果所需转换的日期是月份的最后一天,或者结果月总天数少于当前日,则结果中的日期为结果月的最后一天。

举几个例子
2019-01-31 加一月 2019-02-28
2019-02-28 加一月 2019-03-31
2019-04-30 加一月 2019-05-31
2019-05-30 加一月 2019-06-30

网上找了好久,并没有发现按照这种规则执行的函数,于是自己写了一个。

关键代码

	var add_months_plus = function(oldDate, addMonths){
		var dateArr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		
		var oldYear = fill_zreo(oldDate.getFullYear(), 4);
		var oldMonth = fill_zreo(oldDate.getMonth(), 2);
		var oldDay = fill_zreo(oldDate.getDate(), 2);
		
		var newYear = parseInt(oldYear) + Math.floor((parseInt(oldMonth) + 1 + parseInt(addMonths)) / 12);
		var newMonth = (parseInt(oldMonth) + 1 + parseInt(addMonths)) % 12;
		var newDay;
		
		var currentLastDay; 
		if((oldMonth == 1) && (oldYear %  400 == 0 || (oldYear % 4 == 0 && oldYear % 100 != 0))){
			currentLastDay = 29;
		}else {
			currentLastDay = dateArr[oldMonth];
		}
		
		if(oldDay == currentLastDay){
			newDay = dateArr[newMonth];
		}else if(oldDay > dateArr[(newMonth - 1) % 12]){
			if(newMonth == 2 && (oldYear %  400 == 0 || (oldYear % 4 == 0 && oldYear % 100 != 0))){
				newDay = 29;
			}else {
				newDay = dateArr[(newMonth - 1) % 12];
			}
		}else{
			newDay = oldDay;
		}
		//alert(to_date("2019-04-30 14:34", 'yyyy-mm-dd hh24:mi'));
		//alert("old : " + oldDay + "__"+newYear+"-"+newMonth+"-"+newDay);
		//alert(""+newYear+"-"+newMonth+"-"+newDay+to_char(oldDate, '-hh24-mi-ss'));
		return to_date(""+newYear+"-"+newMonth+"-"+newDay+" "+to_char(oldDate, 'hh24:mi:ss'), 'yyyy-mm-dd hh24:mi:ss');
	}

完整代码
https://blog.csdn.net/nayi_224/article/details/81213116

猜你喜欢

转载自blog.csdn.net/nayi_224/article/details/86742154