Duration is not the same as Date-Time
Duration is not the same as Date-Time and therefore you should not parse your string into a Date-Time type. The Date-Time type (e.g. java.util.Date
) represents a point in time whereas a duration represents a length of time. You can understand it from the following examples:
- I have been reading this book for 10 minutes.
- I have been reading this book since 4:00 pm.
The first example has a duration whereas the second example has a Date-Time (implicitly today).
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
You can convert your string into ISO 8601 format for a Duration and then parse the resulting string into Duration
which you can be converted into milliseconds.
Demo:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
System.out.println(durationToMillis("10:00"));
}
static long durationToMillis(String strDuration) {
String[] arr = strDuration.split(":");
Duration duration = Duration.ZERO;
if (arr.length == 2) {
strDuration = "PT" + arr[0] + "M" + arr[1] + "S";
duration = Duration.parse(strDuration);
}
return duration.toMillis();
}
}
Output:
600000
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.