以下是相关代码
/**
* 计算当前患者的年龄,超过一岁按照一岁显示,未超过的一岁的按照 (2 15/30) 、未超过48小时的按照小时显示
*
* @param birthday
* @return
*/
public static String calcAge(LocalDateTime birthday) {
LocalDateTime now = LocalDateTime.now();
if (!birthday.isBefore(now)) {
throw new IllegalArgumentException("出生时间必须在当前时间之前");
}
//如果两个时间在48小时内就计算出他们的相差的小时
Duration duration = Duration.between(birthday, now);
if (duration.toHours() < 48) {
long hour = Math.abs(duration.toHours());
return hour + "小时";
}
//计算出多少岁
LocalDate birthDate = birthday.toLocalDate();
LocalDate today = LocalDate.now();
Period agePeriod = Period.between(birthDate, today);
int years = agePeriod.getYears();
if (years > 0) {
return years + "岁";
}
//计算多少个月份和天数
long remainingDays = duration.toDays() % 365;
long months = remainingDays / 30; // 粗略计算月份,实际情况每月天数不同
long days = remainingDays % 30;
// 如果今天是生日,不算多一岁
if (today.getDayOfYear() == birthDate.getDayOfYear()) {
days++;
}
// 对于不满一年的情况,进行详细描述
if (months == 0) {
return "0 " + days + "/30";
} else {
return months + " " + days + "/30";
}
}