Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13080

Parse time from string that contains weekname and time

I'm trying to parse only time ignoring weekday from the string with the following format: "Monday 5AM"

Here is my code:

String dateTxt = "Monday 5AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ha");
LocalTime lt = LocalTime.parse(dateTxt, formatter);

It throws an exception: java.time.format.DateTimeParseException: Text 'Saturday 1AM' could not be parsed

How to parse only time from that string?

Upvotes: 3

Views: 310

Answers (3)

the Hutt
the Hutt

Reputation: 18398

If we want to ignore the day then we can use following patterns:
[ optional section start
] optional section end

This has different behavior while parsing and formatting. Note: the same pattern has been used for parsing and formatting in following code.

    String dateTxt = "Monday 5AM";
    //for parsing day of week is ignored
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[EEEE ]ha", Locale.ENGLISH);
    LocalTime lt = LocalTime.parse(dateTxt, formatter);
    System.out.println(lt + " - parsed local time ");
    
    //in case of formatting if data is not available 
    //then the field won't be in output
    System.out.println(lt.format(formatter) + " -local time with optnal day in format.");
    
    //the day is available so it will be there in output
    LocalDateTime ldt = LocalDateTime.now();
    System.out.println(ldt.format(formatter) + " -local date time with optnal day in format");

Output:

05:00 - parsed local time 
5AM -local time with optnal day in format.
Saturday 2PM -local date time with optnal day in format

For formatting if the data is not available then that won't be in output.

Upvotes: 5

Abra
Abra

Reputation: 20914

If you are only interested in the time, why not just extract that part from dateTxt and parse that part only.

String dateTxt = "Monday 5AM";
DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
DateTimeFormatter fmtr = dtfb.appendValue(ChronoField.CLOCK_HOUR_OF_AMPM)
                             .appendText(ChronoField.AMPM_OF_DAY, TextStyle.SHORT)
                             .toFormatter(Locale.ENGLISH);
String timeTxt = dateTxt.split(" ")[1];
System.out.println(LocalTime.parse(timeTxt, fmtr));

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51882

You need to change the format to

"EEEE ha"

I would also recommend to set the Locale so you have the right language and that it supports AM/PM

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE ha", Locale.ENGLISH);

I see the question has been edited now, if you only want the time you can extract or format that from the parse LocalTime object

LocalTime lt = LocalTime.parse(dateTxt, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("h a", Locale.ENGLISH);
System.out.println(lt);
System.out.println(lt.format(formatter2));

05:00
5 AM

Upvotes: 9

Related Questions