tl;dr
Duration // Represent a span-of-time unattached to the timeline on a scale of hours-minutes-seconds.
.between( // Calculate time elapsed between two `Instant` objects.
then , // An `Instant` object instantiated earlier.
Instant.now() // Capture the current moment as seen in UTC (an offset of zero hours-minutes-seconds).
) // Returns a `Duration` object.
.toString() // Generate text in standard ISO 8601 format.
LocalDateTime
cannot represent a moment
LocalDateTime
is the wrong class for tracking specific points on the timeline. That class purposely lacks the context of a time zone or offset-from-UTC. So it cannot represent a moment. I cannot imagine a scenario where calling LocalDateTime.now()
is the right thing to do.
For example, if you were to calculate elapsed time during which a Daylight Saving Time (DST) cut-over occurred, your result would be incorrect. The LocalDateTime
class ignores any offset changes in that time zone.
Track elapsed time with java.time.Instant
Instead, use Instant
.
Instant start = Instant.now() ;
…
Instant end = Instant.now() ;
Represent elapsed time with java.time.Duration
Calculate elapsed time using Duration
class.
Duration elapsed = Duration.between( start , end ) ;
Generate text in standard ISO 8601 format: PnYnMnDTnHnMnS
. Example: PT30M
for exactly one half-hour.
String output = elapsed.toString() ;
To generate text in other formats, access the parts by calling to…Part
methods.