我在字符串中有不同的时间格式(来自videoplayer计数器)。例如:
03:45 -> 3 munutes, 45 seconds
1:03:45 -> 1 hour, 3 munutes, 45 seconds
123:03:45 -> 123 hours, 3 munutes, 45 seconds
如何使用LocalTime lib解析所有这些格式?
如果我使用这样的代码:
LocalTime.parse(time, DateTimeFormatter.ofPattern("[H[H]:]mm:ss"));
它适用于“1:03:45”或“11:03:45”,但对于“03:55”我有例外
java.time.format.DateTimeParseException: Text '03:55' could not be parsed at index 5
有更多的可能性。我可能会修改时间字符串以符合Duration.parse
接受的语法。
String[] timeStrings = { "03:45", "1:03:45", "123:03:45" };
for (String timeString : timeStrings) {
String modifiedString = timeString.replaceFirst("^(\\d+):(\\d{2}):(\\d{2})$", "PT$1H$2M$3S")
.replaceFirst("^(\\d+):(\\d{2})$", "PT$1M$2S");
System.out.println("Duration: " + Duration.parse(modifiedString));
}
输出是:
Duration: PT3M45S Duration: PT1H3M45S Duration: PT123H3M45S
小时,分钟和秒(两个冒号)的情况由第一次调用replaceFirst
处理,replaceFirst
反过来移除两个冒号并确保第二个replaceFirst
不替换任何东西。在只有一个冒号(分钟和秒)的情况下,第一个replaceFirst
不能重复任何东西并将字符串不变地传递给第二个Duration.parse
调用,后者又转换为Duration
接受的ISO 8601格式。
你需要LocalTime
类有两个原因:(1)如果我理解正确,你的时间字符串表示一个持续时间,所以使用LocalTime
是不正确的,并会混淆那些维护你的代码的人。 (2)mm:ss
的最大值是23:59:59.999999999,因此它永远不会接受123:03:45。
从评论和我之前阅读的内容,你无法解析String[] times = {"03:45", "1:03:45", "123:03:45"};
for (String time : times) {
List<Integer> parts = Arrays.stream(time.split(":"))
.map(Integer::valueOf)
.collect(Collectors.toList());
Collections.reverse(parts);
int seconds = (int) IntStream.range(0, parts.size())
.mapToDouble(index -> parts.get(index) * Math.pow(60, index))
.sum();
Duration result = Duration.ofSeconds(seconds);
System.out.println(result);
}
,解决你的问题让我们将所有时间转换为秒,然后将秒转换为持续时间而不是LocalTime,这里是你的问题的解决方案:
PT3M45S -> 03:45
PT1H3M45S -> 1:03:45
PT123H3M45S -> 123:03:45
输出或持续时间是
qazxswpoi