A duplicate question (link at the bottom) asked about a string without seconds, just HH:MM
, for example 25:25
, using Java 7. I still recommend the Duration
class of java.time, the modern Java date and time API. java.time has been backported to Java 6 and 7. With it there are a number of ways to go. It’s simple to adapt one of the good answers by Basil Bourque and Live and Let Live to a string without seconds. I am showing yet an approach.
String durationString = "25:25"; // HH:MM, so 25 hours 25 minutes
String isoDurationString
= durationString.replaceFirst("^(\\d+):(\\d{2})$", "PT$1H$2M");
long durationMilliseconds = Duration.parse(isoDurationString).toMillis();
System.out.format(Locale.US, "%,d milliseconds%n", durationMilliseconds);
Output when running on Java 1.7.0_67:
91,500,000 milliseconds
Duration.parse()
accepts only ISO 8601 format, for example PT25T25M
. Think a period of time of 25 hours 25 minutes. So I am using a regular expression for converting the string you had into the required format.
One limitation of this approach (a limitation shared with some of the other approaches) is that it gives poor validation. We would like reject minutes greater than 59, but Duration.parse()
accepts them.
Question: Did you claim that it works on Java 1.7?
Yes indeed, java.time just requires at least Java 1.6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links