我的程序获取两个时间值并减去它。
减法后有时结果可能是这样的(分钟:秒。毫秒):
9:7.110
但我希望我的程序打印另一个数字(如果分钟、秒或毫秒仅包含一位数字,则在该数字之前打印零:
09:07.110
也许是这样的格式:
DateTimeFormatter formatterForResultedPrinting = DateTimeFormatter.ofPattern("mm:ss.SSS");
我存储了这次:
9:7.110
在字符串中。
最佳答案
您已经获得了一个String
,并且您想要的输出也是一个String
。为什么不使用简单的 String
函数创建自己的函数,如下所示?
public class Main {
public static void main(String[] args) {
try {
System.out.println(convert("09:07.110"));
System.out.println(convert("9:07.110"));
System.out.println(convert("09:7.1"));
System.out.println(convert("9:07.11"));
System.out.println(convert("9:7a.110"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
static String convert(String str) throws IllegalArgumentException {
String mm = str.substring(0, str.indexOf(":"));
String ss = str.substring(str.indexOf(":") + 1, str.indexOf("."));
String mil = str.substring(str.indexOf(".") + 1);
if (mm.length() == 0 || mm.length() > 2 || ss.length() == 0 || ss.length() > 2 || mil.length() == 0
|| mil.length() > 3 || !mm.matches("[0-9]+") || !ss.matches("[0-9]+") || !mil.matches("[0-9]+")) {
throw new IllegalArgumentException("Invalid time string");
}
mm = mm.length() == 1 ? "0" + mm : mm;
ss = ss.length() == 1 ? "0" + ss : ss;
mil = mil.length() == 1 ? "00" + mil : (mil.length() == 2 ? "0" + mil : mil);
return mm + ":" + ss + "." + mil;
}
}
输出:
09:07.110
09:07.110
09:07.001
09:07.011
Invalid time string
关于java - 这次我该如何转换: "9:7.110" to "09:07.110"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59346906/