How to add 2 days to a date and put the value in HTML

Asked

Viewed 258 times

0

I have the following HTML tag:

<h1 id="newDate" style="align: center; font-weight: 100; font-family: Montserrat; font-size: 24px; color: rgb(28, 7, 7);"></h1>

I need a Javascript code to add day and month and add two days to the date. But Javascript has to be inserted on a separate sheet and call this h1 for id to insert the date into it. How do I do this?

  • 1
    1. Search how to load a JS file into HTML; 2) Search how to select the DOM element from id. The part about adding dates you might have already seen in the duplicate questions of your other question.

2 answers

1

To add two days to a date, just use one Date and add 2 to the value of getDate() (using setDate to update the value):

let d = new Date(); // data atual
d.setDate(d.getDate() + 2); // somar 2 dias

Detail: if the day is, for example, 30 April, when adding 2 the value becomes 32. But fortunately the method setDate() already makes the adjustments automatically, resulting in 2 of May. The same goes for other dates, such as December 31 (when adding 2, the value of the day becomes 33, but is adjusted to January 1 of the following year) and February 28 or 29 in leap years (you don’t have to worry whether the year is leap or not, setDate() already makes the adjustments correctly).

This is a mistake that the another answer is committing: it sums the value of the day manually, without paying attention to these special cases, where it is necessary to adjust the values. " Works" for many cases, but fails for several others.

In the example above I use the current date, but the code to add up 2 days is the same for any date you have (and as it is not clear where this date comes from, I will leave the example as well).

Now comes the part of adding this date to h1 (removed the Styles to focus on the part that matters):

<h1 id="newDate"></h1>

This element has a id, then we can get it using document.getElementById. Then you can set the innerHTML of the same to put the date inside it:

let d = new Date(); // data atual
d.setDate(d.getDate() + 2); // somar 2 dias
// buscar elemento cujo id é newDate, e colocar a data como seu conteúdo
document.getElementById('newDate').innerHTML = d;
<h1 id="newDate"></h1>

With this, the text within the h1 will be something like:

Sat Apr 06 2019 11:05:43 GMT-0300 (Brasilia Standard Time)

In fact, the exact output will vary, not only because of the current date/time, but also because of the time zone that is configured in your browser (which by default is the operating system).

Anyway, the above format is the same returned by d.toString() (which is the default used when we assign the Date directly to innerHTML). If you want the date in another format, you have to do it manually. For example, to format it as dd/mm/aaaa:

let d = new Date(); // data atual
d.setDate(d.getDate() + 2); // somar 2 dias
let dataFormatada = `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}/${d.getFullYear()}`;
document.getElementById('newDate').innerHTML = dataFormatada;
<h1 id="newDate"></h1>

Now the result is 06/04/2019 (if you run the code today, obviously - I’m using the current date, then tomorrow the result will be 07/04/2019). One annoying detail is that getMonth() returns the month value indexed at zero (January is zero, February is 1, etc), so always remember to add 1.

I also used the syntax of string template, delimited by ` and which makes it possible to place expressions within it (delimited by ${}). But if you want, you can also use the good old string concatenation syntax:

let dataFormatada = d.getDate().toString().padStart(2, '0') + '/'
                    + (d.getMonth() + 1).toString().padStart(2, '0') + '/'
                    + d.getFullYear();

Another option is to use toLocaleDateString(), which returns the date in the specific format of the locale (default language) that is configured in the browser. In my case the browser is in Brazilian Portuguese, so the return is 06/04/2019. If the browser is in American English, the return will be 4/6/2019.

You can also pass a specific locale code, so it doesn’t depend on browser settings. For example, for Brazilian Portuguese, use d.toLocaleDateString('pt-BR'), and so will be used the format referring to the Portuguese of Brazil, regardless of what is configured in the browser (remembering that the formats that depend on a locale may vary, as explained in this answer).


Another detail is that changing the value of innerHTML you change the entire content of h1. For example, if it already has a string before, it will be overwritten:

let d = new Date(); // data atual
d.setDate(d.getDate() + 2); // somar 2 dias
let dataFormatada = `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}/${d.getFullYear()}`;
document.getElementById('newDate').innerHTML = dataFormatada;
<h1 id="newDate">Um texto qualquer</h1>

Notice that Um texto qualquer some and is replaced by the date. But it is also possible to add the date to the existing text by concatenating it to the innerHTML:

let d = new Date(); // data atual
d.setDate(d.getDate() + 2); // somar 2 dias
let dataFormatada = `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}/${d.getFullYear()}`;
document.getElementById('newDate').innerHTML += ' ' + dataFormatada;
//                                           ^^ concatenar em vez de sobrescrever
<h1 id="newDate">Um texto qualquer</h1>

Now the text of h1 is Um texto qualquer 06/04/2019.


Moment js.

Another alternative is to use the Moment js., an excellent library to handle dates. It may seem a bit much to add a library just for that, but if there are people who add dependencies to much more trivial things, why not use one for something more complex, like dealing with dates? (and believe me, date arithmetic It’s harder than it looks):

let d = moment(); // data atual
// ou, se você já tiver um Date, faça:  d = moment(date)
d.add(2, 'days'); // somar 2 dias
document.getElementById('newDate').innerHTML = d.format('DD/MM/YYYY'); // formatar a data
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<h1 id="newDate"></h1>


If instead of the current date, you want to create a specific date, just do:

// criando data de 3 de abril de 2019

// com Date
let d = new Date(2019, 3, 3);

// com Moment.js
let d = moment([2019, 3, 3]);

Both examples above create the date of 3 de April de 2019. The detail is that, as has already been said, the months are indexed at zero, so April is month 3.

Then, to add 1 day to this date, just use the methods already mentioned above.


In the above examples I could also use innerText instead of innerHTML. For the specific cases of this question, the result is the same, but it is interesting to know that there are cases where it may make a difference to use one or the other.


To put Javascript on your page, just use the tag script:

<script type="text/javascript" src="arquivo.js"></script>

On this specific point, I suggest this reading.

-1

function datacorrig(){
    dayName = new Array ("00","01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12","13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24","25", "26", "27", "28","29", "30", "31"); 
    monName = new Array ("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
    var d = new Date();
    var tp = d.getFullYear()+"-"+monName[d.getMonth()]+"-"+dayName[d.getDate()+2];
    document.getElementById("newDate").innerHTML = tp;
} 
  • If d.getDate() for day 30 or 31, the code fails, as it will try to access positions that do not exist in the array dayName. In addition, there are several other cases to consider: if the date is at the end of the month, the result should be the following month (so it is no use always to take the same month), and if it is at the end of December, the year should also change. Date arithmetic is more complicated than it seems, but anyway you’ve made it up for nothing, take a look here and here to see how to do this in Javascript...

  • I just gave you a straight my friend you aeh already create your own potato checks

Browser other questions tagged

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