计算不同单位的时间差

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天

上一篇:2019-07-25 记录一个bug,插入更新sql-ON DUPLICATE KEY UPDATE


下一篇:POJ - Period(KMP)