Java. ISO-8601 time

Date and Time in Java is always a pain.

Here’s how to parse time and date strings in the ISO-8601 format.

ISO-8601 time example: “2018-07-06T17:58:39.451Z”

The trick is that you need to parse that ISO-8601 string into java.time.Instant

String dateTimeString = "2018-07-06T17:58:39.451Z";
Instant instant = Instant.parse(dateTimeString);

You can compare two instants


or get Epoch milliseconds/seconds

long millis = instant.toEpochMilli();
long seconds = instant.getEpochSecond();
assertEquals(millis / 1000, seconds);

or get ISO-8601 time as Date

Date date = Date.from(Instant.parse("2018-07-06T17:58:39.451Z"));