JS uses the Date object's setdate () function to add and subtract operations _javascript tips

Source: Internet
Author: User
Tags getdate

Want to write a date of the addition and subtraction method, but it involves the judgment of the days of the month, if it is February, but also related to the judgment of leap years, some complex, the application process is always a problem, so check the data, in order to add on a certain date to reduce the number of days You can actually call the setdate () function of the Date object 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; 
}

Where the date parameter is to be added and minus dates, format yyyy-mm-dd,days parameter is the number of days to add and subtract, if the forward calculation on the incoming negative numbers, then the incoming positive numbers, if it is to carry out the month of addition and subtraction, call Setmonth () and getmonth () on it, Note that the returned month is calculated starting at 0, which means that the returned month is one months less than the actual month, so add 1 accordingly.

Special: Note that when the combination of month and day, not directly +, will be as int type sum, to convert to string.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.