<script>
function parseDate(str){
if(str.match(/^\d{4}[\-\/\s+]\d{1,2}[\-\/\s+]\d{1,2}$/)){
return new Date(str.replace(/[\-\/\s+]/i,'/'))
}else if(str.match(/^\d{8}$/)){
return new Date(str.substring(0,4)+'/'+str.substring(4,6)+'/'+str.substring(6))
}else{
alert('date parse error')
}
}
function getAge(){
var age;
var aDate=new Date();
var thisYear=aDate.getFullYear();
var thisMonth=aDate.getMonth()+1;
var thisDay=aDate.getDate();
var brith=parseDate(document.getElementById("date1").value);
brithy=brith.getFullYear();
brithm=brith.getMonth();
brithd=brith.getDate();
if(thisYear-brithy<0)
{
alert("输入错误!");
age="";
}
else
{
if(thisMonth-brithm<0)
{
age = thisYear-brithy-1;
}
else
{
if(thisDay-brithd>=0)
{//alert(thisDay+'-'+brithd+"_ddd");
age = thisYear-brithy;
}
else
{
age = thisYear-brithy-1;
}
}
}
document.getElementById("date2").value=age;
}
</script>
<from name="theform">
生日:<input name="date1" id="date1" onblur="getAge()">
年龄:<input name="date2" id="date2">
</form>
上面代码支持传统的日期格式:2008-06-11,2008-6-14
还有个问题:输入:2008-6-55,就没反应了~
function parseDate(str){
if(str.match(/^\d{4}[\-\/\s+]\d{1,2}[\-\/\s+]\d{1,2}$/)){
return new Date(str.replace(/[\-\/\s+]/i,'/'))
}else if(str.match(/^\d{8}$/)){
return new Date(str.substring(0,4)+'/'+str.substring(4,6)+'/'+str.substring(6))
}else{
alert('date parse error')
}
}
function getAge(){
var age;
var aDate=new Date();
var thisYear=aDate.getFullYear();
var thisMonth=aDate.getMonth()+1;
var thisDay=aDate.getDate();
var brith=parseDate(document.getElementById("date1").value);
brithy=brith.getFullYear();
brithm=brith.getMonth();
brithd=brith.getDate();
if(thisYear-brithy<0)
{
alert("输入错误!");
age="";
}
else
{
if(thisMonth-brithm<0)
{
age = thisYear-brithy-1;
}
else
{
if(thisDay-brithd>=0)
{//alert(thisDay+'-'+brithd+"_ddd");
age = thisYear-brithy;
}
else
{
age = thisYear-brithy-1;
}
}
}
document.getElementById("date2").value=age;
}
</script>
<from name="theform">
生日:<input name="date1" id="date1" onblur="getAge()">
年龄:<input name="date2" id="date2">
</form>
上面代码支持传统的日期格式:2008-06-11,2008-6-14
还有个问题:输入:2008-6-55,就没反应了~
function getAge(birthday){
birthday = birthday.split("-");
var birthday_year = birthday[0];
var now_year = new Date().getYear() + 1900;
var age = now_year - birthday_year + 1;
document.getElementById("birthday").value = age;
}
</script>生日:<input onblur="getAge(this.value)">
年龄:<input id="birthday">
day= (day< 10) ? ('0' + day) : day;