Convert Date from ISO 8601 Zulu string to java.time.Instant in Java 8

surendrapanday picture surendrapanday · Aug 18, 2018 · Viewed 10.4k times · Source

I want to convert string date format into java.time.Instant

I am getting exception while parsing date.

 java.lang.IllegalArgumentException: Too many pattern letters: s

I am using below code for conversion first from String to date.

    String string = "2018-07-17T09:59:51.312Z";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-DD'T'hh:mm:ss.sssZ", Locale.FRANCE);
    LocalDate date = LocalDate.parse(string, formatter);
    System.out.println(date);

I want to convert "timestamp": "2018-07-17T09:59:51.312Z" in format time in the ISO 8601 format YYYY-MM-DDThh:mm:ss.sssZ in the UTC timezone.

Checked Java string to date conversion, but not working.

Answer

Basil Bourque picture Basil Bourque · Aug 18, 2018

tl;dr

convert string date format into java.time.Instant

Skip the formatting pattern. Just parse.

Instant.parse( "2018-07-17T09:59:51.312Z" )

ISO 8601

Yes, you used incorrect formatting pattern as indicated in the first Answer.

But you needn't specify a formatting pattern at all. Your input string is in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings.

The Z on the end means UTC, and is pronounced “Zulu”.

Instant instant = Instant.parse( "2018-07-17T09:59:51.312Z" ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.