tl;dr
Duration.ofMillis( … )
.toString()
…or…
Duration.between( // `Duration` represents a span of time unattached to the timeline, in a scale of days-hours-minutes-seconds-nanos.
instantEarlier , // Capture the current moment to start.
Instant.now() // Capture the current moment now, in UTC.
) // Returns a `Duration` object.
.toString() // Generate a string in standard ISO 8601 format.
PT1M23.407S
ISO 8601
what is the shortest, simplest, no nonsense way to write a time format derived from milliseconds
The ISO 8601 standard defines textual formats for date-time values. These formats are indeed short, simple, and no-nonsense. They are largely human-readable across various cultures, practical, and unambiguous.
For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS
. The P
marks the beginning, and the T
separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M
.
java.time.Duration
The java.time classes include a pair of classes to represent spans of time. The Duration
class is for hours-minutes-seconds, and Period
.
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).
Instant earlier = Instant.now() ; // Capture the current moment in UTC.
…
Instant later = Instant.now() ;
Duration d = Duration.between( earlier , later ) ;
String output = d.toString() ;
PT3.52S
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.
System.currentTimeMillis() - time;
. – Teodorateodorico