0

I wrote the following JavaScript. But, it does not work. Can please someone suggest what I need to do to get the number of years by subtracting two input dates.

<script type="text/javascript">
$(function () {
  $("#startdate, #enddate").keyup(function () {
    $("#totalyears").val(+$("#enddate").val() - +$("#startdate").val());
  });
 });
</script>

My HTML code:

    <div>
        <label>Start</label>
        <input type="date" name="startdate" id="startdate" autocomplete="off" class="form-control"> 
    </div>
    <div>
        <label>End</label>
        <input type="date" name="enddate" id="enddate" autocomplete="off" class="form-control"> 
    </div>
    <div>
        <label>Total Years</label>
        <input type="date" name="totalyears" id="totalyears" autocomplete="off" class="form-control">   
    </div>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Jack Yuan
  • 72
  • 11

1 Answers1

0

Your inputs are type='date' which means they'll force their values into the yyyy-mm-dd format. You can extract the javascript date object from that, convert it to milliseconds, then find the difference. The result input needs to be type='text' rather than date. Also, I added .toFixed(2) to the years total since it could end up being a long decimal

$(function () {
     $("#startdate, #enddate").keyup(function () {
        var start = new Date($("#startdate").val()).getTime()
        var end = new Date($("#enddate").val()).getTime()
        // check for incomplete data ...
        if (isNaN(start) || isNaN(end)) return;
        // find the difference, then convert back to years
        var years = (end - start) / 1000 / 60 / 60 / 24 / 365
        $("#totalyears").val(years.toFixed(2));
  });
 });


<div>
    <label>Total Years</label>
    <input  name="totalyears" id="totalyears" autocomplete="off" class="form-control">   
</div>
Kinglish
  • 23,358
  • 3
  • 22
  • 43