java时间类--Period时间差计算场景2-年月日时分秒

在这里插入图片描述

写在前面:
时间处理函数不仅仅是一系列的编码逻辑,它们体现了对时间的理解与感知,帮助我们在技术与现实之间建立桥梁。通过这些工具,我们得以更加精准地处理这个看似简单、却极其复杂的概念。时间的流动或许无法被停止,但借助这些工具,开发者得以更好地把握和记录每一个时刻。

我们在平时业务中经常会遇到时间差值计算的场景,比如结束时间距离开始时间的间隔了多少月、多少天、时分秒等要求。

那在实际编码的过程中如何实现呢?

本文将以Java Springboot框架演示如何实现,时间差的计算及差值格式转化。

首先在java8中的java.time时间类型中的类函数 Period.between 可以用来计算两个日期之间的时间差,获取年、月、天等信息。为了支持 String 类型的日期输入,我们可以将字符串解析为 LocalDateTime,然后计算时间差。

如果业务需求要求精确计算时间差并区分到年、月、日、时、分、秒,我们可以结合 java.time.Periodjava.time.Duration,分别用于处理年月日时分秒的部分。

Period 可以计算两个日期的年、月、日差异,Duration 可以计算两个时间的时、分、秒差异。为了支持年月日时分秒的完整计算,我们需要分开处理 LocalDateLocalTime 的部分。

以下是封装的 DateUtils 工具类,支持 String 和 LocalDateTime 类型的输入:

package com.javastudy.springboot3framework.myapp.util;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.*;
/**
 * @author zhizhou   2024/10/21 21:22
 */
public class DateUtils {
   
    // 定义日期时间格式
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 计算时间差,精确到年、月、日、时、分、秒
     * @param startAt 起始日期,支持 String 和 LocalDateTime
     * @param endAt 结束日期,支持 String 和 LocalDateTime
     * @return 返回格式化后的年、月、日、时、分、秒的差异
     */
    public static String calculatePeriodAndDuration(String startAt, String endAt) {
        LocalDateTime startDateTime = parseStringToDateTime(startAt);
        LocalDateTime endDateTime = parseStringToDateTime(endAt);
        return calculatePeriodAndDuration(startDateTime, endDateTime);
    }
    
    public static String calculatePeriodAndDuration(LocalDateTime startAt, LocalDateTime endAt) {
        // 计算年月日
        Period period = Period.between(startAt.toLocalDate(), endAt.toLocalDate());
        
        // 计算时分秒
        Duration duration = Duration.between(startAt.toLocalTime(), endAt.toLocalTime());
        
        long totalSeconds = duration.getSeconds();
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        
        return period.getYears() + " 年, " +
                       period.getMonths() + " 月, " +
                       period.getDays() + " 天, " +
                       hours + " 时, " +
                       minutes + " 分, " +
                       seconds + " 秒";
    }
    
    // 工具方法:解析字符串为 LocalDateTime
    private static LocalDateTime parseStringToDateTime(String dateTime) {
        try {
            return LocalDateTime.parse(dateTime, DATETIME_FORMATTER);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("格式不合法, 请使用yyyy-MM-dd HH:mm:ss");
        }
    }

    

    public static void main(String[] args) {
        // 测试
        System.out.println(calculatePeriodAndDuration("2021-01-15 12:30:15", "2024-10-21 18:45:30"));
        // 输出: 3 年, 9 月, 6 天, 6 时, 15 分, 15 秒
    
        System.out.println(calculatePeriodAndDuration(LocalDateTime.of(2021, 1, 15, 12, 30, 15),
                LocalDateTime.of(2024, 10, 21, 18, 45, 30)));
        // 输出: 3 年, 9 月, 6 天, 6 时, 15 分, 15 秒
    }
}

代码解读说明:

  1. 年月日部分:使用 Period.between 计算 LocalDate 的年、月、日差异。
  2. 时分秒部分:使用 Duration.between 计算 LocalTime 的时、分、秒差异。
  3. 入参支持 StringLocalDateTime:字符串将解析为 LocalDateTime,格式为 yyyy-MM-dd HH:mm:ss
  4. 日期格式支持:支持日期和时间格式为 yyyy-MM-dd HH:mm:ss,可根据需求修改。

示例输出:

// 测试
System.out.println(calculatePeriodAndDuration("2021-01-15 12:30:15", "2024-10-21 18:45:30"));
// 输出: 3 年, 9 月, 6 天, 6 时, 15 分, 15 秒
    
System.out.println(calculatePeriodAndDuration(LocalDateTime.of(2021, 1, 15, 12, 30, 15),
                LocalDateTime.of(2024, 10, 21, 18, 45, 30)));
// 输出: 3 年, 9 月, 6 天, 6 时, 15 分, 15 秒

优点:

  • 精确到年、月、日、时、分、秒:分别处理年月日和时分秒,保证精度。
  • 支持 StringLocalDateTime:根据需求可以使用日期时间字符串或者 LocalDateTime 直接计算。

这样,我们可以在实际应用中处理更精确的时间差计算。

写在最后:

时间都去哪了?昨天法定34了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值