我需要将我的String
转换为没有日期的时间。我使用了 SimpleDateFormat 并且它有效。但我需要的是java中的Localdatetime。
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()
,因为日期中的字符串不包含日期部分。
关于java - 将字符串转换为特定格式的日期时间对象(例如不带日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61115208/