java - 将字符串“5m 12s 635ms”转换为“05:12:635”
问题描述
我需要转换如下所示的字符串:
“5m 12s 635ms” “5m 12s” “12s 635ms” 等
注意:字符串可能包含也可能不包含任何单独的时间元素。
格式为:hh:mm:ss.SSS
有没有一种简单的方法可以做到这一点?我查看了 simpledateformat,它不需要输入字符串进行转换。
-格雷格
解决方案
格式为:hh:mm:ss.SSS
这工作如下:
- 转换为
xxs
_yyyms
xx.yyys
- 然后只需解析持续时间并添加到
LocalTime
实例
public static void main(String[] args) {
String[] times = { "5m 12s 635ms", "5m 12s", "12s 635ms",
"1h 17m 12s 998ms", "2h 222ms" };
for (String tm : times) {
System.out.printf("%18s --> %10s%n",tm, formatTime(tm));
}
}
public static String formatTime(String time) {
// modify seconds for Duration parse
String modtm = time.replaceAll("(\\d+)s\\s+(\\d+)ms", "$1.$2s")
.replaceAll("(\\d+)ms", "0.$1s");
// now build up the local time value
LocalTime lt = LocalTime.of(0, 0);
for (String v : modtm.split("\\s+")) {
lt = lt.plus(Duration.parse("PT" + v));
}
return lt.format(
DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
印刷
5m 12s 635ms --> 00:05:12.635
5m 12s --> 00:05:12.000
12s 635ms --> 00:00:12.635
1h 17m 12s 998ms --> 01:17:12.998
2h 222ms --> 02:00:00.222
如果您的秒数已经是 ss.sss 格式(例如 12.635s),那会简单得多。但replaceAll
照顾它。
推荐阅读
- macos - `brew list` 显示了很多我没有安装的东西。为什么?如果安装的东西取决于他们,我怎么知道?
- google-sheets - 如何使这个 Google 表格公式更简单?
- python - 利用前一行的数据应用列数学运算,没有 For 循环?
- azure - Azure 中的 Web 部署任务失败
- python - 如何重塑numpy数组以将行变成列
- python - 除了块内的logger.error导致程序停止运行?
- python - 在哪里可以找到 python 中 bog 标准异常类的原始代码
- pytorch - cuda.amp 和 model.half() 有什么区别?
- python - 一个 python 脚本循环一个变量并运行其他 3 个使用该变量的脚本
- python - 将元素的值分配给变量输出