Help to sum days on a user-selected date

Asked

Viewed 48 times

-1

I need a help, I have a form of reservation of rooms, have as I increase the number of days of a date that the user selected, received by the value of the html form?

Like something like that.

function myFunction() {

var datainicio = $("#dtini").val();

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

var a = d.getFullYear()+"-"+d.getMonth()+"-"+d.getDate();

alert(a);

$('#dtfim').attr('min',a);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input id="dtini" type="date" min="2021-02-10" onchange="myFunction()">
<input id="dtfim" type="date">

But in this case, it is only printed at the current date + 3, I need to add with the date selected by the user himself. Thanks in advance!

  • let d = new Date(); // data atual, why did you do this instead of using the variable datainicio?

  • It was only an example, but I’ve tested it with the variable itself, but it didn’t work.

2 answers

1

Changes:

  1. If you do not want the current date as a reference, do not use new Date(); instead, new Date(datainicio).
  2. Care that d.getMonth() returns the month starting at 0, then January is 0, February is 1, etc; so you need to add 1 to generate the correct date.
  3. I used padStart(2, '0') to ensure that the month always has 2 characters, adding the 0 to the left if necessary.

function myFunction() {

  var datainicio = $("#dtini").val();

  const d = new Date(datainicio);

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

  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate();
  
  console.log(`${year}-${month}-${day}`);

  $('#dtfim').attr('min', `${year}-${month}-${day}`);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input id="dtini" type="date" min="2021-02-10" onchange="myFunction()">
<input id="dtfim" type="date">

  • 1

    Showw, thanks for the help, I made a similar code, but when selecting the day 28 January for example, ends up not working..

0

See if that helps you... Here it works every day of the month, different from the answer of the colleague below.

function myFunction() {

  var datainicio = $("#dtini").val();

  let d = new Date(datainicio);
  d.setDate(d.getDate() + 2);

  var dia = String(d.getDate());
  var n = dia.length;
  if(dia.length == 1){
    dia = "0"+dia;
  }
  
  var mes = String(d.getMonth()+1);  
  if(mes.length == 1){
    mes = "0"+mes;
  }

  var a = d.getFullYear()+"-"+mes+"-"+dia;
  $('#dtfim').attr('min',a);
}

  • This would help in the problem of always using the current date as reference instead of the selected one?

  • Don’t be so friendly .... @Woss

  • Boaaaa, working day of the month too, thanks for your help!

Browser other questions tagged

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