java Android:将分钟和秒转换为毫秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17808935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 15:04:38  来源:igfitidea点击:

Android: Converting minutes and seconds to millisecond

javaandroid

提问by Hammad Tariq

I am trying to convert time which I have in static string such as "07:02" into milliseconds. I am looking at documentation TimeUnitand 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?

我正在尝试将静态字符串中的时间(例如“07:02”)转换为毫秒。我正在查看文档TimeUnit并试图让我的字符串以毫秒为单位进行转换,但首先我有一个字符串,所以我猜转换器函数不接受字符串,其次我有分钟和秒,所以我应该将它们转换为一个然后添加它们?似乎不是一个好方法?

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

回答by Husman

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

我刚刚检查了 TimeUnit 的文档。你可以这样做:

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);

回答by mksteve

I came up with the following approach.

我想出了以下方法。

Split the time by the ':' and use the TimeUnit function.

按“:”分割时间并使用 TimeUnit 函数。

    int convertTime(String timeString) {
        String[] time = timeString.split ( ":" );
        int pos = time.length - 1;
        long res = 0;
        if( pos >=0 ){
            res = res + TimeUnit.SECONDS.toMillis( Long.parseLong( time[pos] ));
            pos --;
        }
        if( pos >=0 ){
            res = res + TimeUnit.MINUTES.toMillis( Long.parseLong( time[pos] ));
            pos --;
        }
        if( pos >=0 ){
            res = res + TimeUnit.HOURS.toMillis( Long.parseLong( time[pos] ));
            pos --;
        }
        return (int)res;
    }

The code is more complex, as it should work with

代码更复杂,因为它应该与

10
1:10
01:10
1:10:20

回答by Husman

The algorithm would be as follows:

算法如下:

  1. convert to integer (int minutes, int seconds)
  2. convert the minutes to seconds (i.e. minutes*60;)
  3. add the converted minutes to the seconds (i.e. int total = (minutes*60) + seconds;)
  4. convert to milliseconds (i.e. milli = total/1000)
  1. 转换为整数(int 分钟,int 秒)
  2. 将分钟转换为秒(即分钟*60;)
  3. 将转换后的分钟与秒相加(即 int total = (minutes*60) + seconds;)
  4. 转换为毫秒(即毫秒 = 总计/1000)