/**
* 根据生日获取年龄或者预产期
*
* @param birthday
* @return
* @throws ParseException
*/
public static String getAge(Date birthday) throws ParseException {
StringBuffer str = new StringBuffer();
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
if (birthday.getTime() > Calendartoday.getTime().getTime()) {
long daysBetweennumber = daysBetween(Calendartoday.getTime(), birthday);
long pregnantDays = 280 - daysBetweennumber;
// 算出多少周
int WeekBetweennumber = (int) pregnantDays / 7;
// 零多少天
long dayNumber = pregnantDays % 7;
str.append("孕");
if (WeekBetweennumber > 0) {
str.append(WeekBetweennumber + "周");
}
if (dayNumber > 0) {
str.append(dayNumber + "天");
}
} else {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(birthday);
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_MONTH) - calendar.get(Calendar.DAY_OF_MONTH);
int month = now.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
/**
* 按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。
*/
if (day < 0) {
month -= 1;
now.add(Calendar.MONTH, -1);//得到上一个月,用来得到上个月的天数。
day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
}
if (month < 0) {
month = (month + 12) % 12;
year--;
}
if (year > 0) {
str.append(year + "岁");
}
if (month > 0) {
str.append(month + "个月");
}
if (day > 0) {
str.append(day + "天");
}
/**
* 当预产期或者生日是当天则显示孕40周
*/
if (StringUtil.isNullOrEmpty(str.toString())) {
str.append("孕40周");
}
}
return str.toString();
}