问题
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.
回答1:
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;
回答2:
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));
回答3:
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.
回答4:
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.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Some great tutorials on Java Stream
API:
- Processing Data with Java SE 8 Streams, Part 1
- Part 2: Processing Data with Java SE 8 Streams
- Lesson: Aggregate Operations
- Reduction
回答5:
Check out the Joda Time Duration class.
回答6:
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());
}
}
回答7:
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;
}
回答8:
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
- Duplicate question: Java convert time string to milliseconds [duplicate]
- Oracle tutorial: Date Time explaining how to use java.time.
- Other answers using java.time
- Answer by Basil Bourque converting via
LocalTime
, a hack that works up to 23 hours 59 minutes and does validate that minutes don’t exceed 59. - Answer by Live and Let Live parsing each integer and assembling into a
Duration
.
- Answer by Basil Bourque converting via
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - Java 8+ APIs available through desugaring
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Wikipedia article: ISO 8601
来源:https://stackoverflow.com/questions/15410512/converting-duration-string-into-milliseconds-in-java