jsは生年月日で年齢を取得します.
1642 ワード
jsは生年月日と現在の日付を比較して年齢を取得します.コードは以下の通りです.処理が不十分なところはご了承ください.ありがとうございます.
/**
* @uses , :2016-09-23
* @param string birthday
* @return string|number
**/
function getAge(birthday) {
let iage = 0;
if (!$.isNull(birthday)) {
//
let year = this.getYmd(birthday,'y');
let month = this.getYmd(birthday, 'm');
let day = this.getYmd(birthday, 'd');
//
let myDate = new Date();
let now_year = myDate.getFullYear();
let now_month = myDate.getMonth()+1;
let now_day = myDate.getDate();
if (now_year > year) {
iage = now_year - year - 1;
if (now_month > month) {
iage++;
} else if (now_month == month) {
if (now_day >= day) {
iage++;
}
}
}
}
return iage;
},
/**
* @uses , :2016-09-23
* @param string s
* @param string type y m d
* @return string|number
**/
function getYmd(s,type) {
// var s = "2010-5-6";
let a = s.split("-");
if (a.length > 2) {
let y = a[0];
let m = a[1];
let d = a[2];
console.log('y:'+y,'m:'+m,'d:'+d)
let returnStr = '';
switch(type){
case 'y':
returnStr = y;
break;
case 'm':
returnStr = m;
break;
case 'd':
returnStr = d;
break;
default:
returnStr = '';
break;
}
return returnStr;
}else{
return '';
}
}