tl;dr
Duration.parse(
"PT" +
"10:45".replace( ":" , "M" )
.replace( "-" , "M" )
.replace( "." , "M" )
.replace( "," , "M" )
+ "S"
).toMinutes()
"10:45" → PT10M45S → 10
ISO 8601 format
The ISO 8601 standard defines a format for such spans of time not attached to the time line: PnYnMnDTnHnMnS
The P
marks the beginning. The T
separates any years-months-days from the hours-minutes-seconds. So an hour and a half is PT1H30M
. Your example of ten minutes and forty-five seconds is PT10M45S
.
Perform simple string manipulations to convert your input to this format.
String input = "10:45" ;
String inputStandardized = "PT" +
input.replace( ":" , "M" )
.replace( "-" , "M" )
.replace( "." , "M" )
.replace( "," , "M" )
+ "S" ;
PT10M45S
Duration
Parse as a Duration
. The java.time classes use ISO 8601 formats by default when parsing and generating strings. So no need to specify a formatting pattern.
Duration duration = Duration.parse( inputStandardized );
duration.toString(): PT10M45S
You can use the Duration
object to do date-time math, passing to plus
and minus
. So you may not need the number of minutes as an integer number. But you can ask for total number of minutes in the duration.
long minutes = duration.toMinutes();
10
See this code run live at IdeOne.com.
Tip: Using a clock-time format for a span of time is asking for trouble. The ambiguity leads to confusion and errors. I suggest using the standard ISO 8601 formats for durations as they are designed to be unambiguous, easy to read, and easy to parse.