How to convert a given time (String) to a LocalTime?
Asked Answered
W

4

10

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?

Williamwilliams answered 9/8, 2017 at 15:41 Comment(2)
That's not a LocalDateTime, that's only a LocalTime.Sisyphean
I apologize. Let me rephrase that.Williamwilliams
R
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.

Ratafia answered 9/8, 2017 at 16:18 Comment(1)
Obrigado Hugo. Wish I was as smart as you. Have a great dayWilliamwilliams
F
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);
Foundry answered 9/8, 2017 at 16:0 Comment(1)
This will only works for time exactly respecting the format hh:mma like 12:30AM but not for 5AM or 2:12PM...Marguritemargy
W
2

The solution provided in the accepted answer works only if you execute it on a machine with ENGLISH as the default Locale; it will fail otherwise.

Never use SimpleDateFormat or DateTimeFormatter without a Locale because they are Locale-sensitive. Use the following one to avoid failure due to the default Locale not matching the input.

DateTimeFormatter.ofPattern("h[:mm]a", Locale.ENGLISH);

Demo:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("h[:mm]a", Locale.ENGLISH);
        Stream.of(
                "10AM",
                "12:30PM",
                "2:47PM",
                "1:09AM",
                "5PM"
        )
        .map(s -> LocalTime.parse(s, parser))
        .forEach(System.out::println);

        // See how it can fail with other locales
        // Assuming the default Locale of the system is Locale.CHINA,
        // DateTimeFormatter.ofPattern("h[:mm]a") will automatically be turned into
        // DateTimeFormatter.ofPattern("h[:mm]a", Locale.CHINA) causig the parsing to
        // fail
        DateTimeFormatter errorProneParser = DateTimeFormatter.ofPattern("h[:mm]a", Locale.CHINA);
        LocalTime localTime = LocalTime.parse("10AM", errorProneParser);
    }
}

Output:

10:00
12:30
14:47
01:09
17:00
Exception in thread "main" java.time.format.DateTimeParseException: Text '10AM' could not be parsed at index 2
        at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
        at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
        at java.base/java.time.LocalTime.parse(LocalTime.java:465)
        at Main.main(Main.java:24)
Whosoever answered 16/10, 2022 at 16:34 Comment(1)
Excellent answer for non-English localePanel
W
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

Woolley answered 9/8, 2017 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.