我必须在seekTo()
类的MediaPlayer
方法中使用一些字符串时间,但这些格式为0:01.432
。
现在如何将其转换为毫秒?
答案 0 :(得分:2)
我创建了这两种将文本转换为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;
}
和int到文本
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;
}
答案 1 :(得分:0)
从1.5开始就有java.util.concurrent.TimeUnit
类,比如......
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
如果要为值0-9添加前导零,请...
String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
对于1.5以下的Java版本或不完全支持TimeUnit
类的系统,如...
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
答案 2 :(得分:0)
有点长的方法,但你可以尝试这个,它应该可以工作:
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