0

I have a MVC View which the user can enter 2 dates. The Controller makes the correct calculations, however I want the amount of days to be shown immediatly. So I added some Javascript to the page.


        <div class="col-md-10">
            <input type="date" name="DateOut" min=@DateTime.Now.ToString("yyyy-MM-dd") id="date_out" onchange="showDates()">
        </div>
    </div>

    <text>Until:</text>
    <div class="form-group">

        <div class="col-md-10">
            <input type="date" name="DateIn" min=@DateTime.Now.ToString("yyyy-MM-dd") id="date_in" onchange="showDates()">
        </div>
    </div>
<script>
    function showDates() {
        document.getElementById("show_amount_of_days").innerHTML =  document.getElementById("date_in").value - document.getElementById("date_out").value;
    }
 </script>

The problem is that the element seems to be a string and not a date type, so Javascript is unable to calculate the days.

How do I fix this?

Roger
  • 11
  • 4
  • You would have to use something like `(new Date(string1) - new Date(string2)) / 86400000` to get days. –  Feb 11 '20 at 21:49

1 Answers1

-1

try doing it this way:

var dateOut= new Date(document.getElementById("date_out").value);
var dateIn= new Date(document.getElementById("date_in").value);

var difference = dateOut - dateIn;

var days = difference/(24*3600*1000);

original answer: https://stackoverflow.com/a/23733511/9157015

Kamil Z
  • 181
  • 12
  • Please don’t answer questions which can be answered by other questions’ answers. Once you get enough rep, you can flag them as duplicates. – Heretic Monkey Feb 11 '20 at 21:54