Java 不支持的字段:格式化即时到日期 ISO 时的年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40211892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:31:21  来源:igfitidea点击:

Unsupported field: Year when formatting an instant to Date ISO

java

提问by Eric Reboisson

I am trying to format an Instant to a ldap date ISO8601 but it fails at f.format(Instant.now()); :

我正在尝试将 Instant 格式化为 ldap 日期 ISO8601,但它在 f.format(Instant.now()); 处失败;:

String input = "20161012235959.0Z";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuuMMddHHmmss[,S][.S]X" );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
Instant instant = odt.toInstant ();

f.format(Instant.now());

And the error is :

错误是:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year

    at java.time.Instant.getLong(Instant.java:603)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540)
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
...
...

采纳答案by andolsi zied

To format an Instant a time-zone is required.

要格式化 Instant 需要时区。

 String input = "20161012235959.0Z";
 DateTimeFormatter f = DateTimeFormatter
       .ofPattern ( "uuuuMMddHHmmss.SX" ) 
       .withLocale( Locale.FRANCE )
       .withZone( ZoneId.of("UTC"));
 OffsetDateTime odt = OffsetDateTime.parse ( input , f );
 Instant instant = odt.toInstant ();

 System.out.println(input);
 System.out.print(f.format(instant));