首页 > 解决方案 > 将字符串“5m 12s 635ms”转换为“05:12:635”

问题描述

我需要转换如下所示的字符串:

“5m 12s 635ms” “5m 12s” “12s 635ms” 等

注意:字符串可能包含也可能不包含任何单独的时间元素。

格式为:hh:mm:ss.SSS

有没有一种简单的方法可以做到这一点?我查看了 simpledateformat,它不需要输入字符串进行转换。

-格雷格

标签: java

解决方案


格式为:hh:mm:ss.SSS

这工作如下:

  • 转换为xxs_yyymsxx.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照顾它。


推荐阅读