java - 将字符串转换为特定格式的日期时间对象(例如不带日期)

标签 java datetime time localdate

我需要将我的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/

相关文章:

c++ - 如何使用 boost::date_time 获取两个日期之间的天数

SQL - 将时间序列事件转换为开/关对(处理可能丢失的开或关)

Android:多个与 AsyncTask

java - 如何在java程序中从网站获取HTML代码?

datetime - 如何使用 Snowflake SQL 解析 ISO 8601 时间戳?

java - 在 mongo 集合上使用时,Spring 数据版本注释不会递增

MYSQL时间和日期问题

C - 我可以将格式化时间输出到文本文件吗

java - 如何获取点击复选框所在行的ListView位置和对应的SimpleAdapter数据?

java - 不断收到 java.lang.nullException : null 的错误