Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsupported field: Year when formatting an instant to Date ISO [duplicate]

Tags:

java

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)
...
...
like image 485
Eric Reboisson Avatar asked Oct 24 '16 06:10

Eric Reboisson


People also ask

How do you format an instant date?

Instant instant = ...; String out = DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm:ss").

How to format LocalDate in Java 8?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance.

Is Date time formatter thread safe?

A formatter created from a pattern can be used as many times as necessary, it is immutable and is thread-safe.


1 Answers

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));
like image 160
andolsi zied Avatar answered Oct 12 '22 03:10

andolsi zied