Getting Age Automatically When Given Date Of Birth
I wanted to get the age of a person from his date of birth. I have a HTML code where I'm using a datepicker for dob, when I give the date-of-birth it show automatically show the ag
Solution 1:
You can try using this function as your onSelect
event handler instead:
$('#dob').datepicker({
onSelect: function(value, ui) {
var today = newDate(),
dob = newDate(value),
age = newDate(today - dob).getFullYear() - 1970;
$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true
});
This should be very accurate (and much better than my old code), since everything's been handed off to the native Date
object.
See a simple demonstration of this here: http://www.jsfiddle.net/yijiang/PHvYK/1
Solution 2:
functiongetAge(birth) {
var today = newDate();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) returnparseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) returnparseInt(curr_year-birth_year-1);
if (curr_month > birth_month) returnparseInt(curr_year-birth_year);
if (curr_month < birth_month) returnparseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Solution 3:
If you subtract two Date
objects in javascript, you get their difference in milliseconds so ( BDate - (new Date()) )/365.25/24/60/60/1000
will give you an age result that should be accurate to within a day. (i.e. if their birthday is today and its a leap year it may be inaccurate)
Solution 4:
<scripttype="text/javascript">
$(function() {
$('#dtp').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
//firstDay: 1,onSelect: function(dateText, inst) {
var d = newDate(Date.parse(inst.lastVal));
var diff = (newDate()).getFullYear() - d.getFullYear();
document.getElementById('AGE').value = diff;
}
});
});
</script>
Solution 5:
Try This Code very simple
functionagefinding()
{
var birthDay = document.getElementById("TxtDOB").value;
varDOB = newDate(birthDay);
var today = newDate();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
// alert(age);return age;
}
this is very simple to find the age using javascript
Post a Comment for "Getting Age Automatically When Given Date Of Birth"