计算不同单位的时间差

July 7, 2019
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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天