Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.2k points)

I'm trying to format an Instant to a String using the new java 8 time-api and a pattern:

Instant instant = ...;

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

Using the code above I get an Exception which complains an unsupported field:

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

    at java.time.Instant.getLong(Instant.java:608)

    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)

    ...

1 Answer

0 votes
by (46k points)

Try:

public static void main(String[] args) {

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

            .withZone(ZoneId.systemDefault());

    System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));

}

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...