tl;dr
ChronoUnit.MILLISECONDS.between( // This enum object offers a method for calculated elapsed time in a particular granularity.
myJavaUtilDateStart.toInstant() , // Convert from legacy class (`java.util.Date`) to modern class (`java.time.Instant`).
myJavaUtilDateStop.toInstant()
) // Returns a long integer.
java.time
The modern approach uses the java.time classes.
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). This class replaces java.util.Date
and java.sql.Timestamp
.
Instant instant = Instant.now() ; // Capture current moment in UTC in up to nanosecond resolution.
ChronoUnit.MILLISECONDS
To calculate elapsed time as a count of milliseconds specifically, use ChronoUnit.MILLISECONDS
enum object. Beware of data loss, as any microseconds or nanoseconds in the Instant
objects will be ignored.
long millisElapsed = ChronoUnit.MILLISECONDS.between( startInstant , stopInstant ) ;
Duration
Java offers a couple classes for represent a span of time unattached to the timeline:
Period
for years-months-days.
Duration
for hours-minutes-seconds-fractionalSecond.
Example:
Duration d = Duration.between( startInstant , stopInstant ) ;
Generate a String in standard ISO 8601 format by calling Duration::toString
.
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?
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.