Add 365 days to a date in an input type="date"

Asked

Viewed 128 times

1

I have a problem I have an input that I type a date input format , I wanted to add what was typed + 365 but I can’t get by id nor by class:

function somaFerias(){  
  var Hoje = new Date();
  Hoje.setDate(Hoje.getDate(".campo") + 365);
  //string apenas de data em um formato determinado pelo browser
  var Today2 = Hoje.toLocaleDateString();

  alert(Today2)
}
<p>Data de Admissão</p> 
    <input type="date"  class="campo" data-ls-module="charCounter" id="adm" maxlength="10" name="data" placeholder="01/01/1990" required> 


<input type="submit" value="Ferias" name="ferias" id="feria" onClick="somaFerias()">

  • First of all you have to create a button to call the method somaFerias() thus: <button onclick="somaFerias()">Somar</button>

  • I’ve already created excuse not to put

1 answer

4


If you want to add with the date that was typed, it makes no sense to use new Date(), which takes the current date. You have to create the date based on the value of the input.

The detail is that a input type="date" returns the date in the format "yyyy-mm-dd" (which is format defined by ISO 8601 standard), and a date created with this string considers that the time is midnight in UTC (visually in the browser, the date may be in another format, but internally, when you take the value of input, the result will be "yyyy-mm-dd").

Only that toLocaleDateString() will take the date in the browser’s time zone, which is not necessarily UTC, and can give difference in the result (for example, in Brasilia Time, we are 3 hours behind UTC, so toLocaleDateString() will display "one day less" than was typed).

Another detail is that by default is considered the locale (browser language settings), then the format used by toLocaleDateString may be different depending on the environment where the code runs. If you always want the same format, specify a locale in the parameters (in the example below I used pt-BR, which corresponds to the Portuguese used in Brazil). And to avoid the time zone conversion problem, indicate that you want the date to be in UTC:

function somaFerias() {
    var data = new Date(document.getElementById('adm').value);
    data.setDate(data.getDate() + 365);
    //string apenas de data em um formato determinado pelo browser
    var dataFormatada = data.toLocaleDateString('pt-BR', {timeZone: 'UTC'});

    alert(dataFormatada);
}
<p>Data de Admissão</p> 
<input type="date" class="campo" data-ls-module="charCounter" id="adm" maxlength="10" name="data" placeholder="01/01/1990" required> 
<input type="submit" value="Ferias" name="ferias" id="feria" onClick="somaFerias()">

Note also that getDate() does not receive any parameter.


It is worth remembering that adding 365 days will not always result in the same day and month of the following year, because of leap years. In this case, use setFullYear would be more appropriate, see the difference in this example:

let d = new Date(2020, 0, 1); // 1 de janeiro de 2020
console.log(d);
// somar 1 ano
d.setFullYear(d.getFullYear() + 1);
console.log(d); // 1 de janeiro de 2021

//-----------------------------------------------------
d = new Date(2020, 0, 1); // 1 de janeiro de 2020
// somar 365 dias
d.setDate(d.getDate() + 365);
console.log(d); // 31 de dezembro de 2020

In the example above, it is worth remembering that the month is zero because in Javascript January is zero, February is 1, etc (but only when we use numeric values, because when we use strings like '2020-01-01', then the month must have the correct value).

And the above approach will still have a corner case which is when we add 1 year to 29 February:

let d = new Date(2020, 1, 29); // 29 de fevereiro de 2020
console.log(d);
// somar 1 ano
d.setFullYear(d.getFullYear() + 1);
console.log(d); // 1 de março de 2021

The result is March 1. Yes, Date arithmetic is a tricky business...

  • If I could afford a million Ikes I’d be worth it

  • 1

    @nikolaslutgens If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. Don’t forget that you can also vote in response, if it has found it useful.

  • 1

    I have no idea why the donvote, I let one up vote. I wanted to ask the following about leap years, this approach of adding 365 indiscriminately would not be a problem. I am asking because I wrote an answer using getFullYear() and setFullYear() thinking of leap years. But then the negative came up a little before I published my answer, so I aborted it and preferred to ask you instead of causing a misunderstanding.

  • 2

    @Augustovasques The question clearly says it wants to add 365 days. If the idea is to add 1 year, there setFullYear is more suitable because if I’m not mistaken already makes these adjustments taking into account leap years. And anyway, removed the downvote :-)

  • 1

    Truth I ignored the fact of the question specify 365 days and assumed the period of 1 years.

  • 2

    @Augustovasques Well, anyway, I added an example with setFullYear explaining the difference. Thank you for the comment!

  • 2

    @Augustovasques It is worth remembering that none of the approaches is free of corner cases and "strange" cases. For example, 29 February 2020 + 1 year is equal to what? In some API’s or other languages, the result is 28/02/2021, Javascript is 01/03/2021 (I also added this example in the answer). This calculation is never as simple as we would like...

  • 1

    @nikolaslutgens, that setFullYear() only works with time in years.

  • @May I ask another question here, or shall I ask another question? i was wondering how to play the value of this Function in another input while clicking on my button

  • 2

    @nikolaslutgens If it’s something as simple as I think, it would just be input.value = valor. If it’s more complicated than that, then I’ll ask you another question. Although I suggest you do a site search before, because you should already have several questions about how to put a value on another input :-)

Show 5 more comments

Browser other questions tagged

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