给定生日,怎么计算年龄

cyberworm 2003-12-03 01:50:06
给定一个如1980-03-22的字符串,怎么计算出它代表的年龄?
...全文
932 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cyberworm 2003-12-03
  • 打赏
  • 举报
回复
很好用,谢谢
rongwenfeng 2003-12-03
  • 打赏
  • 举报
回复
<script language=javascript>
function checkDate( date ) {
if ( date == null || date == "" ) {
return true;
}

var strDate = date;

if (NumberFormat( strDate ))
{

if (strDate.length != 10) {
alert( "错误的日期!" );
return false ;
}

if ( toDateFromString( strDate ) == null ) {
alert("错误的日期!");
return false;
}
}

return true ;
}

function NumberFormat(pstrNum)
{
var strReturn = "";

strNumber = ""+delMoji(pstrNum,"-");

for(var i=0; i<strNumber.length; i++)
{
if (strNumber.charAt(i) >= "0" && strNumber.charAt(i) <= "9")
{

}
else if (strNumber.charAt(i) == "+" || strNumber.charAt(i) == "-" || strNumber.charAt(i) == ".")
{
alert("错误的日期!");
return false;
}
}

return true;
}

function delMoji(pstrMoji, pstrChar)
{
var strReturn ="";
for(var i=0; i<pstrMoji.length; i++)
{
if (pstrMoji.charAt(i) != pstrChar)
{
strReturn = strReturn + pstrMoji.charAt(i);
}
}
return strReturn;
}

function toDateFromString( strDate )
{
var dtDate = null ;
var nYear = parseInt( strDate.substring( 0, 4 ), 10 ) ;
var nMonth = parseInt( strDate.substring( 5, 7 ), 10 ) ;
var nDay = parseInt( strDate.substring( 8, 10 ), 10 ) ;

if( isNaN( nYear ) == true || isNaN( nMonth ) == true || isNaN( nDay ) == true )
{
return null ;
}
dtDate = new Date( nYear, nMonth - 1, nDay ) ;
if( nYear != dtDate.getFullYear() || ( nMonth - 1 ) != dtDate.getMonth() || nDay != dtDate.getDate() )
{
return null ;
}

return dtDate ;
}
function ages(str)
{
if(checkDate(str))
{
var Y = new Date().getFullYear();
var age;
age = parseInt(Y) - parseInt(str.substr(0,4))
return age
alert();
}
}
</script>
bzscs 2003-12-03
  • 打赏
  • 举报
回复
<script language="vbScript">
birthday="1980-03-22"
msgbox(datediff("yyyy",cdate(birthday),now))
</script>
ricky460 2003-12-03
  • 打赏
  • 举报
回复
<script>
function CurAge(str)
{
var pos = str.indexOf("-");
var bir = str.substring(0,pos);
var time = new Date();
var year = time.getYear();
var age = parseInt(year) - parseInt(bir);
alert(age);
}
</script>
hrong 2003-12-03
  • 打赏
  • 举报
回复
<script language=javascript>
function ages(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
if (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4])
{
var Y = new Date().getFullYear();
return("年龄 = "+ (Y-r[1]) +" 周岁");
}
return("输入的日期格式错误!");
}
alert(ages("1980-03-22"));
alert(ages("2002-01-31"));
alert(ages("2002-01-41"));
</script>

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧