Js uses the setDate () function of the Date object to add or subtract a Date. datesetdate
I want to write a date addition and subtraction method, but it involves the judgment of the number of days each month. If it is July, it also involves the judgment of a leap year. It is complicated and there is always a problem in the application process, so I checked the information to add or subtract days from a Date. In fact, you only need to call the setDate () function of the Date object. The specific method is as follows:
function addDate(date,days){ var d=new Date(date); d.setDate(d.getDate()+days); var month=d.getMonth()+1; var day = d.getDate(); if(month<10){ month = "0"+month; } if(day<10){ day = "0"+day; } var val = d.getFullYear()+""+month+""+day; return val; }
Among them, the date parameter is to add or subtract the date, the format of YYYY-MM-DD, days parameter is to add or subtract the number of days, if the previous calculation is passed into a negative number, after the calculation is passed into a positive number, to add or subtract a month, call setMonth () and getMonth (). Note that the returned month starts from 0, that is to say, the returned month is one month less than the actual month, so 1 is required.
Note: When combining the year, month, and day types, you cannot directly +. It is treated as an int type sum and must be converted to a string.
Add or subtract dates in js
Var today = new Date (); // get today's time
Today. setDate (today. getDate () + 7); // the system automatically converts
The following are three functions provided by the date class that you may use to generate strings:
GetDate () returns a day (1 ~ 31 ).
GetMonth () returns the month from the Date object (0 ~ 11 ).
GetFullYear () returns the year from the Date object in four digits.
How to add or subtract a date in js
Convert getTime () to the millisecond format before performing addition or subtraction;
Then, use setTime () to convert it to the date format for output;