I am presenting two options:
- Time4J, an advanced external date, time and time interval library.
- java.time, the built-in modern Java date and time API.
SimpleDateFormat
and Date
are the wrong classes to use, both because a duration of 1 minute 30.5 seoncds is not a date and because those classes have long gone out of any reasonable use.
Time4J
This is the elegant solution. We first declare a formatter:
private static final Duration.Formatter<ClockUnit> DURATION_FORMAT
= Duration.formatter(ClockUnit.class, "hh:mm:ss.fff");
Then parse and convert to milliseconds like this:
String startAfter = "00:01:30.555";
Duration<ClockUnit> dur = DURATION_FORMAT.parse(startAfter);
long milliseconds = dur.with(ClockUnit.MILLIS.only())
.getPartialAmount(ClockUnit.MILLIS);
System.out.format("%d milliseconds%n", milliseconds);
Output is:
90555 milliseconds
java.time
The java.time.Duration
class can only parse ISO 8601 format. So I am first converting your string to that format. It goes like PT00H01M30.555S
(the leading zeroes are not required, but why should I bother removing them?)
String startAfter = "00:01:30.555";
String iso = startAfter.replaceFirst(
"^(\\d{2}):(\\d{2}):(\\d{2}\\.\\d{3})$", "PT$1H$2M$3S");
Duration dur = Duration.parse(iso);
long milliseconds = dur.toMillis();
System.out.format("%d milliseconds%n", milliseconds);
Output is the same as before:
90555 milliseconds
Another difference from Time4J is that the Java Duration
can be directly converted to milliseconds without being converted to a Duration
of only milliseconds first.
Links
00:01:30.500
to mean a duration, an amount of time, 1 minute 30.5 seconds. If soDate
andSimpleDateFormat
are the wrong classes to use. A duration is not a date. Also I recommend you never use those classes. They are poorly designed and long outdated, the latter in particular notoriously troublesome. Use java.time, the modern Java date and time API. – Omor