Add 1 day to a date

Asked

Viewed 185 times

8

I need to pick up the next day after today. To do this I was trying:

var data = new Date() ;
var dia = data.getDate();
dia = data.setDate(dia + 1);

Only that the end of the return is 1585748377830 for example.

if (dia < 10) {
    dia = '0' + dia;
}

var mes = data.getMonth();
if (mes < 10) {
    mes = '0' + (mes + 1);
}

var ano = data.getFullYear();
var data_string = ano + '-' + mes + '-' + dia;

The problem is that I need to treat in form of string that date, so I can’t just add 1, since if it’s the last day of the month it goes back to the current month.

2 answers

13


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

  • For the specific formatting you are trying to do, you have more details here: https://answall.com/q/295929/112052

7

To catch the right day just call the getDate again, take a look:

var data = new Date();
var dia = data.getDate();
data.setDate(dia + 1);
console.log (data.getDate());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.