Reputation: 322
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
Upvotes: 0
Views: 690
Reputation: 1158
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);
Upvotes: 2
Reputation: 11153
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.
Upvotes: 3