java 计算两个时间 的 时分秒 差值,格式 00:00:00

    /**
     * 计算两个时间的 时分秒 差值
     *
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return 时分秒差值 格式 00:00:00
     */
    public static String calculateTimeDifference(Date startDate, Date endDate) {
        if (null == startDate || null == endDate) {
            return "";
        }
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime fromDateTime = LocalDateTime.ofInstant(startDate.toInstant(), zoneId);
        LocalDateTime toDateTime = LocalDateTime.ofInstant(endDate.toInstant(), zoneId);

        LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);

        long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
        tempDateTime = tempDateTime.plusYears(years);

        long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
        tempDateTime = tempDateTime.plusMonths(months);

        long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
        tempDateTime = tempDateTime.plusDays(days);

        long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
        tempDateTime = tempDateTime.plusHours(hours);

        long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
        tempDateTime = tempDateTime.plusMinutes(minutes);

        long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);

        String s = (hours + ":")
                + (minutes + ":")
                + (seconds + "");
        String currentDateTimeStr = DateUtils.getCurrentDateTimeStr();
        String s1 = currentDateTimeStr.substring(0, 11) + s;
        DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd H:m:s");
        DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(s1, inputFormat).format(outputFormat).substring(11);
    }
原文地址:https://www.cnblogs.com/mmh760/p/15479544.html