JAVA持续时间

时间:2016-11-28 14:46:29

标签: java time duration

我有一个应用,我需要检查旅行的持续时间是否在4小时到30小时之间,我将其存储为字符串“04:00”“30:00 “,然后我尝试使用LocalTime.parse()解析它,”04:00“已成功解析但”30:00“收到错误对于无效格式,什么可能是从字符串解析持续时间小时的最佳方法?

1 个答案:

答案 0 :(得分:4)

首先,你存储的方式有点不对劲。我建议以标Duration.parse格式ISO 8601处理它的方式存储它。

Examples:

    "PT20.345S" -- parses as "20.345 seconds"
    "PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
    "PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
    "P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
    "P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
    "P-6H3M"    -- parses as "-6 hours and +3 minutes"
    "-P6H3M"    -- parses as "-6 hours and -3 minutes"
    "-P-6H+3M"  -- parses as "+6 hours and -3 minutes"

那么你就可以这样做:

Duration dur30H = Duration.parse("PT30H"); // 30h
Duration dur4H = Duration.parse("PT4H"); // 4h
Duration travelTime = Duration.parse("P1D"); // 1D
boolean result = travelTime.compareTo(dur30H) <= 0 && travelTime.compareTo(dur4H) >= 0; // true