Do you have control over that string generation? If so use standard format instead.
ISO 8601
The ISO 8601 standard defines many textual formats for representing date-time values. This includes a format for durations such as yours: PnYnMnDTnHnMnS
where the P
marks the beginning and the T
separates the years-month-days from the hours-minutes-seconds.
For example, an hour and a half is PT1H30M
.
Using java.time
The java.time classes built into Java 8 and later, and back-ported to Java 6 & 7 & Android, use the ISO 8601 formats by default for both parsing and generating strings.
The java.time classes represent years-months-days as a Period
object, and hours-minutes-seconds as a Duration
object.
String input = "P1DT1H55M15.584S";
Duration d = Duration.parse ( input );
d.toString(): PT25H55M15.584S
d.toMillis(): 93315584
d.toNanos(): 93315584000000
String manipulation
If you cannot control the format of your input string, I would consider manipulating those inputs into standard format. Add the P
, insert the T
, and change the ms
portion into a decimal fraction.
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.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android