Reputation: 410
I'm trying to convert a time string to milliseconds using the code below. Because I will use the time as countdown timer.
The problem is that the time is from database and it is on varchar type. I tried this code and it's not giving me the correct output.
String timeDuration = "10:00"; //for example only
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
Date time = sdf.parse(timeDuration);
long millis = time.getTime(); //The output must be 600000
I'm getting the wrong "millis" using this code.
I'm using Android Studio.
Upvotes: 3
Views: 1157
Reputation: 7792
Using classes SimpleDateFormat and Date is VERY STRONGLY discouraged. These classes are deprecated and very problematic. Use package java.time instead. for parser use DateTimeFormatter class. Also, in your case you may use class Duration. Alternatively, you can use Open Source MgntUtils library That has class TimeInterval and method TextUtils.parseStringToTimeInterval(java.lang.String valueStr). In this case your code could be very simple:
long milliseconds = TextUtils.parseStringToTimeInterval("10m").toMillis();
And this will give you 600000 as a result. The library is available as Maven artifact here, and on the github (including source code and Javadoc) here. Here is a link to Javadoc. The article about the library is here (See paragraph "Parsing String to Time Interval")
Disclaimer: The library is written by me
Upvotes: 2
Reputation: 79015
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:
The first example has a duration whereas the second example has a Date-Time (implicitly today).
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
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 5
Reputation: 125
I think you can cut substring first. Then convert the substring to integer. Then multiple with 60000.
Integer.parseInt(timeDuration.substring(0, timeDuration.indexOf(":"))) * 60 * 1000
HTH
Cheers,
Hook
Upvotes: -5