前言
该工具类为自己项目中所写,可以拿来即用,若工具类名称与项目中工具类名称冲突,可自行修改,该工具类主要用于解决计算两个LocalDataTime的时间差值,并直接返回时间差对应的年月日时分秒。
工具类
package com.cdqckj.gmis.common.utils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
/**
* LocalDateTime时间操作工具类,可自行扩展方法
*
* @author wyj
* @date 2021/11/5 10:28
*/
public class LocalDateTimeUtil {
private static final String LOCAL_DATATIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 计算两个时间差值并转换为时分秒 例如: 2021-11-05 09:53:05和2021-11-05 09:53:08 返回结果为3秒
*
* @param start 开始时间
* @param end 结束时间
* @return 时间差值
* @date 2021/11/5 10:30
*/
public static String getTimeTnterval(String start, String end) {
if (Objects.isNull(start) || Objects.isNull(end)) {
return null;
}
return getTimeTnterval(parseStringToDateTime(start), parseStringToDateTime(end));
}
/**
* 计算两个时间差值并转换为时分秒 例如: 2021-11-05 09:53:05和2021-11-05 09:53:08 返回结果为3秒
*
* @param start 开始时间
* @param end 结束时间
* @return 时间差值
* @date 2021/11/5 10:30
*/
public static String getTimeTnterval(LocalDateTime start, LocalDateTime end) {
if (Objects.isNull(start) || Objects.isNull(end)) {
return null;
}
StringBuilder builder = new StringBuilder();
LocalDateTime tempDateTime = LocalDateTime.from(start);
long year = tempDateTime.until(end, ChronoUnit.YEARS);
if (year != 0) {
builder.append(year).append("年");
}
long month = tempDateTime.until(end, ChronoUnit.MONTHS);
if (month != 0) {
builder.append(month).append("月");
}
tempDateTime = tempDateTime.plusMonths(month);
long days = tempDateTime.until(end, ChronoUnit.DAYS);
if (days != 0) {
builder.append(days).append("天");
}
tempDateTime = tempDateTime.plusDays(days);
long hours = tempDateTime.until(end, ChronoUnit.HOURS);
if (hours != 0) {
builder.append(hours).append("小时");
}
tempDateTime = tempDateTime.plusHours(hours);
long minutes = tempDateTime.until(end, ChronoUnit.MINUTES);
if (minutes != 0) {
builder.append(minutes).append("分钟");
}
tempDateTime = tempDateTime.plusMinutes(minutes);
long seconds = tempDateTime.until(end, ChronoUnit.SECONDS);
if (seconds != 0) {
builder.append(seconds).append("秒");
}
return builder.toString();
}
/**
* 将指定时间字符串转换为LocalDateTime
*
* @param time 待转换时间字符串
* @return 转换结果
* @date 2021/11/5 10:35
*/
public static LocalDateTime parseStringToDateTime(String time) {
return LocalDateTime.parse(time, DateTimeFormatter.ofPattern(LOCAL_DATATIME_FORMAT));
}
}