Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot parse time string to LocalDateTime

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading