Search code examples
javajava-timedatetime-parsing

How to convert a given time (String) to a LocalTime?


I will be asking a user to enter a specific time: 10AM, 12:30PM, 2:47PM, 1:09AM, 5PM, etc. I will be using a Scanner to get the user's input.

How can I parse/convert that String to a LocalTime object? Is there any built-in function in Java that will allow me to do that?


Solution

  • Just use a java.time.format.DateTimeFormatter:

    DateTimeFormatter parser = DateTimeFormatter.ofPattern("h[:mm]a");
    LocalTime localTime = LocalTime.parse("10AM", parser);
    

    Explaining the pattern:

    • h: am/pm hour of day (from 1 to 12), with 1 or 2 digits
    • []: delimiters for optional section (everything inside it is optional)
    • :mm: a : character followed by minutes with 2 digits
    • a: designator for AM/PM

    This works for all your inputs.