Skip to content

Issue with Duration ParsingΒ #1963

@RapidTransit

Description

@RapidTransit

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:

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions