Hi, I have the following code in which they ask me to take the current date and add 3 days to it to simulate the return of a movie.
Well, with today's date "01/12/2018" when adding the 3 days, the result is that the day of the return is "01/15/2018" which is correct, but if you put the current date as " 01/30/2018" when adding the 3 days it becomes "01/33/2018". How could I validate it so that the return date in that case would be "02/03/2018". I hope I have explained myself correctly.
Code:
function devolucionPelicula()
{
fecha = new Date();
dia = fecha.getDate();
mes = fecha.getMonth()+1;// +1 porque los meses empiezan en 0
anio = fecha.getFullYear();
document.write("Fecha actual: "+dia+"/"+mes+"/"+anio);
document.write("<br>Fecha devolucion: "+(dia+3)+"/"+mes+"/"+anio);
}
The function
Date.setDate()
allows you to enter values outside the usual range of a month, the month and/or year being readjusted if they are out of range:In Spanish:
So your code could be:
You just have to use the method
setDate
to set the day of the date. If the day number exceeds the last day of the month, it automatically goes to the next month:It could look like this:
You have to perform the sum of days with the methods that JavaScript provides you, in this case the setDate method , not to your numeric variables separately since it will not have any date logic (unless you offer it of course).
When adding the days allowed for the return, you need to do it inside the Date.setDate() of the return date. I hope it helps you