Java 8: How to create DateTimeFormatter with milli, micro or nano seconds?
DateTimeFormatter
only supports width ranges, so this wouldn't be possible with a single instance. You could make 3 separate formatters using .appendFraction(NANO_OF_SECOND, #, #, true)
where # is 3, 6, or 9. Then try them in sequence, ignoring any DateTimeParseException
until the last one:
private static TemporalAccessor parse(String text) {
try {
return formatter3.parse(text);
} catch (DateTimeParseException e) {
// ignore
}
try {
return formatter6.parse(text);
} catch (DateTimeParseException e) {
// ignore
}
return formatter9.parse(text); // let this one throw
}
Another option would be checking the input with a regular expression first, something like text.matches("[^.]+(.+\\.(\\d{3}|\\d{6}|\\d{9})\\b.*)?")
.
Liubov E.
Updated on June 16, 2022Comments
-
Liubov E. almost 2 years
I need to create the formatter for parsing timestamps with optional milli, micro or nano fractions of second.
For example, for my needs I see the following opportunity:
DateTimeFormatter formatter = new DateTimeFormatterBuilder() .append(DateTimeFormatter.BASIC_ISO_DATE) .appendLiteral('-') .append(DateTimeFormatter.ISO_LOCAL_TIME) .appendOffset("+HH:mm", "Z") .toFormatter();
Or it is also possible to use
appendFraction(field, minWidth, maxWidth, decimalPoint)
.However in these cases will it be possible to parse timestamps with any number of decimals (up to 9 or maxWidth). How to achieve that we can parse (optionally) only 3, 6 or 9 numbers after the comma?
It should be possible to parse the following time parts:
HH:mm:ss.SSS
HH:mm:ss.SSSSSS
HH:mm:ss.SSSSSSSSS
But impossible to parse:
HH:mm:ss.SSSS
.