编写时间类的工具类
时间工具类DateTimeUtil
package com.kang.redisson.utils;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
public class DateTimeUtil {
private static final String DATE_FORMATTER = "yyyy-MM-dd";
private static final String DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
public static LocalDateTime localDateToLocalDateTime(LocalDate localDate) {
if(Objects.isNull(localDate)){
return null;
}
return localDate.atStartOfDay();
}
public static LocalDate localDateTimeToLocalDate(LocalDateTime localDateTime) {
if(Objects.isNull(localDateTime)){
return null;
}
return localDateTime.toLocalDate();
}
public static LocalDateTime dateToLocalDateTime(Date date) {
if(Objects.isNull(date)){
return null;
}
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
if(Objects.isNull(localDateTime)){
return null;
}
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static Date localDateToDate(LocalDate localDate) {
if(Objects.isNull(localDate)){
return null;
}
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate dateToLocalDate(Date date) {
if(Objects.isNull(date)){
return null;
}
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();
}
public static String localDateToString(LocalDate localDate) {
if(Objects.isNull(localDate)){
return null;
}
return localDate.format(DateTimeFormatter.ofPattern(DATE_FORMATTER));
}
public static String localDateTimeToString(LocalDateTime localDateTime) {
if(Objects.isNull(localDateTime)){
return null;
}
return localDateTime.format(DateTimeFormatter.ofPattern(DATE_TIME_FORMATTER));
}
public static String dateToString(Date date) {
if(Objects.isNull(date)){
return null;
}
return new SimpleDateFormat(DATE_TIME_FORMATTER).format(date);
}
public static LocalDate stringToLocalDate(String dateString) {
if(StringUtils.isBlank(dateString)){
return null;
}
return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(DATE_FORMATTER));
}
public static LocalDateTime stringToLocalDateTime(String dateTimeString) {
if(StringUtils.isBlank(dateTimeString)){
return null;
}
return LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern(DATE_TIME_FORMATTER));
}
public static Date stringToDate(String dateString) {
if(StringUtils.isBlank(dateString)){
return null;
}
try {
return new SimpleDateFormat(DATE_TIME_FORMATTER).parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}