How to analyze wartime (including truncated partial) in Time?

Official airline departures and arrival times are often given in hours and minutes. Below are typical examples:

1830  - 6:30 pm
 730  - 7:30 am
  30  - 30 minutes after midnight (ie 12:30 am)

      

The first two can be parsed using DateTimeFormatter with HHmm and Hmm. The third result results in a parsing error and trying to parse it in just a few minutes (mm) results in another error: Unable to get LocalTime from TemporalAccessor: {MinuteOfHour = 30}

Limitations:

  • I would like to provide a general solution to handle this with formatters if possible, since I don't want to break parsing for all the other timing options that work.

  • Obviously I could preprocess the incoming data to add missing zeros, but I have a lot of GB of data and would like to avoid an extra pass.

Thank you for your help.

Update. The obvious solution is to add zeros in one pass. For example, using Guava:

stringValue = Strings.padStart(stringValue, 4, '0');
LocalTime.parse(stringValue, TypeUtils.timeFormatter);

      

Still wondering if there is a way to do this with just standard formatting codes like hh and mm.

+3


source to share


1 answer


Well, you can create a default value using DateTimeFormatterBuilder

:



    String timeStr = "30";
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                .append(DateTimeFormatter.ofPattern("mm"))
                                .parseDefaulting(ChronoField.HOUR_OF_DAY,0)
                                .toFormatter();
    LocalTime parsedTime = LocalTime.parse(timeStr, formatter);

      

+5


source







All Articles