Java日期时间工具类

在开发过程中经常会用到日期相关的计算,这里进行总结,后续不断进行方法的增加。

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @Description 日期时间工具类
* @Author Maverickos
* @Date 2023-08-17
*/
public class DateTimeUtil {
private static final String DATETIME_FORMATTER = "yyyyMMdd HH:mm:ss";
private static final String DATE_FORMATTER = "yyyyMMdd";
private static final String TIME_FORMATTER = "HHmmss";
private static final String TIME_MILLISECOND_FORMATTER = "HHmmssSSS";
@Data
public static class CurrDateTime {
private Integer currDate = 0;
private Integer currTime = 0;
private Integer currMillisecond = 0;
}
public static void main(String[] args) {
CurrDateTime currDateTime = getCurrDateTime();
System.out.println("日期: " + currDateTime.getCurrDate());
System.out.println("时间(秒): " + currDateTime.getCurrTime());
System.out.println("时间(毫秒): " + currDateTime.getCurrMillisecond());
System.out.println(addDate(currDateTime.getCurrDate(), -100));
System.out.println(addTimeBySecond(currDateTime.getCurrTime(), -3600));
}
/**
* 获取当前日期和时间信息
*
* @return 获取当前日期、当前时间、当前秒、当前毫秒
*/
public static CurrDateTime getCurrDateTime() {
CurrDateTime currDateTime = new CurrDateTime();
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMATTER);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(TIME_FORMATTER);
DateTimeFormatter timeMillisecondFormatter = DateTimeFormatter.ofPattern(TIME_MILLISECOND_FORMATTER);
currDateTime.setCurrDate(Integer.valueOf(dateFormatter.format(now)));
currDateTime.setCurrTime(Integer.valueOf(timeFormatter.format(now)));
currDateTime.setCurrMillisecond(Integer.valueOf(timeMillisecondFormatter.format(now)));
return currDateTime;
}
/**
* 给定间隔天数,计算输入日期往前或往后对应的日期
*
* @param date 输入日期
* @param interval 间隔天数
* @return
*/
public static Integer addDate(Integer date, Integer interval) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMATTER);
// dateFormat此时输出格式为2001-01-01
LocalDate dateFormat = LocalDate.parse(String.valueOf(date), dateFormatter);
LocalDate nextDate = dateFormat.plusDays(interval);
Integer result = Integer.valueOf(dateFormatter.format(nextDate));
return result;
}
/**
* 给定间隔秒数,获取当前时间间隔后对应的时间
*
* @param currTime
* @param interavalSecond————往前计算则送入负数
* @return
*/
public static int addTimeBySecond(int currTime, int interavalSecond) {
DateTimeFormatter secondFormatter = DateTimeFormatter.ofPattern(TIME_FORMATTER);
// dateFormat此时输出格式为:12:00:00
LocalTime dateFormat = LocalTime.parse(String.valueOf(currTime), secondFormatter);
LocalTime nextTime = dateFormat.plusSeconds(interavalSecond);
// 12:00:00 转化格式为 120000
Integer result = Integer.valueOf(secondFormatter.format(nextTime));
return result;
}
}
posted @   Maverickos  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示