import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtil {
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
private static final String DATE_ERROR_MSG = "日期格式不正确!当前日期格式:";
private static final String STR_ERROR_MSG = "字符串格式不正确!当前字符串格式:";
public static void main(String[] args) {
System.err.println(dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
System.err.println(dateToStr(new Date()));
System.err.println(localDateTimeToStr(LocalDateTime.now(), YYYY_MM_DD_HH_MM_SS));
System.err.println(localDateTimeToStr(LocalDateTime.now()));
System.err.println(strToDate("2023-03-21 14:02:59"));
System.err.println(strToDate("2023-03-21", YYYY_MM_DD));
System.err.println(strToLocalDateTime("2023-03-21 14:20:42"));
System.err.println(dateToLocalDateTime(new Date()));
System.err.println(localDateTimeToDate(LocalDateTime.now()));
}
public static String dateToStr(Date date) {
return dateToStr(date, YYYY_MM_DD_HH_MM_SS);
}
public static String dateToStr(Date date, String format) {
try {
return new SimpleDateFormat(format).format(date);
} catch (RuntimeException e) {
throw new RuntimeException(DATE_ERROR_MSG + format);
}
}
public static Date strToDate(String dateStr) {
return strToDate(dateStr, YYYY_MM_DD_HH_MM_SS);
}
public static Date strToDate(String dateStr, String format) {
try {
return new SimpleDateFormat(format).parse(dateStr);
} catch (ParseException e) {
throw new RuntimeException(STR_ERROR_MSG + dateStr);
}
}
public static String localDateTimeToStr(LocalDateTime localDateTime) {
return localDateTimeToStr(localDateTime, YYYY_MM_DD_HH_MM_SS);
}
public static String localDateTimeToStr(LocalDateTime localDateTime, String format) {
try {
return DateTimeFormatter.ofPattern(format).format(localDateTime);
} catch (RuntimeException e) {
throw new RuntimeException(DATE_ERROR_MSG + format);
}
}
public static LocalDateTime strToLocalDateTime(String localDateTimeStr) {
try {
return LocalDateTime.parse(localDateTimeStr, DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
} catch (RuntimeException e) {
throw new RuntimeException(STR_ERROR_MSG + localDateTimeStr);
}
}
public static LocalDateTime strToLocalDateTime(String localDateTimeStr, String format) {
try {
return LocalDateTime.parse(localDateTimeStr, DateTimeFormatter.ofPattern(format));
} catch (RuntimeException e) {
throw new RuntimeException(STR_ERROR_MSG + localDateTimeStr);
}
}
public static LocalDateTime dateToLocalDateTime(Date date) {
return strToLocalDateTime(dateToStr(date));
}
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
return strToDate(localDateTimeToStr(localDateTime));
}
}
输出结果:
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。