How to add another day using "new Date ()" [duplicate]

2

Hello, I have this function, but I do not know how I put one more date on the date, someone can help me.

var myVar = setTimeout(function(){ myTimer() });

function myTimer() {
    var d = new Date();
    var options = {weekday: 'long', month: 'long', year: 'numeric', day: 'numeric' }
    var t = d.toLocaleDateString('pt-br', (options));
        document.getElementById("demo").innerHTML = t;

}
    
asked by anonymous 30.06.2017 / 16:27

2 answers

2

The canonical, cross-browswer, documented and workable way is that you add up the amount of milliseconds from a day to your date.

I.e.:

var agora = new Date();
var agoraAmanha = new Date(agora.getTime() + (1000 * 60 * 60 * 24));
// essa é a quantidade de milissegundos em 24 horas.

The reason for this is that:

  • Adding a date is a browser behavior. It is not guaranteed that all browsers will have the same behavior, nor that the same browser will behave the same behavior on all devices. Outside other environments like Node.js. I'm not saying that it does not work in every environment you use ... I just think the above solution is more secure.

  • You could also use the setDate of type Date. In the environments in which I tested, adding a day does what you want. Set March 32, for example, gets you a date on April 1st. But again, there is no guarantee of this behavior in all environments.

30.06.2017 / 16:45
1

Add a line:

d.setDate(d.getDate() + 1);

the code will be:

    var myVar = setTimeout(function(){ myTimer() });

    function myTimer() {
        var d = new Date();
        d.setDate(d.getDate() + 1);
        var options = {weekday: 'long', month: 'long', year: 'numeric', day: 'numeric' }
        var t = d.toLocaleDateString('pt-br', (options));
            document.getElementById("demo").innerHTML = t;

    }

No need to worry about the last day of the month or year, because JavaScript is smart in terms of rollover .     

30.06.2017 / 16:37