-1

I have a textfield which takes date of birth as input from user. In another textfield i want to set the age calculated. However, the current date and date of birth are in different formats.

Current Date
Date of birth
Age

The javascript function is as follows:

function todayDate(){

       var currentDate = new Date();
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();
    document.getElementById("date").value = (day + "/" + month + "/" + year);
       }

function ageCalculation(){

       var currentDate = new Date();
    var birthDate = document.getElementById("dob").value;
    alert(birthDate);
    var difference = currentDate - birthDate;
    document.getElementById("age").value = difference ;
       }

In textfield of age I am getting "NaN"

Radhika Kulkarni
  • 298
  • 1
  • 4
  • 19

1 Answers1

0

The Javascript Date constructor and Date.parse function are capable of bringing various date formats into a single representation in order to make date calculations and other operations with Date objects.

Try this:

function ageCalculation(){
    var currentDate = new Date();
    var birthDate = new Date(document.getElementById("dob").value);
    alert(birthDate);
    var difference = currentDate - birthDate;
    document.getElementById("age").value = difference + ' ms';
}

To calculate in years:

var differenceInYears = Math.floor(difference / (1000 * 60 * 60 * 24 * 365.25));

Please, have in mind that this conversion to years is not a precise one due to poor leap year handling. For better precision you might want to implement a better leap year handling algorithm. The best one is mentioned by Rishi in the first comment to your question.

Graham
  • 7,431
  • 18
  • 59
  • 84
Taras
  • 105
  • 1
  • 7