20
20
21
21
import java .math .BigInteger ;
22
22
import java .time .Duration ;
23
+ import java .time .format .DateTimeParseException ;
23
24
import java .time .temporal .ChronoUnit ;
24
25
import java .util .Arrays ;
25
26
import java .util .Collections ;
@@ -43,7 +44,8 @@ public class TimeUtils {
43
44
/**
44
45
* Parse the given string to a java {@link Duration}. The string is in format "{length
45
46
* value}{time unit label}", e.g. "123ms", "321 s". If no time unit label is specified, it will
46
- * be considered as milliseconds.
47
+ * be considered as milliseconds. If above rules are not matched, it will fall back to parse
48
+ * ISO-8601 duration format.
47
49
*
48
50
* <p>Supported time unit labels are:
49
51
*
@@ -77,7 +79,19 @@ public static Duration parseDuration(String text) {
77
79
final String unitLabel = trimmed .substring (pos ).trim ().toLowerCase (Locale .US );
78
80
79
81
if (number .isEmpty ()) {
80
- throw new NumberFormatException ("text does not start with a number" );
82
+ try {
83
+ // Fall back to parse ISO-8601 duration format
84
+ Duration parsedDuration = Duration .parse (trimmed );
85
+ if (parsedDuration .isNegative ()) {
86
+ // Don't support negative duration which is consistent with before format
87
+ throw new NumberFormatException ("negative duration is not supported" );
88
+ }
89
+ return parsedDuration ;
90
+ } catch (DateTimeParseException e ) {
91
+ throw new NumberFormatException (
92
+ "text does not start with a number, and is not a valid ISO-8601 duration format: "
93
+ + trimmed );
94
+ }
81
95
}
82
96
83
97
final BigInteger value ;
0 commit comments