Date plus minus

This article is a reprinted article, the original address: https://www.cnblogs.com/zangdalei/p/4948812.html

If it is suspected of infringement, please contact the original author to delete it!

As in the title, I started to check the js documentation, but I didn't find any functions that I could use directly, so I wanted to write my own functions, which would involve judging the number of days in each month, and if it was February, it would also involve The judgment of leap year, although it is not complicated, I think js should not be so low-level, so I checked the information, and finally made the following major discovery. In terms of adding or subtracting days on a certain date, in fact, just call the setDate of the Date object. () function, the specific method is as follows: 

function addDate(date,days){ 
var d=new Date(date); 
	d.setDate(d.getDate()+days); 
	var m=d.getMonth()+1; 
	return d.getFullYear()+'-'+m+'-'+d.getDate(); 


Among them, the date parameter is the date to be added and subtracted, and the days parameter is the number of days to be added and subtracted. If you calculate forward, pass in a negative number, and if you calculate later, pass in a positive number. If you want to add or subtract months, call setMonth() and getMonth() are fine. It should be noted that the returned month is calculated from 0, which means that the returned month is one month less than the actual month, so add 1 accordingly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324425111&siteId=291194637