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

SVCS1994 :

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?

user7605325 :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473163&siteId=1