【方法记录】java封装方法 传入 localdatetime1 localdatetime2 得出二者差值转成 HH:mm:ss 字符串格式返回

文章目录

概要

java封装方法 传入 localdatetime1 localdatetime2 得出二者差值转成 HH:mm:ss 字符串格式返回

import java.time.Duration;  
import java.time.LocalDateTime;  
import java.time.format.DateTimeFormatter;  
  
public class TimeDifferenceUtil {  
  
    /**  
     * 计算两个LocalDateTime之间的时间差,并返回格式为HH:mm:ss的字符串  
     *  
     * @param localDateTime1 第一个时间  
     * @param localDateTime2 第二个时间  
     * @return 两个时间之间的时间差,格式为HH:mm:ss  
     */  
    public static String getTimeDifferenceAsString(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {  
        // 确保localDateTime1早于或等于localDateTime2  
        if (localDateTime1.isAfter(localDateTime2)) {  
            LocalDateTime temp = localDateTime1;  
            localDateTime1 = localDateTime2;  
            localDateTime2 = temp;  
        }  
  
        // 计算时间差  
        Duration duration = Duration.between(localDateTime1, localDateTime2);  
  
        // 将时间差转换为秒  
        long seconds = duration.getSeconds();  
  
        // 转换秒为时、分、秒  
        int hours = (int) (seconds / 3600);  
        int minutes = (int) ((seconds % 3600) / 60);  
        int secs = (int) (seconds % 60);  
  
        // 使用DateTimeFormatter格式化可能不是最直接的方式,但为了格式统一,这里我们使用String.format  
        String timeDifference = String.format("%02d:%02d:%02d", hours, minutes, secs);  
  
        // 如果你想使用DateTimeFormatter,可以这样做(但更适用于处理日期和时间)  
        // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");  
        // 注意:DateTimeFormatter不能直接用于Duration,因为它不是为处理时长设计的  
  
        return timeDifference;  
    }  
  
    public static void main(String[] args) {  
        LocalDateTime now = LocalDateTime.now();  
        LocalDateTime later = now.plusHours(1).plusMinutes(30).plusSeconds(15);  
        String timeDifference = getTimeDifferenceAsString(now, later);  
        System.out.println("Time difference: " + timeDifference); // 输出:Time difference: 01:30:15  
    }  
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值