golkarm
golkarm

Reputation: 1014

Converting string time to milliseconds

I have some string time that must use in seekTo() methode of MediaPlayer class but these are as this format 0:01.432.

Now how can i convert it to milliseconds?

Upvotes: 2

Views: 2958

Answers (3)

golkarm
golkarm

Reputation: 1014

I created these two methods for converting text to int

private static int convert(String time) {
    int quoteInd = time.indexOf(":");
    int pointInd = time.indexOf(".");

    int min = Integer.valueOf(time.substring(0, quoteInd));
    int sec = Integer.valueOf(time.substring(++quoteInd, pointInd));
    int mil = Integer.valueOf(time.substring(++pointInd, time.length()));

    return (((min * 60) + sec) * 1000) + mil;
}

and int to text

private static String convert(final int duration) {
    int dur, min, sec, mil;

    dur = duration;
    min = dur / 60000;
    dur -= min * 60000;
    sec = dur / 1000;
    dur -= sec * 1000;
    mil = dur;

    return min + ":" + sec + "." + mil;
}

Upvotes: 2

Aamir
Aamir

Reputation: 286

A bit Long Method but you can try this and it should probably work:

String time = "0:01.432";
   String[] time1 = time.split(":");
   String Minutes = time1[0]; //You get your Minutes here
   long min = Integer.parseInt(Minutes); //Converting into Integer

   String Sec_mSec=time1[1]; //Seconds & MilliSeconds
   String[] time2 =Sec_mSec.split("."); //Splitting Both

   String Seconds = time2[0]; //You get your Seconds here

   long sec = Integer.parseInt(Seconds); //Converting into Integer
   String mSeconds = time2[1]; //You get your Milli Seconds here
   long t = (min * 60) + sec;
   long result = TimeUnit.SECONDS.toMillis(t); //Minutes and Seconds in Millis
   long msec = Integer.parseInt(mSeconds); //Converting into Integer

   long f_result=result+msec //Final Result

Upvotes: 0

Hardik Parmar
Hardik Parmar

Reputation: 712

Since 1.5 there is the java.util.concurrent.TimeUnit class,Like...

String.format("%d min, %d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - 
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

If you want to add a leading zero for values 0-9,Like...

String.format("%02d min, %02d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - 
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

For Java versions below 1.5 or for systems that do not fully support the TimeUnit class like...

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

Upvotes: 0

Related Questions