53

したがって、このコードは、指定された ZonedDateTime を文字列に変換し、同じ組み込みの DateTimeFormatter インスタンス (ISO_INSTANT) を使用して戻すだけなので、新しい Java 8 日付/時刻パッケージの下で機能することが期待されます。

ZonedDateTime now = ZonedDateTime.now();
System.out.println(ZonedDateTime.parse(
    now.format(DateTimeFormatter.ISO_INSTANT),
    DateTimeFormatter.ISO_INSTANT));

しかし、明らかにそうではありません:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2014-09-01T19:37:48.549Z' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=549, NanoOfSecond=549000000, MicroOfSecond=549000, InstantSeconds=1409600268},ISO of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)

このエントリは既に見ましたが、ローカル オブジェクトではなく ZonedDateTime オブジェクトが必要であり、8u20 が既にインストールされているため、役に立ちませんでした: Java 8 で DateTimeFormatter と ZonedDateTime を使用して TemporalAccessor から ZonedDateTime を取得できません

ここで何が起こっているか知っている人はいますか?

4

4 に答える 4

3

よくわかりませんが、これは Java 8 のバグである可能性があります。このように動作することを意図していたのかもしれませんが、提案する回避策はデフォルトの動作であるべきだと思います (ZoneId が指定されていない場合)。システムのデフォルトを使用します):

ZonedDateTime now = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT
    .withZone(ZoneId.systemDefault());
System.out
    .println(ZonedDateTime.parse(now.format(formatter), formatter));

OpenJDK で修正された同様のバグがあります: JDK-8033662 - ただし、似ているだけで、まったく同じではありません。

于 2014-09-01T21:21:28.287 に答える