1. 周歲的理解
必須過了生日,才表示滿周歲号俐。例如:
- 2000-10-01出生,當(dāng)前日期是2000-11-01定庵,未滿1周歲吏饿,算0周歲!
- 2000-10-01出生蔬浙,當(dāng)前日期是2005-10-01猪落,未滿5周歲,算4周歲(生日當(dāng)天未過完)畴博!
- 2000-10-01出生笨忌,當(dāng)前日期是2005-10-02,已滿5周歲了俱病!
2. 所謂的“算法”
- 先看“年”蜜唾,用當(dāng)前年份減去生日年份得出年齡age
- 再看“月”,如果當(dāng)前月份小于生日月份庶艾,說明未滿周歲age,年齡age需減1擎勘;如果當(dāng)前月份大于等于生日月份咱揍,則說明滿了周歲age,計算over棚饵!
- 最后“日”煤裙,如果月份相等并且當(dāng)前日小于等于出生日掩完,說明仍未滿周歲,年齡age需減1硼砰;反之滿周歲age且蓬,over!
3. 上代碼题翰!
/**
* 根據(jù)生日計算當(dāng)前周歲數(shù)
*/
public int getCurrentAge(Date birthday) {
// 當(dāng)前時間
Calendar curr = Calendar.getInstance();
// 生日
Calendar born = Calendar.getInstance();
born.setTime(birthday);
// 年齡 = 當(dāng)前年 - 出生年
int age = curr.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if (age <= 0) {
return 0;
}
// 如果當(dāng)前月份小于出生月份: age-1
// 如果當(dāng)前月份等于出生月份, 且當(dāng)前日小于出生日: age-1
int currMonth = curr.get(Calendar.MONTH);
int currDay = curr.get(Calendar.DAY_OF_MONTH);
int bornMonth = born.get(Calendar.MONTH);
int bornDay = born.get(Calendar.DAY_OF_MONTH);
if ((currMonth < bornMonth) || (currMonth == bornMonth && currDay <= bornDay)) {
age--;
}
return age < 0 ? 0 : age;
}