Home  >  Article  >  Java  >  Can Java.time Parse Fractions of a Second Accurately?

Can Java.time Parse Fractions of a Second Accurately?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 16:08:02124browse

 Can Java.time Parse Fractions of a Second Accurately?

Can java.time Handle Fraction-of-Second Parsing?

Issue Outline:

In Java 8, attempts to parse fraction-of-second using the java.time package initially yielded success but later encountered exceptions. This failure persisted even when incorporating "SS" in the formatting pattern for milliseconds. Despite documentation indicating the need for the same number of format characters as input digits, strict mode enforcement misinterpreted the lack of fraction characters.

Solution:

This issue has been resolved in Java 9. Until then, a workaround involving adjacent value parsing is available:

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

However, this approach does not handle the specific instance of two fraction digits in SS.

Technical Background:

The pattern symbol "S" represents any fraction of a second, including nanoseconds. Adjacent value parsing enables the parser to delineate fields separated by literals or time part separators.

Alternative Solutions:

Due to JSR-310's limitations in managing adjacent value parsing, alternative solutions exist:

  • SimpleDateFormat (with caveats):
<code class="java">SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date d = sdf.parse(input);</code>
  • Third-party libraries (e.g., Joda-Time, Time4J):
<code class="java">// Joda-Time
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddHHmmssSS");</code>
<code class="java">// Time4J
ChronoFormatter<PlainTimestamp> f = ChronoFormatter.ofTimestampPattern("yyyyMMddHHmmssSS", PatternType.CLDR, Locale.ROOT);</code>
  • DIY hack:
<code class="java">String input = "2011120312345655";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
int len = input.length();
LocalDateTime ldt = LocalDateTime.parse(input.substring(0, len - 2), dtf);
int millis = Integer.parseInt(input.substring(len - 2)) * 10;
ldt = ldt.plus(millis, ChronoUnit.MILLIS);</code>

The above is the detailed content of Can Java.time Parse Fractions of a Second Accurately?. 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