DEV Community

Cover image for Calcular los días entre dos fechas ingresadas Javascript
Verónica Guamán
Verónica Guamán

Posted on • Edited on

13

Calcular los días entre dos fechas ingresadas Javascript

Me acabo de topar con este caso, tengo que calcular los días que existen entre dos fechas ingresadas por el usuario a través de un input.

Después de buscar tanto encontré la siguiente solución, la adapte y realice algunas validaciones, funciono para mí así que se las comparto.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calcular los días entre dos fechas</title>
</head>
<body>
    <label>Fecha de inicio</label>
    <input type="date" id="timeStart" class="form-control" oninput="calculardiasDiscount()">
    <label>Fecha fin</label>
    <input type="date" id="timeEnd" class="form-control" oninput="calculardiasDiscount()">
    <label>Días</label>
    <input class="form-control" id="daysDiscount">
</body>
</html>                                                                                 
Enter fullscreen mode Exit fullscreen mode

y en el Javascript colocamos lo siguiente

<script>
function calculardiasDiscount() {
        var timeStart = new Date(document.getElementById("timeStart").value);
        var timeEnd = new Date(document.getElementById("timeEnd").value);
        var actualDate = new Date();
        if (timeEnd > timeStart)
        {
            var diff = timeEnd.getTime() - timeStart.getTime();
            document.getElementById("daysDiscount").value = Math.round(diff / (1000 * 60 * 60 * 24));
        }
        else if (timeEnd != null && timeEnd < timeStart) {
            alert("La fecha final de la promoción debe ser mayor a la fecha inicial");
            document.getElementById("daysDiscount").value = 0;
        }
    }
</script>
Enter fullscreen mode Exit fullscreen mode

Esto funcionó para mí, si tiene alguna sugerencia pueden dejarla en los comentarios para que las demás personas puedan verlo.

Nos vemos en Twitter e Instagram ;)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
daruiz23 profile image
DaRuiz23

hola esta interesante el código me sirvió bastante, una consulta abras hecho multiplicar con otro input ??

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs