Unsupported field: Year when formatting an instant to Date ISO

Java

Java Problem Overview


I am trying to format an Instant to a ldap date ISO8601 but it fails at 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)
...
...

Java Solutions


Solution 1 - Java

To format an Instant a time-zone is required.

 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));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric ReboissonView Question on Stackoverflow
Solution 1 - Javaandolsi ziedView Answer on Stackoverflow