import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class DateTimeParsingExample {
public static void main(String[] args) {
String[] dateTimeStrings = {
"2023-11-30",
"2023-11-30T00:00",
"2023-11-30T09:00",
"2023-11-30T15:13",
"2023-11-30T15:13:11"
};
for (String dateTimeString : dateTimeStrings) {
try {
LocalDateTime parsedDateTime = tryParseDateTime(dateTimeString);
System.out.println("正确: " + parsedDateTime);
} catch (DateTimeParseException e) {
System.out.println("错误: " + dateTimeString);
}
}
}
private static LocalDateTime tryParseDateTime(String dateTimeString) {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm[:ss]]");
try {
// 尝试解析带有时间的格式
return LocalDateTime.parse(dateTimeString, timeFormatter);
} catch (DateTimeParseException e) {
// 解析失败,尝试解析不带时间的格式
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDateTime.of(LocalDate.parse(dateTimeString, dateFormatter), LocalTime.MIDNIGHT);
}
}
}
标签:11,java,LocalDateTime,例子,dateTimeString,2023,字符串,import From: https://www.cnblogs.com/xxsdnol/p/17867588.html