Reputation: 7604
I apologize if this has already been discussed.
I have a clip duration in a string:
00:10:17
I would like to convert that to value in milliseconds. (Basically 617000 for the above string)
Is there some API that I could use to do this in one or two steps. On basic way would be to split the string and then add the minutes, seconds and hours.
But is there a shorter way to do this?
Thanks.
Upvotes: 6
Views: 14261
Reputation: 86203
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.
Yes indeed, java.time just requires at least Java 1.6.
org.threeten.bp
with subpackages.LocalTime
, a hack that works up to 23 hours 59 minutes and does validate that minutes don’t exceed 59.Duration
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 0
Reputation: 79005
You can use java.time.Duration
which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
Demo:
import java.time.Duration;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String strDuration = "00:10:17";
int[] parts = Arrays.stream(strDuration.split(":"))
.mapToInt(Integer::parseInt)
.toArray();
Duration duration = Duration.ZERO;
long millis = 0;
if (parts.length == 3) {
millis = duration.plusHours(parts[0])
.plusMinutes(parts[1])
.plusSeconds(parts[2])
.toMillis();
}
System.out.println(millis);
}
}
Output:
617000
Note: I've used Stream
API to convert the String[]
to int[]
. You can do it without using Stream
API as follows:
String strDuration = "00:10:17";
String[] strParts = strDuration.split(":");
int[] parts = new int[strParts.length];
for (int i = 0; i < strParts.length; i++) {
parts[i] = Integer.parseInt(strParts[i]);
}
Alternatively, you can parse the parts at the time of adding them to Duration
as follows:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
String strDuration = "00:10:17";
String[] parts = strDuration.split(":");
Duration duration = Duration.ZERO;
long millis = 0;
if (parts.length == 3) {
millis = duration.plusHours(Integer.parseInt(parts[0]))
.plusMinutes(Integer.parseInt(parts[1]))
.plusSeconds(Integer.parseInt(parts[2]))
.toMillis();
}
System.out.println(millis);
}
}
Output:
617000
Learn about the modern date-time API from Trail: Date Time.
Some great tutorials on Java Stream
API:
Upvotes: 1
Reputation: 492
It does not matter if the duration includes hours or minutes or seconds or none.
public static long durationToMillis(String duration) {
String[] parts = duration.split(":");
long result = 0;
for (int i = parts.length - 1, j = 1000; i >= 0; i--, j *= 60) {
try {
result += Integer.parseInt(parts[i]) * j;
} catch (NumberFormatException ignored) {
}
}
return result;
}
Upvotes: 0
Reputation: 338306
java.time.Duration
Use the Duration
class.
Duration.between(
LocalTime.MIN ,
LocalTime.parse( "00:10:17" )
).toMillis()
milliseconds: 617000
See this code live in IdeOne.com.
See this Answer of mine and this Answer of mine to similar Questions for more explanation of Duration
, LocalTime
, and a java.time.
Caution: Beware of possible data-loss when converting from possible values of nanoseconds in java.time objects to your desired milliseconds.
Upvotes: 12
Reputation: 3389
Create an appropriate instance of DateFormat
. Use the parse()
method to get a Date
. Use getTime()
on the Date
object to get milliseconds.
You can check here .
I just tested it as:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:10:17";
Date date = sdf .parse(inputString);// .parse("1970-01-01" + inputString);
System.out.println("in milliseconds: " + date.getTime());
}
}
Upvotes: 0
Reputation: 33495
Here is one own written possible approach(assumption of same source format always)
String source = "00:10:17";
String[] tokens = source.split(":");
int secondsToMs = Integer.parseInt(tokens[2]) * 1000;
int minutesToMs = Integer.parseInt(tokens[1]) * 60000;
int hoursToMs = Integer.parseInt(tokens[0]) * 3600000;
long total = secondsToMs + minutesToMs + hoursToMs;
Upvotes: 10
Reputation: 328598
You could simply parse it manually:
String s = "00:10:17";
String[] data = s.split(":");
int hours = Integer.parseInt(data[0]);
int minutes = Integer.parseInt(data[1]);
int seconds = Integer.parseInt(data[2]);
int time = seconds + 60 * minutes + 3600 * hours;
System.out.println("time in millis = " + TimeUnit.MILLISECONDS.convert(time, TimeUnit.SECONDS));
Upvotes: 9