I’m trying to convert this string 01:43:56 to a LocalDateTime but keep getting this error thrown:
Text ’01:43:56′ could not be parsed: Unable to obtain LocalDateTime
from TemporalAccessor: {},ISO resolved to 01:43:56 of type
java.time.format.Parsed
I’ve tried every variation of the time format I can think of:
LocalDateTime.parse("01:43:56", DateTimeFormatter.ofPattern("hh:mm:ss"))
LocalDateTime.parse("01:43:56", DateTimeFormatter.ofPattern("HH:mm:ss"))
LocalDateTime.parse("01:43:56", DateTimeFormatter.ofPattern("H:mm:ss"))
LocalDateTime.parse("01:43:56", DateTimeFormatter.ofPattern("H:m:s"))
LocalDateTime.parse("01:43:56", DateTimeFormatter.ISO_LOCAL_TIME)
>Solution :
The string "01:43:56" only contains time information without any date information, which is why you are getting an error when trying to parse it as a LocalDateTime.
You should use LocalTime.parse() instead of LocalDateTime.parse():
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String timeString = "01:43:56";
LocalTime localTime = LocalTime.parse(timeString, DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime); // Output: 01:43:56
}
}