LocalDateTime转String
方法一:使用LocalDateTimeUtil工具类进行式化
LocalDateTime localDateTime = LocalDateTime.now();
String time =LocalDateTimeUtil.format(localDateTime,DatePattern.NORM_DATETIME_PATTERN);
其中:DatePattern类是日期格式化类,提供常用的日期格式化对象。
方法二:使用DateUtil工具类,需要导入hutool包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.10</version>
</dependency>
LocalDateTime localDateTime = LocalDateTime.now();
String time = DateUtil.format(localDateTime, "yyyyMMdd");
方法三:使用DateTimeFormatter格式化
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = LocalDateTime.now().format(df);
String转LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.parse("2022-03-17 09:56:00", df);
//如果格式是yyyy-MM-dd,则使用LocalDate,使用LocalDateTime会报错:
//java.time.format.DateTimeParseException: Text '2022-03-17' could not be parsed: Unable to //obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2022-03-17 of type //java.time.format.Parsed
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate time = LocalDate.parse("2022-03-17", df);
注意:传入时间格式必须与格式化(df)格式一致,否则报错!
String时间类型转特定String时间类型
DateTimeFormatter dfs = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
LocalDateTime localDateTime = LocalDateTime.parse("2023-12-21T12:00:00.159+00:00",dfs);
System.out.println(localDateTime);
DateTimeFormatter dfa = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String format = localDateTime.format(dfa);
System.out.println(format);
//2023-12-21T12:00:00.159+00:00-->2023-12-21