【问题标题】:Convert given time in String format to seconds in Android将字符串格式的给定时间转换为Android中的秒数
【发布时间】:2015-05-30 03:23:43
【问题描述】:

假设时间以字符串格式的 MM:SS(ex- 02:30) 或 HH:MM:SS 给出。我们如何将这个时间转换为秒。

【问题讨论】:

标签: java android


【解决方案1】:

我在 Kotlin 中编写了一个扩展函数,用于将字符串转换为秒

fun String?.converTimeToSeconds(): Int {
if (this.isNullOrEmpty().not()) {
    val units = this?.split(":")?.toTypedArray() 
    if (units?.isNotEmpty() == true && units.size >= 3) {
        val hours = units[0].toInt()
        val minutes = units[1].toInt()
        val seconds = units[2].toInt()
        return (3660 * hours) + (60 * minutes) + seconds 
    }

}
return 0

}

【讨论】:

    【解决方案2】:
    int v = 0;
    for (var x: t.split(":")) {
        v = v * 60 + new Byte(x);
    }
    

    这个 sn-p 应该支持 HH:MM:SS(v 以秒为单位)或 HH:MM(v 以分钟为单位)

    【讨论】:

      【解决方案3】:
      private static final String TIME_FORMAT = "hh:mm a";//give whatever format you want.
      
      //Function calling
      long timeInMillis = TimeUtils.getCurrentTimeInMillis("04:21 PM");
      long seconds = timeInMillis/1000;
      
      //Util Function
      public static long getCurrentTimeInMillis(String time) {
          SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
          //        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //getting exact milliseconds at GMT
          //        sdf.setTimeZone(TimeZone.getDefault());
          Date date = null;
          try {
              date = sdf.parse(time);
          } catch (ParseException e) {
              e.printStackTrace();
          }
          return date.getTime();
      }
      

      【讨论】:

        【解决方案4】:
        public class TimeToSeconds {
            // given: mm:ss or hh:mm:ss or hhh:mm:ss, return number of seconds.
            // bad input throws NumberFormatException.
            // bad includes:  "", null, :50, 5:-4
            public static long parseTime(String str) throws NumberFormatException {
                if (str == null)
                    throw new NumberFormatException("parseTimeString null str");
                if (str.isEmpty())
                    throw new NumberFormatException("parseTimeString empty str");
        
                int h = 0;
                int m, s;
                String units[] = str.split(":");
                assert (units.length == 2 || units.length == 3);
                switch (units.length) {
                    case 2:
                        // mm:ss
                        m = Integer.parseInt(units[0]);
                        s = Integer.parseInt(units[1]);
                        break;
        
                    case 3:
                        // hh:mm:ss
                        h = Integer.parseInt(units[0]);
                        m = Integer.parseInt(units[1]);
                        s = Integer.parseInt(units[2]);
                        break;
        
                    default:
                        throw new NumberFormatException("parseTimeString failed:" + str);
                }
                if (m<0 || m>60 || s<0 || s>60 || h<0)
                    throw new NumberFormatException("parseTimeString range error:" + str);
                return h * 3600 + m * 60 + s;
            }
        
            // given time string (hours:minutes:seconds, or mm:ss, return number of seconds.
            public static long parseTimeStringToSeconds(String str) {
                try {
                    return parseTime(str);
                } catch (NumberFormatException nfe) {
                    return 0;
                }
            }
        
        }
        
        
        import org.junit.Test;
        
        import static org.junit.Assert.*;
        
        public class TimeToSecondsTest {
        
            @Test
            public void parseTimeStringToSeconds() {
        
                assertEquals(TimeToSeconds.parseTimeStringToSeconds("1:00"), 60);
                assertEquals(TimeToSeconds.parseTimeStringToSeconds("00:55"), 55);
                assertEquals(TimeToSeconds.parseTimeStringToSeconds("5:55"), 5 * 60 + 55);
                assertEquals(TimeToSeconds.parseTimeStringToSeconds(""), 0);
                assertEquals(TimeToSeconds.parseTimeStringToSeconds("6:01:05"), 6 * 3600 + 1*60 + 5);
            }
        
            @Test
            public void parseTime() {
                // make sure all these tests fail.
                String fails[] = {null, "", "abc", ":::", "A:B:C", "1:2:3:4", "1:99", "1:99:05", ":50", "-4:32", "-99:-2:4", "2.2:30"};
                for (String t: fails)
                {
                    try {
                        long seconds = TimeToSeconds.parseTime(t);
                        assertFalse("FAIL: Expected failure:"+t+" got "+seconds, true);
                    } catch (NumberFormatException nfe)
                    {
                        assertNotNull(nfe);
                        assertTrue(nfe instanceof NumberFormatException);
                        // expected this nfe.
                    }
                }
            }
        
        
        }
        

        【讨论】:

          【解决方案5】:

          在您的情况下,使用您的示例,您可以使用以下内容:

          String time = "02:30"; //mm:ss
          String[] units = time.split(":"); //will break the string up into an array
          int minutes = Integer.parseInt(units[0]); //first element
          int seconds = Integer.parseInt(units[1]); //second element
          int duration = 60 * minutes + seconds; //add up our values
          

          如果您想包含小时数,只需修改上面的代码并将小时数乘以 3600,即一小时的秒数。

          【讨论】:

            【解决方案6】:

            试试这个

            hours = totalSecs / 3600;
            minutes = (totalSecs % 3600) / 60;
            seconds = totalSecs % 60;
            
            timeString = String.format("%02d",seconds);
            

            【讨论】:

            • 嗨,他已经有了小时分钟和秒(HH:MM:SS)。他想将其转换为毫秒。首先正确阅读问题。然后回答
            • @Signare 他问“我们如何将这个时间转换为秒”。他没有说毫秒
            • 分钟 = (totalSecs % 3600) / 60;我挣扎了几分钟。这条线解决了我的问题。谢谢。
            猜你喜欢
            • 2013-10-28
            • 1970-01-01
            • 1970-01-01
            • 2021-03-16
            • 2011-07-04
            • 2019-12-15
            • 1970-01-01
            • 2011-05-07
            • 1970-01-01
            相关资源
            最近更新 更多