Skip to main content

Instant.now() in Java 8 is different from Instant.now() in Java 11

· One min read

Java 9 had some improvement in java.time.Clock.systemUTC().instant() (JDK-8068730).

Long story short, Clock.systemUTC().instant() creates an Instant object using nanoseconds instead of milliseconds.

This causes some change in Instant.now() in Java 9 or higher.

In Java 8,

import java.time.Instant

val now1 = Instant.now(); val now2 = Instant.ofEpochMilli(System.currentTimeMillis())
// 2020-07-27T11:07:18.933Z
// 2020-07-27T11:07:18.933Z

now1.getNano()
// 933000000
now2.getNano()
// 933000000

now1.getNano() == now2.getNano()
// true

In Java 11 (9 or higher),

import java.time.Instant

val now1 = Instant.now(); val now2 = Instant.ofEpochMilli(System.currentTimeMillis());
// 2020-07-27T11:11:30.529216Z
// 2020-07-27T11:11:30.529Z

now1.getNano()
// 529216000
now2.getNano()
// 529000000

now1.getNano() == now2.getNano()
// false

So if your code relies on Instant.toString(), it may not work the same as before upgrading Java from 8 to 9 or higher.

By the way, relying on Instant.toString() is bad so if you have code like that, now is the time to fix it.