In your case, you do not need to assign the return of setDate
to the variable:
let data = new Date();
data.setDate(data.getDate() + 1);
console.log(data);
console.log(data.getDate());
According to the documentation, the return of setDate
is "the amount of milliseconds since 1 January 1970 at 00:00 UTC" (better known as timestamp). But you don’t need that number, so you can ignore it. Just call setDate()
that it already updates the data
.
Even the problem you mentioned about the last day of the month does not proceed, because when adding 1 on the day it already updates the month as well:
let data = new Date(2020, 0, 31); // 31 de janeiro
data.setDate(data.getDate() + 1);
console.log(data); // 1 de fevereiro
Remembering that in the example above I used 0
for the month because in Javascript months are indexed to zero (January is zero, February is 1, etc).
Then, to format, use the getters to get field values (after adding 1 day to date):
let data = new Date();
data.setDate(data.getDate() + 1);
let dia = data.getDate();
let mes = data.getMonth() + 1;
let ano = data.getFullYear();
// formate a data usando os valores acima
Note that I have already added 1 per month to get the correct value. That’s because your code had a problem:
if (mes < 10) {
mes = '0' + (mes + 1);
}
If the month is 9
, the result ends up being 010
. Already if you add up 1 soon to get the value, this problem does not occur, and then just do:
let mes = data.getMonth() + 1;
if (mes < 10) {
mes = '0' + mes;
}
OK thank you very much man, it worked here I thank you very much
– mer.guilherme.uem
For the specific formatting you are trying to do, you have more details here: https://answall.com/q/295929/112052
– hkotsubo