0

Taking the user input for date using

<input type="date" id="date1" onchange='leavenumber();'/>
<input type="date" id="date2" onchange='leavenumber();'/>

I want to calculate the difference between two dates using javascript.

I have tried using below function but it doesnot work:

var leavenumber = function(){
        const date1 = document.getElementById("date1").value;
        const date2 = document.getElementById("date2").value;
        const diffTime = Math.abs(date2 - date1);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        console.log(diffDays);
       }
Error
  • 133
  • 2
  • 10
  • Does this answer your question? [How to calculate date difference in JavaScript?](https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) – dmuensterer Apr 24 '20 at 13:30
  • No, it returns NaN instead. – Error Apr 24 '20 at 13:36
  • @Error No, it doesn’t. The top answer starts with _“Assuming you have two `Date` objects”_. Neither `date1` nor `date2` are `Date` objects. With proper `Date` objects from correctly filled out ``s, you won’t get `NaN`. – Sebastian Simon Dec 14 '21 at 19:33

2 Answers2

1

Instead of document.getElementById("date").value you should use document.getElementById("date").valueAsDate which gives you a Date object instead of a raw string which can be used for further calculations.

flappix
  • 2,038
  • 17
  • 28
-1

I suggest using the library Moment.js. This way you can measure the difference very easily - in days, hours, etc. I give you example with difference measured in days.

var leavenumber = function(){
        var date1 = moment(document.getElementById("date1").value);
        var date2 = moment(document.getElementById("date2").value);
        if (date1.isValid() && date2.isValid()) {
            console.log(date1.diff(date2, 'days'))
        }
       }

Working Fiddle

antanta
  • 618
  • 8
  • 16