写在前面:
时间处理函数不仅仅是一系列的编码逻辑,它们体现了对时间的理解与感知,帮助我们在技术与现实之间建立桥梁。通过这些工具,我们得以更加精准地处理这个看似简单、却极其复杂的概念。时间的流动或许无法被停止,但借助这些工具,开发者得以更好地把握和记录每一个时刻。
我们在平时业务中经常会遇到时间差值计算的场景,比如结束时间距离开始时间的间隔了多少月、多少天、时分秒等要求。
那在实际编码的过程中如何实现呢?
本文将以Java Springboot框架演示如何实现,时间差的计算及差值格式转化。
首先在java8中的java.time时间类型中的类函数 Period.between 可以用来计算两个日期之间的时间差,获取年、月、天等信息。为了支持 String 类型的日期输入,我们可以将字符串解析为 LocalDateTime,然后计算时间差。
如果业务需求要求精确计算时间差并区分到年、月、日、时、分、秒,我们可以结合 java.time.Period
和 java.time.Duration
,分别用于处理年月日和时分秒的部分。
Period
可以计算两个日期的年、月、日差异,Duration
可以计算两个时间的时、分、秒差异。为了支持年月日时分秒的完整计算,我们需要分开处理 LocalDate
和 LocalTime
的部分。
以下是封装的 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 秒
}
}
代码解读说明:
- 年月日部分:使用
Period.between
计算LocalDate
的年、月、日差异。 - 时分秒部分:使用
Duration.between
计算LocalTime
的时、分、秒差异。 - 入参支持
String
和LocalDateTime
:字符串将解析为LocalDateTime
,格式为yyyy-MM-dd HH:mm:ss
。 - 日期格式支持:支持日期和时间格式为
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 秒
优点:
- 精确到年、月、日、时、分、秒:分别处理年月日和时分秒,保证精度。
- 支持
String
和LocalDateTime
:根据需求可以使用日期时间字符串或者LocalDateTime
直接计算。
这样,我们可以在实际应用中处理更精确的时间差计算。
写在最后:
时间都去哪了?昨天法定34了。