根据生日计算年龄的JS代码
来源:自学PHP网
时间:2014-09-19 14:47 作者:
阅读:次
[导读] 本文章来给大家介绍计算年龄一个js代码,他是根据生日计算年龄了,原理当时时间减去你出生时间就等于你的年龄了算法相当简单这里就说多了。...
例
代码如下 |
复制代码 |
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;
}
|
|