Search code examples
javascriptdateevent-listenersubtraction

Subtracting two dates with a submit button


I have a problem with subtracting two dates. It all start with two inputs. One is for date and one is submit button. On paragraph #ekran it needs to show if datePicked is lower than today's date. it will show that we need to pick some date in future. Otherwise it will count difference between today's date and some date that we pick.

When I do like this it says its NaN. I know i messed up somewhere but I don't know where it is. Probably at var d = newDate() that needs to get date formatted correctly. Or I`m wrong? Help me guys.

p.s. It needs to be done in DOM lvl 2 way with eventListener.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="date">
    <input type="submit" value="submit">

    <p id="ekran"></p>


    <script>
     var button = document.querySelector("[type=submit]").addEventListener('click', racunaj);

     function racunaj() {
        var d = new Date();
        d.setDate(30,9,2018);
        var datePicked = document.querySelector("[type=date]").value;

        var diff = document.getElementById("ekran").innerHTML = datePicked;




        if (datePicked< d) {
            "The Picked date need to be bigger then todays date";
        } else {
            return diff;
        }
     }
     </script>
</body>
</html>

Solution

  • You can change your code like this (this is my prev answer which i summed up it to increasing the similarities with your code):

     window.onload=function(){
        document.querySelector("[type='submit']").addEventListener('click', racunaj); 
       function racunaj() {
            var d = new Date();
            d.setDate(30,9,2018);
            var datePicked = new Date(document.querySelector("[type=date]").value); 
            var diff = datePicked.getTime()-d.getTime();
            document.getElementById("ekran").innerHTML=diff<0 ? "The Picked date need to be bigger then todays date" : diff +" (days: "+(diff/1000/60/60/24).toFixed(2)+")";
            return diff;
         }
    }
    

    You can check the result online!