【问题标题】:How to parse different time formats如何解析不同的时间格式
【发布时间】:2019-03-03 16:05:06
【问题描述】:

我在字符串中有不同的时间格式(来自视频播放器计数器)。 例如:

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 库解析所有这些格式?

如果我使用这样的代码:

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 是更适合这些值的类型。例如,您不能将123:03:45 存储在localTime 对象中(123 在几小时内超出范围)
  • 123:03:45 是持续时间而不是本地时间。您可以直接拆分 :'s 并提取小时、分钟、秒组件。
  • 嗨@OleV.V。我不认为 OP 要求HH:mm:ssmm:ssHH:mm:ss 的任何格式,我看不到任何答案可以回答这个特定问题
  • 感谢您的帮助!

标签: java datetime time localtime


【解决方案1】:

还有更多的可能性。我可能会去修改时间字符串以符合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 接受的 ISO 8601 格式。

您需要 Duration 类有两个原因:(1) 如果我理解正确,您的时间字符串表示持续时间,因此使用 LocalTime 是不正确的,并且会混淆那些在您之后维护您的代码的人。 (2) LocalTime 的最大值是 23:59:59.999999999,所以它永远不会接受 123:03:45。

【讨论】:

  • 智能解决方案 Ole V.V. ;)
【解决方案2】:

从 cmets 和我之前读到的内容,您无法解析 mm:ss,为了解决您的问题,让我们将所有时间转换为秒,然后将该秒转换为 持续时间 而不是 LocalTime,这是您的问题的解决方案:

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);    
}

输出或持续时间是

PT3M45S              -> 03:45 
PT1H3M45S            -> 1:03:45  
PT123H3M45S          -> 123:03:45

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2018-08-29
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多