With the initial release of Java 8, the java.time package appeared to have an issue parsing fractions of seconds. This problem arose when adding "SS" to the DateTimeFormatter pattern to represent fractions of seconds and encountering an exception.
When attempting to parse a fraction of a second, as specified by the "SS" pattern, an exception was thrown. This was surprising as the documentation indicated that this should have worked.
This issue was later reported and fixed in Java 9. However, until Java 9 is released, a workaround is necessary. As mentioned in the JDK bug report, the following workaround can be used:
DateTimeFormatter dtf = new DateTimeFormatterBuilder() .appendPattern("yyyyMMddHHmmss") .appendValue(ChronoField.MILLI_OF_SECOND, 3) .toFormatter();
The crux of the issue lies in how the fraction of seconds is parsed when characters are adjacent. Adjacent value parsing is only supported by appendValue(...) methods, which assume numerical representations. The appendFraction(...) method, used internally by the fractional part, does not handle adjacent value parsing. This limitation prevents the correct interpretation of fractions of seconds when the pattern contains adjacent digits.
While the workaround above addresses the issue, it may not be ideal for all use cases. Other alternatives include:
In Java 9, the issue has been resolved. The fraction of seconds can now be parsed correctly using the "SS" pattern or, for greater precision, using the ChronoField.MICRO_OF_SECOND or ChronoField.NANO_OF_SECOND fields.
The above is the detailed content of Can Java.time Parse Fractions of Seconds Before Java 9?. For more information, please follow other related articles on the PHP Chinese website!