js根据生日计算年龄的代码

发布时间:2019-08-18编辑:脚本学堂
js代码如何计算年龄,js根据生日求出年龄,js数据函数类Math中常用函数的例子,需要的朋友参考下。

根据生日日期计算年龄

代码:
 

复制代码 代码示例:
/**
 * Calculate Age
 * 求年龄
 */
function displayage( yr, mon, day, countunit, decimals, rounding ) {
 // Starter Variables
 today = new Date();
 yr = parseInt(yr);
 mon = parseInt(mon);
 day = parseInt(day);
 var one_day = 1000*60*60*24;
 var one_month = 1000*60*60*24*30;
 var one_year = 1000*60*60*24*30*12;
 var pastdate = new Date(yr, mon-1, day);
 var return_value = 0;
 
 finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year;
 decimals = ( decimals <= 0 ) ? 1 : decimals * 10;
 
 if ( countunit != "years" ) {
  if ( rounding == "rounddown" )
   return_value = Math.floor ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
  else
   return_value = Math.ceil ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
 } else {
  yearspast = today.getFullYear()-yr-1;
  tail = ( today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day ) ? 1 : 0;
  return_value = yearspast + tail;
 }
 return return_value;
}