The Answer by Colin Pickard is correct.
I'll add two issues:
java.time.Duration
does not offer getter methods (not yet).
- There is also another way to input and output such values.
Getter Methods
The current implementation of java.time as of Java 8 Update 74 has no getter methods to interrogate a Duration
object for each part, the hours, the minutes, and the seconds.
A java.time.Duration
is structured as two parts internally, a total number of seconds plus an adjustment of a number of nanoseconds (a fractional second):
- To get the fractional second as a count of nanoseconds:
getNano
- To translate the Duration as a count of whole seconds:
getSeconds
From there you can do the math yourself (see below).
Java 9 brings such getter methods, according to this OpenJDK page, Add java.time.Duration methods for days, hours, minutes, seconds, etc.. For more info, see this Question, Why can't I get a duration in minutes or hours in java.time?.
You can look at the source code to help you do the math as mentioned above.
Seems to be something like this:
[Beware! I've not run this, just my own pseudo-code. Please edit to fix and improve.]
- Days part:
( getSeconds() / 86400 )
( 86400 seconds in generic 24-hour day)
- Hours part:
( int ) ( toHours() % 24 )
- Minutes part:
( int ) ( toMinutes() % 60 )
( 60 minutes per hour )
- Seconds part:
( int ) ( getSeconds() % 60 )
( 60 seconds per minute )
- Milliseconds part:
( int ) ( getNano() / 1_000_000 )
ISO 8601
The ISO 8601 standard defines sensible unambiguous text formats for representing various kinds of date-time values.
They have a format for durations in this structure: PnYnMnDTnHnMnS
where the P
marks the beginning (‘p’ for Period, a synonym) and the T
in the middle separates year-month-day portion from the hours-minutes-seconds. Split seconds are represented as a decimal fraction, with digits following after the decimal point (a period or a comma).
For example, P3Y6M4DT12H30M5S
represents a duration of three years, six months, four days, twelve hours, thirty minutes, and five seconds
.
Your 20min30secs
example would be PT20M30S
.
Input-Output
Both the java.time and Joda-Time frameworks use ISO 8601 by default when parsing/generating String representations of their date-time values.
String input = "PT20M30S";
Duration duration = java.time.Duration.parse ( input );
Dump to console.
System.out.println ( "input: " + input + " | duration: " + duration.toString() );
input: PT20M30S | duration: PT20M30S