1

Why Im getting NaN as a result? Code should cout time in days bettwen two dates. I think that something is off with getting milisec from input date.

function data() {
  let data1 = new Date();
  let data2 = new Date();
  data1 = document.getElementById('pierwszadata');
  data2 = document.getElementById('drugadata');
  let dataN2 = new Date(data2).getTime();
  let dataN1 = new Date(data1).getTime();
  let dni = dataN2 - dataN1;
  dni = dni / 86400000;
  document.write(dni);
}
<html>

<head>
  <script language="javascript" type="text/javascript">
  </script>
</head>

<body>
  <input type="date" id="pierwszadata">
  <input type="date" id="drugadata">
  <input type="button" value="data" onclick="data()">
</body>

</html>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Best Pirat
  • 11
  • 1
  • 2
    you need to write `document.getElementById('pierwszadata').value` – Tobias S. Apr 13 '22 at 18:43
  • 3
    Why are you declaring `data1` and `data2` as new dates just to reassign element references to them? Are you trying to *set* the values of the inputs to the `Date`s generated with `data1` and `data2`? – D M Apr 13 '22 at 18:45
  • As *D M* mentions it, at the time of `new Date(data2)` the OP tries to creates a date object from a DOM element node which results in an `Invalid Date` date type. The return value of `getTime` from the latter is `NaN` and any mathematical computation where `NaN` is/was involved will have `NaN` as end result as well. – Peter Seliger Apr 13 '22 at 18:47
  • 1
    NaN means Not a Number, you are trying to calculate with what is not a number. – Grumpy Apr 13 '22 at 19:04
  • Don't use `document.write()` after the page has been loaded. See https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Barmar Apr 13 '22 at 19:22

1 Answers1

1

Update this lines:

    let dataN2 = new Date(data2.value).getTime();
    let dataN1 = new Date(data1.value).getTime();

You are using data1 instead of data1.value to create the Date

Victor
  • 2,313
  • 2
  • 5
  • 13