tl;dr
Instant.now()
java.time
The modern approach uses the java.time classes built into Java 8 and later, and in the latest Android. For earlier Android, see the last bullets below.
Avoid the legacy date-time classes from the earliest versions of Java. They are troublesome, confusing, poorly-designed, and flawed.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
To capture the current moment in UTC, call Instant.now
.
Instant instant = Instant.now() ; // Current moment in UTC.
As of 2018, conventional computer hardware clocks are not capable of capturing the current moment with a resolution as fine as nanoseconds. Commonly, you will get the current moment only in microseconds or more coarse a granularity.
In the OpenJDK & Oracle implementations of Java, Java 8 captures the current moment only in milliseconds. Java 9 in those implementations brought a new implementation of Clock
, now capable of capturing the current moment in a finer resolution. On macOS on a MacBook Pro (Retina, 15-inch, Late 2013) with the Oracle JDK using Java 9.0.1, I am seeing the current moment captured in six digits of decimal fraction, microseconds.
instant.toString(): 2018-01-09T05:26:04.327132Z
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.
Where to obtain the java.time classes?