Java 中 Date、LocalDateTime 与字符串之间的相互转换

Date 对象转换成时间字符串

案例代码:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = format.format(new Date());
System.out.println(dateStr);

输出结果:

2022-07-30 16:19:45

时间字符串转换成 Date 对象

案例代码:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "2022-07-30 16:19:45";
Date date = format.parse(dateStr);
System.out.println(date);

输出结果:

Sat Jul 30 16:19:45 CST 2022

LocalDateTime 对象转换成时间字符串

案例代码:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
String dateStr = formatter.format(localDateTime);
System.out.println(dateStr);

输出结果:

2022-07-30 16:13:19

时间字符串转换成 LocalDateTime 对象

案例代码:

String dateStr = "2022-07-30 16:13:19";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
System.out.println(localDateTime);

输出结果:

2022-07-30T16:13:19