`
leeyb
  • 浏览: 28242 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Java 根据yyyyMMdd 计算 年龄

阅读更多
private static int calcAge(String birthday) {
		int iage = 0;

		if (birthday != "" || birthday != null) {
			int year = Integer.parseInt(birthday.substring(0, 4));
			int month = Integer.parseInt(birthday.substring(4, 6));
			int day = Integer.parseInt(birthday.substring(6, 8));

			Calendar birthDate = new GregorianCalendar(year, month, day);
			Calendar today = Calendar.getInstance();

			if (today.get(Calendar.YEAR) > birthDate.get(Calendar.YEAR)) {
				iage = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR)
						- 1;
				if (today.get(Calendar.MONTH) + 1 > birthDate
						.get(Calendar.MONTH)) {
					iage++;
				} else if (today.get(Calendar.MONTH) + 1 == birthDate
						.get(Calendar.MONTH)) {
					if (today.get(Calendar.DAY_OF_MONTH) > birthDate
							.get(Calendar.DAY_OF_MONTH)) {
						iage++;
					}
				}
			}
			return iage;
		}
		return 0;
	}

  

  PS:这里,today.get(Calendar.MONTH) + 1的原因是发现当前换算出的日历的月份比实际小一月。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics