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";
public static class CurrDateTime {
private Integer currDate = 0;
private Integer currTime = 0;
private Integer currMillisecond = 0;
public Integer getCurrDate() {
return currDate;
}
public void setCurrDate(Integer currDate) {
this.currDate = currDate;
}
public Integer getCurrTime() {
return currTime;
}
public void setCurrTime(Integer currTime) {
this.currTime = currTime;
}
public Integer getCurrMillisecond() {
return currMillisecond;
}
public void setCurrMillisecond(Integer currMillisecond) {
this.currMillisecond = currMillisecond;
}
}
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));
}
/**
* 获取当前日期和时间信息
*
* @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;
}
}