Home > Web Front-end > JS Tutorial > body text

js uses the setDate() function of the Date object to add and subtract dates_javascript skills

WBOY
Release: 2016-05-16 16:36:03
Original
2099 people have browsed it

I want to write a date addition and subtraction method myself, but it involves the judgment of the number of days in each month. If it is February, it also involves the judgment of the leap year. It is a bit complicated and there are always problems during the application process, so I checked After reading the information, for example, to add or subtract days from a certain date, 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; 
}
Copy after login

Among them, the date parameter is the date to be added or subtracted, in the format YYYY-MM-DD, and the days parameter is the number of days to be added or subtracted. If counting forward, pass in a negative number, and if counting backward, pass in a positive number. If To add or subtract months, just call setMonth() and getMonth(). 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.

Special: Note that when combining year, month and day, it cannot be used directly. It will be summed as an int type and needs to be converted into a string.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template