public static String getTimeGap(Date startTime, Date endTime) {
Duration duration = Duration.between(Instant.ofEpochMilli(startTime.getTime()), Instant.ofEpochMilli(endTime.getTime()));
Period period = Period.ofDays((int) duration.toDays());
long yearGap = period.getYears();
if (yearGap != 0) {
return yearGap + "年前";
}
long monthGap = period.getMonths();
if (monthGap != 0) {
return monthGap + "个月前";
}
long dayGap = period.getDays();
long weekGap = dayGap / 7;
if (weekGap != 0) {
return weekGap + "周前";
}
if (dayGap != 0) {
return dayGap + "天前";
}
long hourGap = duration.toHours();
if (hourGap != 0) {
return hourGap + "小时前";
}
long minuteGap = duration.toMinutes();
if (minuteGap != 0) {
return minuteGap + "分钟前";
}
long secondGap = duration.getSeconds();
return secondGap + "秒前";
}
Duration:基于时间的时间量,如34.5s
Period:基于日期的时间量,如2年3个月4天