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:
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With