9

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?

SVCS1994
  • 203
  • 3
  • 13

3 Answers3

10

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.

2

If you want to parse time only, you should try parsing to LocalTime. Following is the code to implement this:

DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("hh[:mm]a").toFormatter();
LocalTime localTime = LocalTime.parse(timeValue, parseFormat);
Chinmay jain
  • 961
  • 9
  • 20
  • 3
    This will only works for time exactly respecting the format hh:mma like 12:30AM but not for 5AM or 2:12PM... – jeanr Aug 09 '17 at 16:09
0

Hope this will help you. I think you could do it using DateTimeFormatter and LocalDateTime parsing like below example.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a");

    String date = "Tuesday, Aug 13, 2017 12:10:56 PM";
    LocalDateTime localDateTime = LocalDateTime.parse(date,  formatter);
    System.out.println(localDateTime);
    System.out.println(formatter.format(localDateTime));

Output

2017-08-13T12:10:56

Tuesday, Aug 13, 2017 12:10:56 PM

Similar posts would be Java 8 - Trying to convert String to LocalDateTime