如何转换00:00:00格式的字符串时间值?

时间:2018-09-21 11:28:04

标签: android string

我有一个字符串

字符串时间= 1小时37分钟 如何在Android中将此时间转换为1:37:00格式?

2 个答案:

答案 0 :(得分:0)

1)第一步,从字符串中删除空间(字符串=“ 1小时37分钟”)

   text = string.replace(" ", "");

2)第二步,将小时替换为“:”,将分钟替换为“:00”

text = text.replace("hour",":");
      text = text.replace("minutes",":00");

答案 1 :(得分:0)

我想您必须编写一个函数,将字符串格式化为所需的格式。您的功能应如下所示:

public static String formatTime(String inputTime)
{
String result = inputTime.replace(" ","");
result = result.replace("hours",":").replace("hour",":").replace("minutes","").replace("minute","");
String[] resultAux = result.split(":"); //First position will be hours, second position will be minutes

for(int i=0; i<resultAux.length; i++)
{
    if(resultAux[i].length() == 1)
    {
        resultAux[i] = "0" + resultAux[i]; //If we have 1 character in minutes we put the 0
    }
}

return String.join(":",resultAux) + ":00"; //Due to in your example you don't mention that you can have miliseconds we just put the miliseconds at the end


}

当然,您将这样调用函数:

System.out.println("result is: " + formatTime("2 hours 37 minutes"));