Hammad Tariq Hammad Tariq - 6 months ago 27
Java Question

Android: Converting minutes and seconds to millisecond

I am trying to convert time which I have in static string such as "07:02" into milliseconds. I am looking at documentation TimeUnit and trying to get my string to convert in milliseconds but first I have a string, so the converter function is not accepting string I guess and secondly I have both, minutes and seconds, so should I convert them one by one and then add them? Don't seem to be a nice approach?

TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)

Answer

I have just checked the documentation for TimeUnit. You could do something like this:

String time = "07:02";

long min = Integer.parseInt(time.substring(0, 2));
long sec = Integer.parseInt(time.substring(3));

long t = (min * 60L) + sec;

long result = TimeUnit.SECONDS.toMillis(t);
Comments