Search code examples
javadatejava-8date-formattingjava-time

How to print a date using DateTimeFormatter.ISO_LOCAL_DATE?


I want to use DateTimeFormatter.ISO_LOCAL_DATE to print and parse dates. This is what I'm doing for printing:

Date date;
String text = DateTimeFormatter.ISO_LOCAL_DATE.format(
  date.toInstant()
);

This is what I'm getting:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
  at java.time.Instant.getLong(Instant.java:603)
  at java.time.format.DateTimePrintContext$1.getLong(DateTimePrintContext.java:205)
  at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
  at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
  at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
  at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1744)
  at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1718)

Solution

  • This is how it works:

    String text = DateTimeFormatter.ISO_LOCAL_DATE
      .withZone(ZoneId.of("UTC"))
      .format(date.toInstant());