[JavaScript] 根据生日计算年龄的JS代码 →→→→→进入此内容的聊天室

来自 , 2019-06-27, 写在 JavaScript, 查看 111 次.
URL http://www.code666.cn/view/17257e81
  1. /**
  2.  * Calculate Age
  3.  *
  4.  * Calculates the amount of time since the date specified with yr, mon, and day.
  5.  * The parameter "countunit" can be "years", "months", or "days" and is the duration
  6.  * between the specified day and today in the selected denomination. The "decimals"
  7.  * parameter allows you to set a decimal place to round to for days and months return
  8.  * values. Rounding is also meant for days and months and can be "roundup" or "rounddown"
  9.  * based solely on the properties of Math.ceil and math.floor respectively.
  10.  * Sample - displayage(1997, 11, 24, "years", 0, "rounddown")
  11.  */
  12. function displayage( yr, mon, day, countunit, decimals, rounding ) {
  13.  
  14.         // Starter Variables
  15.         today = new Date();
  16.         yr = parseInt(yr);
  17.         mon = parseInt(mon);
  18.         day = parseInt(day);
  19.         var one_day = 1000*60*60*24;
  20.         var one_month = 1000*60*60*24*30;
  21.         var one_year = 1000*60*60*24*30*12;
  22.         var pastdate = new Date(yr, mon-1, day);
  23.         var return_value = 0;
  24.  
  25.         finalunit = ( countunit == "days" ) ? one_day : ( countunit == "months" ) ? one_month : one_year;
  26.         decimals = ( decimals <= 0 ) ? 1 : decimals * 10;
  27.  
  28.         if ( countunit != "years" ) {
  29.                 if ( rounding == "rounddown" )
  30.                         return_value = Math.floor ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
  31.                 else
  32.                         return_value = Math.ceil ( ( today.getTime() - pastdate.getTime() ) / ( finalunit ) * decimals ) / decimals;
  33.         } else {
  34.                 yearspast = today.getFullYear()-yr-1;
  35.                 tail = ( today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day ) ? 1 : 0;
  36.                 return_value = yearspast + tail;
  37.         }
  38.  
  39.         return return_value;
  40.  
  41. }
  42. //javascript/2116

回复 "根据生日计算年龄的JS代码"

这儿你可以回复上面这条便签

captcha