Fairy
Fairy

Reputation: 531

LocalTime parsing with AM/PM

I have a time string coming from another source in format "hh:mma", for example, 10:00a or 07:30p. I need to create an instance of LocalTime from that string. I've tried to parse it by calling the method: LocalTime.parse("10:00p", DateTimeFormatter.ofPattern("hh:mma")), but it throws an DateTimeParseException. In accordance with DateTimeFormatter API, part of the time should be in uppercase and consist of 2 letters (PM instead of p). But is there any method to parse time without changing the sourse line?

Upvotes: 2

Views: 6832

Answers (2)

Anonymous
Anonymous

Reputation: 86280

But is there any method to parse time without changing the sourse line?

Yes, this formatter can do that for you:

    Map<Long, String> ampmStrings = Map.of(0L, "a", 1L, "p");
    DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
            .appendPattern("hh:mm")
            .appendText(ChronoField.AMPM_OF_DAY, ampmStrings)
            .toFormatter();

With DateTimeFormatterBuilder.appendText we can define our own texts for both formatting and parsing. I used the Java 9+ Map.of to initialize a map of two key-value pairs. If you are using Java (6, 7 or) 8, I trust you to initialize the map differently. The rest should still work. (For Java 6 and 7 you can use the ThreeTen Backport for the java.time functionality used in this answer; link at the bottom).

Let’s try it out:

    String sourceLine = "10:00a";
    LocalTime time = LocalTime.parse(sourceLine, timeFormatter);
    System.out.println("Parsed time: " + time);

Output is:

Parsed time: 10:00

A yet better option would be if you could persuade your source to provide strings in ISO 8601 format (like 10:00 and 19:30).

Link:

ThreeTen Backport

Upvotes: 3

xingbin
xingbin

Reputation: 28279

Replace p with PM, a with AM, then parse it with pattern hh:mm a.

String time = "10:00p";
time = time.replace("p", "PM").replace("a", "AM"); // 10:00PM
LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm a", Locale.US));
System.out.println(localTime); // 22:00

Upvotes: 3

Related Questions