1

I'm using 3 different lists to get date of birth from user and then trying to calculate the age of user with JavaScript but failed please do help.

How to calculate difference between variables dob and crntDate?

Code snippet:

function calculateDOB()
{
  var day = document.getElementById("signUpDate").value;
  var mnth = document.getElementById("signUpMnth").value;
  var year = document.getElementById("signUpYear").value;
  var dob = day+"/"+mnth+"/"+year;
  var crntDate = Date();
}
DNA
  • 42,007
  • 12
  • 107
  • 146
anil
  • 231
  • 1
  • 9
  • var diff = dob.getDate()-crntDate.getDate(); not working that is with direct input but how can i do it with variable or a suggestion for other way arround – anil Mar 04 '15 at 22:22

1 Answers1

2

Your dob is String. You should convert to date and use .getTime() to calculate it. Below is some example, hope it will help.

function calc() {
  var day = document.getElementById("signUpDate").value;
  var mth = document.getElementById("signUpMnth").value;
  var year = document.getElementById("signUpYear").value;
  
  var today = new Date();
  var dob = new Date(year, mth, day);
  
  var diff = today.getTime() - dob.getTime();
  alert("Day " + Math.ceil((diff / 24 / 60 / 60 / 1000)));
}
<input id="signUpDate" maxlength="2" size="2" value="1">
<select id="signUpMnth">
  <option value="0">Jan</option>
  <option value="1">Feb</option>
  <option value="2" selected>Mar</option>
  <option value="3">Apr</option>
  <option value="4">May</option>
  <option value="5">Jun</option>
  <option value="6">Jul</option>
  <option value="7">Aug</option>
  <option value="8">Sep</option>
  <option value="9">Oct</option>
  <option value="10">Nov</option>
  <option value="11">Dec</option>
</select>
<input id="signUpYear" maxlength="4" size="4" value="2015">
<input type="button" onClick="calc()" value="test">
Joey Chong
  • 1,470
  • 15
  • 20