Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
Calcule la duración de la fecha de inicio y la fecha de finalización desde un formulario HTML

Me pregunto si alguien puede señalarme alguna documentación sobre cómo resolver mi problema. Todavía nuevo en JS nativo, y buscando hacer algunos cálculos de fechas.

Básicamente, necesito calcular la duración entre las fechas X e Y y la fecha del tipo de entrada de formularios HTML.

Tengo un boceto aproximado de mi HTML y JS... pero aún no puedo resolver el problema sin la guía y la documentación adecuadas.

 <div> <form> <label for="start-date"></label> <input type="date" id="start-date"> <label for="end-date"></label> <input type="date" id="end-date"> <label for="duration"></label> <input type="text" id="duration"> </form> </div>
 const startDate = document.getElementById("start-date").value const endDate = document.getElementById("end-date").value let duration_from_form = document.getElementById("duration").value let duration = endDate - startDate; if (duration_from_form === ""){ duration_from_form = duration; } }

Sé que ambos son maquetas aproximadas y no ideales, pero me encantaría que me ayudaran a encontrar la documentación adecuada sobre este asunto. Atentamente

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

 function getTimeBetweenDates(e) { var date1 = new Date(document.getElementById("date1").value); var date2 = new Date(document.getElementById("date2").value); var diff; if (date1 < date2) { diff = new Date(date2 - date1); } else { diff = new Date(date1 - date2); } var years = (diff.getFullYear() - 1970); var months = diff.getMonth(); var days = diff.getDate(); var yearTxt = "year"; var monthTxt = "month"; var dayTxt = "day"; if (years > 1) yearTxt += "s"; if (months > 1) monthTxt += "s"; if (days > 1) dayTxt += "s"; if (years >= 0) { document.getElementById("showdiff").innerHTML = years + " " + yearTxt + ", " + months + " " + monthTxt + ", " + days + " " + dayTxt; } else { document.getElementById("showdiff").innerHTML = "Equal dates"; } }
 <form id="form1" action="" method="" onSubmit="event.preventDefault(); getTimeBetweenDates();"> <input type="date" id="date1"> <input type="date" id="date2"> </form> <br> <button type="submit" form="form1" value="Send">Send</button> <br> <p id="showdiff"></p>

about 4 years ago · Juan Pablo Isaza Relatório

0

Si desea cálculos de fecha y más documentación sobre cómo jugar con fechas, intente esto, Fechas -JS MDN

Pero si está buscando establecer el valor en el campo, entonces

 document.getElementById("duration").value = duration

debe escribirse en el evento onChange del campo, más sobre eso aquí ingrese la descripción del enlace aquí

about 4 years ago · Juan Pablo Isaza Relatório

0

Así es como puede encontrar su diferencia de fecha con la ayuda de Jquery

 const setup = () => { let firstDate = $('#start-date').val(); let secondDate = $('#end-date').val(); const findTheDifferenceBetweenTwoDates = (firstDate, secondDate) => { firstDate = new Date(firstDate); secondDate = new Date(secondDate); let timeDifference = Math.abs(secondDate.getTime() - firstDate.getTime()); let millisecondsInADay = (1000 * 3600 * 24); let differenceOfDays = Math.ceil(timeDifference / millisecondsInADay); return differenceOfDays; } let result = findTheDifferenceBetweenTwoDates(firstDate, secondDate); $("#duration").val(result); } $(document).ready(function () { $('#start-date').change(function () { if($('#end-date').val()!='') { setup(); } }) $('#end-date').change(function () { if($('#start-date').val()!='') { setup(); } }) });
 .container { position: absolute; top: 10%; width: 100%; text-align: center; color: black; font-style: italic; font-family: avenir; margin: 10px; } input { width: 20%; height: 30px; font-family: avenir; } input:focus { color: black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <form> <label for="start-date"></label> <input type="date" id="start-date"> <label for="end-date"></label> <input type="date" id="end-date"> <label for="duration"></label> <input type="text" id="duration" placeholder="Difference"> </form> </div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda