Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  42] [ 1]  / answers: 1 / hits: 25043  / 11 Years ago, tue, june 11, 2013, 12:00:00

I created this function to increment a date (for a jQuery UI Datepicker):



function addDay(date) {
var moreDay = new Date();
var decomposed = date.split(-);
var act = new Date(decomposed[2], decomposed[1], decomposed[0]);
moreDay.setDate(act.getDate()+1);
return moreDay;
}


So, it scomposes the date (ex: 12-06-2013 (dd-mm-YYYY)) and put the values into a new Date, after that it addes a day. It works, but the month not change. Example, I changed the function into this:



function addDay() {
var moreDay = new Date();
var act = new Date(2013, 7, 3);
moreDay.setDate(act.getDate()+1);
alert(moreDay);
}


And it returns Jun 4th 2013.. How it's possible?


More From » javascript

 Answers
146

It's not clear what you want to do with your function. If you want to take a date and add a day, try with this:



function addDay(date) {
var decomposed = date.split(-),
moreDay = new Date(decomposed[2], decomposed[1] - 1, decomposed[0]);
moreDay.setDate(moreDay.getDate() + 1);
alert(moreDay);
}


Please take note that in common dd-mm-yyyy dates, January is 1, whereas to define a Date object January is 0, hence the - 1.



This alternative should be faster than setDate:



moreDay.setTime(moreDay.getTime() + 864e5);


Or you could define your Date object directly with an added day:



moreDay = new Date(decomposed[2], decomposed[1] - 1, +decomposed[0] + 1);

[#77675] Monday, June 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;