将字符串转换为特定格式的 DateTime 对象(例如,没有日期)

Convert String to DateTime object in specific format(ex. without Date)

我需要将 String 转换为没有日期的时间。我使用 SimpleDateFormat 并且有效。但我需要的是 Localdatetime in java.

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

但是它给我这个错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text '10:30:20 PM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 22:30:20 of type java.time.format.Parsed

您可以将 Locale 与您的 DateTimeFormatter -

一起使用
String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a",Locale.ENGLISH);
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);

还要注意,您必须在此处使用 LocalTime.parse(),因为日期中的字符串不包含日期部分。

您需要的是 LocalTime 而不是 LocalDateTime。 你也可以试试这个:

LocalTime localTime = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
System.out.println(localTime);

如果您有 24 小时格式的时间:

LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime);