英文:
Convert String to DateTime object in specific format(ex. without Date)
问题
String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalTime time = LocalTime.parse(str, formatter);
英文:
I need to convert my String
to time without the date. I used SimpleDateFormat and it worked. But what I need is from Localdatetime in java.
String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
But it is giving me this error:
> 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
答案1
得分: 3
你可以在 DateTimeFormatter
中使用 Locale
-
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()
,因为你的字符串中没有日期部分。
英文:
You could use Locale
with your 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);
And also note you have to use LocalTime.parse()
here, since your string in the date doesn't contain date part.
答案2
得分: 2
你需要的是 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);
英文:
What you need is LocalTime & not LocalDateTime.
You can try this as well:
LocalTime localTime = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
System.out.println(localTime);
If you have time in 24 hr format:
LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论