TL; DR
Duration.ofMillis(
SystemClock.elapsedRealTime()
)
.toString()
PT7M21S
Avoid the time of day format
Displaying elapsed time in the time of day format (HH: MM: SS.SSS) is misleading and ambiguous, as it can easily be interpreted as the time of day.
ISO 8601 - Duration Format
The ISO 8601 standard defines reasonable string representations of various date and time values. These values include elapsed time.
PnYnMnDTnHnMnS, P, T years-month-days --. :
PT30M=PT8H30M=P3Y6M4DT12H30M5S " , , , , ".
"" "" . . , "", P, "". Cest la vie.
java.time
java.time , :
/ ISO 8601, .
SystemClock.elapsedRealTime() - long, . , , Duration.
long millis = SystemClock.elapsedRealTime() ;
Duration d = Duration.ofMillis( millis ) ;
441000 .
Duration d = Duration.ofMillis( 441_000L ) ;
. 441_000L 21 .
String output = d.toString() ;
PT7M21S
, Duration.
Duration d = Duration.parse( "PT7M21S" ) ;
ISO 8601, . (00:07:21), , . , .
to…Part .
int minutesPart = d.toMinutesPart() ;
int secondsPart = d.toSecondsPart() ;
.
long millis = d.toMillis() ;
java.time
java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.
Joda-Time, , java.time.
, . Oracle. Qaru . JSR 310.
java.time . JDBC , JDBC 4.2 , , java.sql.*.
java.time?
ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .
Joda
UPDATE: Joda-Time , java.time. .
Joda-Time , Interval, Duration Period, , Period, , , .. ISO 8601. Period ISO 8601. Joda-Time Android, java.util.Date/.Calendar.
Period long . , , SystemClock.elapsedRealTime() .
long machineUptimeMillis = SystemClock.elapsedRealtime() ;
Period machineUptimePeriod = new Period( machineUptimeMillis );
String output = machineUptimePeriod.toString();
, - , long .
long start = SystemClock.elapsedRealtime() ;
// … Perform some operation …
long stop = SystemClock.elapsedRealtime() ;
long elapsedMillis = stop - start ;
Period elapsedPeriod = new Period( elapsedMillis );
P / T .
String output = elapsedPeriod.toString().replace( "P" , "" ).replace( "T", " " ).toLowerCase() ;
, 3y6m4d 12h30m5s.
-
Period, "5 2 ".
, , .
PeriodFormatter formatter = PeriodFormat.wordBased( Locale.CANADA_FRENCH ) ;
String output = formatter.print( elapsedPeriod ) ;
PeriodFormatterBuilder.
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSuffix(" year", " years")
.appendSeparator(" and ")
.printZeroRarelyLast()
.appendMonths()
.appendSuffix(" month", " months")
.toFormatter() ;