java计算两个日期之间的时间间隔

Calendar和Date都没用提供能直接计算两个日期之间时间间隔的api,所以使用了在java8后提供的java.time包下的Duration类来实现,需要先将Date转成java8提供的java.time.LocalDateTime,然后再使用Duration计算两个时间之间的间隔。代码如下:

public String createResponseDurationStr(Date startTime, Date endTime) {
        Calendar
        StringBuilder sb = null;
        if (startTime != null && endTime != null){
            Instant startInstant = startTime.toInstant();
            Instant endInstant = endTime.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime start = startInstant.atZone(zoneId).toLocalDateTime();
            LocalDateTime end = endInstant.atZone(zoneId).toLocalDateTime();
            long days = Duration.between(start,end).toDays();
            long hours = Duration.between(start, end).toHours();
            long minutes = Duration.between(start, end).toMinutes();
            if (days > 0){
                sb = new StringBuilder("");
                sb.append(days).append("天");
            }
            if (hours >= 0){
                sb = sb ==  null ? new StringBuilder("") : sb;
                if (sb.length() > 0 || hours != 0){
                    sb.append(hours).append("小时");
                }
            }
            if (minutes > 0){
                sb = sb ==  null ? new StringBuilder("") : sb;
                sb.append(minutes).append("分钟");
            }
            if (sb != null && sb.length() > 0){
                sb.insert(0,"响应时长: ");
            }
        }
        return sb == null ?  null : sb.toString();
    }

返回示例:

响应时长:1小时5分钟

你可能感兴趣的:(java,java)