本工具类主要内容是LocalDateTime与Date的互转以及与日期字符串的互转,可与commons-lang-xxx.jar中的DateUtils配合使用。
import java.time.*; import java.time.format.DateTimeFormatter; import java.util.Date; public class DateTimeUtils { /** * 格式化LocalDateTime实例为日期时间字符串 * * @param localDateTime * @param regex */ public static String format(LocalDateTime localDateTime, String regex) throws Exception { return localDateTime.format(DateTimeFormatter.ofPattern(regex)); } /** * 解析日期时间字符串为LocalDateTime实例 * * @param str * @param regex */ public static LocalDateTime parse(String str, String regex) throws Exception { return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(regex)); } /** * Date实例转为LocalDateTime实例 * * @param date */ public static LocalDateTime Date2LocalDateTime(Date date) throws Exception { LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); System.out.println("localDateTime = " + localDateTime); return localDateTime; } /** * LocalDateTime实例转为Date实例,用到了Instant、ZoneId以及ZoneDateTime * * @param localDateTime */ public static Date LocalDateTime2Date(LocalDateTime localDateTime) throws Exception { Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("date = " + date); return date; } }