Home > Java > javaTutorial > body text

Can Java.time Parse Fractions of Seconds Before Java 9?

Susan Sarandon
Release: 2024-11-01 16:11:02
Original
422 people have browsed it

 Can Java.time Parse Fractions of Seconds Before Java 9?

Is java.time Unable to Parse Fractions of Seconds?

Introduction

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.

The Problem

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.

The Solution

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();
Copy after login

The Issue and Its Implications

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.

Alternatives and Updates

While the workaround above addresses the issue, it may not be ideal for all use cases. Other alternatives include:

  • Using SimpleDateFormat, but be aware that it may interpret the fraction incorrectly.
  • Waiting until Java 9 (or later) for the official fix.
  • Using a third-party library like Joda-Time or Time4J.

Update: Java 9 Fix

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!