Home  >  Article  >  Java  >  Can `java.time` Parse Fraction-of-Second Values in Date Strings?

Can `java.time` Parse Fraction-of-Second Values in Date Strings?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 22:26:02406browse

 Can `java.time` Parse Fraction-of-Second Values in Date Strings?

Is java.time failing to parse fraction-of-second?

Java 8's java.time package struggles to parse input strings with a fraction-of-second component when using the DateTimeFormatter class. Attempts to parse a string like "2011120312345655" using the format pattern "yyyyMMddHHmmssSS" result in a DateTimeParseException, despite documentation indicating that "SS" should represent fraction-of-second values.

Workaround Prior to Java 9

Prior to Java 9, a workaround was proposed:

<code class="java">DateTimeFormatter dtf = 
  new DateTimeFormatterBuilder()
  .appendPattern("yyyyMMddHHmmss")
  .appendValue(ChronoField.MILLI_OF_SECOND, 3)
  .toFormatter();</code>

However, this workaround does not fully address the issue, as it cannot handle the use case of only two pattern symbols, "SS". Alternative solutions using other fields or external libraries were also suggested.

Resolution in Java 9

The JDK-issue associated with this problem has been marked as resolved for Java 9. This indicates that the java.time package's ability to parse fraction-of-second values has been improved in this version.

The above is the detailed content of Can `java.time` Parse Fraction-of-Second Values in Date Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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