-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Closed
Milestone
Description
I was working on something unrelated and needed to parse a string like 10s
or 10ms
, I did a quick search in my project and came up with:
logging-log4j2/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
Lines 639 to 674 in b4986fe
private enum TimeUnit { | |
NANOS("ns,nano,nanos,nanosecond,nanoseconds", ChronoUnit.NANOS), | |
MICROS("us,micro,micros,microsecond,microseconds", ChronoUnit.MICROS), | |
MILLIS("ms,milli,millis,millsecond,milliseconds", ChronoUnit.MILLIS), | |
SECONDS("s,second,seconds", ChronoUnit.SECONDS), | |
MINUTES("m,minute,minutes", ChronoUnit.MINUTES), | |
HOURS("h,hour,hours", ChronoUnit.HOURS), | |
DAYS("d,day,days", ChronoUnit.DAYS); | |
private final String[] descriptions; | |
private final ChronoUnit timeUnit; | |
TimeUnit(final String descriptions, final ChronoUnit timeUnit) { | |
this.descriptions = descriptions.split(","); | |
this.timeUnit = timeUnit; | |
} | |
ChronoUnit getTimeUnit() { | |
return this.timeUnit; | |
} | |
static Duration getDuration(final String time) { | |
final String value = time.trim(); | |
TemporalUnit temporalUnit = ChronoUnit.MILLIS; | |
long timeVal = 0; | |
for (TimeUnit timeUnit : values()) { | |
for (String suffix : timeUnit.descriptions) { | |
if (value.endsWith(suffix)) { | |
temporalUnit = timeUnit.timeUnit; | |
timeVal = Long.parseLong(value.substring(0, value.length() - suffix.length())); | |
} | |
} | |
} | |
return Duration.of(timeVal, temporalUnit); | |
} | |
} |
I'm not sure if it is a bug, but when it finds the first matching suffix it should immediately return, other wise it always falls through to SECONDS
for most of the covered cases and the order is slightly messed up as the SECONDS
could produce an early match for MINUTES
, HOURS
, and DAYS
.
ppkarwasz
Metadata
Metadata
Assignees
Labels
No labels