Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse military time (including truncated partials) into a Time?

Tags:

java

time

java-8

Official airline departure and arrival times are often provided in hour and minutes. The following 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 results in a parsing error, and attempting to parse it with only minutes (mm) results in a different error: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=30}

Constraints:

  1. I would like to provide a general solution to handle this using formatters if possible, as i don't want to break parsing for all other time variants that work.

  2. Obviously I could pre-process the incoming data to prepend missing zeros, but i have many GB of data and would like to avoid an additional pass.

Thanks for your help.

Update: An obvious solution is to prepend zeros in the same pass. For example, using Guava:

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

Still curious if there a way to do this only with standard formatting codes like hh and mm.

like image 835
L. Blanc Avatar asked Nov 29 '25 23:11

L. Blanc


1 Answers

Well, you can create a default 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);
like image 164
RealSkeptic Avatar answered Dec 01 '25 14:12

RealSkeptic