Calculate age from birthdate
I have tw开发者_运维问答o textboxes. The first one is a date, the second one is an age. I have 2 cases :
- I know the birthdate, I fill in the textbox and the age is calculated and displayed in the second textbox, this textbox is readonly
- I don't know the birthdate, I enter an age, no birthdate and no more action
Do you have an idea for the first point ?
Kris,
I had a similar issue and used this page as a ref a while ago:
http://www.javascriptkit.com/javatutors/datedifference.shtml
or this:
http://snippets.dzone.com/posts/show/623
just wrap your call inside the required jquery button click etc.
cheers
Use the dateJS library
--markup--
<input id = "eAge" type = "text"/>
<input type= "button" id = "fAge" value = "find"/>
<input id = "age" type = "text"/>
--jQuery --
$("#fAge").click(function() {
var currentYear = (new Date).getFullYear();
var year = $("#eAge").val().split(',');
$("#age").val(currentYear - year[1]);
});
here's the jsFiddle link to it -- http://jsfiddle.net/GGgqx/
hope it helped
My function:
$('#txtFecha').focusout(function () {
var fecha = document.getElementById('txtFecha').value;
var edad = '';
//supose my date is dd/mm/yyyy
if ((fecha.substring(2,3) != "/") && (fecha.substring(5,6) != "/")) {
edad = '';
}
else {
var dia = fecha.substring(0, 2);
var mes = fecha.substring(3, 5);
var anio = fecha.substring(6, 10);
var diaActual = (new Date).getDay();
var mesActual = (new Date).getMonth();
var anioActual = (new Date).getFullYear();
if (mes > mesActual)
edad = anioActual - anio - 1;
if (mesActual == mes && dia > diaActual)
edad = anioActual - anio - 1;
edad = anioActual - anio;
if (edad < 0 || edad > 100)
edad = '';
}
$("#txt2Edad").val(edad);
});
精彩评论