0

i have source code php form there's a inputtext about date (YYYY/mm/dd) and i want to automate calculate the diff between input date and i want use javascript(jquery) after i finish input the diff date show ... years in textbox it's my code:

date.php

<form action="url.php" method="post">
    .........
    <input type:"text" name="date" id="date"/>
    .........
    <input type:"text" name="dur" id="dur" disabled="disable"/>
</form>

my javascript

function calc(){
   var now = new Date();
   var month = ("0"+(now.getMonth()+1)).slice(-2);
   var month = ("0"+now.getDate()).slice(-2);
   var year = now.getFullYear();
   var date = month+" / "+day+" / "+year;
   var date_form = $('#date').val();

   $('#dur').val(date - date_form);
}

and when i run the value of dur its show NaN

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

1 Answers1

0

Here you have to pass the dates on change event of your input box and you will get the difference of year between two dates.

function getYearDiff(startDate, endDate) {
    let yearDiff = endDate.getFullYear() - startDate.getFullYear();
    if (startDate.getMonth() > endDate.getMonth()) {
        yearDiff--;
    } else if (startDate.getMonth() === endDate.getMonth()) {
        if (startDate.getDate() > endDate.getDate()) {
            yearDiff--;
        } else if (startDate.getDate() === endDate.getDate()) {
            if (startDate.getHours() > endDate.getHours()) {
                yearDiff--;
            } else if (startDate.getHours() === endDate.getHours()) {
                if (startDate.getMinutes() > endDate.getMinutes()) {
                    yearDiff--;
                }
            }
        }
    }
    return yearDiff;
}

alert(getYearDiff(firstDate, secondDate));

Ref: How can I calculate the number of years betwen two dates?

dekts
  • 744
  • 4
  • 19