Js USES the setDate of the Date object to add and subtract the Date

  • 2020-03-30 03:57:29
  • OfStack

Want to write a Date and subtract method, but involves the number of days every month, if is in February, also involves the leap year judgment, complicated, is always a problem in the process of application, and checked the information, in order to introduce a number of days on a certain Date, in fact, as long as the call Date object setDate () function, 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 and subtract, the date of format - DD YYYY - MM, days parameter is to add and subtract the number of days, if the figure is introduced into negative, calculate back into positive, if you're in the add and subtract, call setMonth () and getMonth () is ok, it's important to note that the returned in starting from zero, that is less than actual in return for a month, so the corresponding plus 1.

In particular: note that when the combination of year, month and day, not directly +, will be as an int sum, to convert to a string.

PS: finally, I will recommend several online tools related to time and date for your reference:

Online date/days calculator:
(link: http://tools.jb51.net/jisuanqi/date_jisuanqi)

Online date calculator/day difference calculator:
(link: http://tools.jb51.net/jisuanqi/datecalc)

Online date days difference calculator:
(link: http://tools.jb51.net/jisuanqi/onlinedatejsq)

Unix timestamp conversion tool:
(link: http://tools.jb51.net/code/unixtime)


Related articles: