Skip to content

Instantly share code, notes, and snippets.

@outofrange
Last active August 29, 2015 14:21
Show Gist options
  • Save outofrange/913b93bcb34124eea0e1 to your computer and use it in GitHub Desktop.
Save outofrange/913b93bcb34124eea0e1 to your computer and use it in GitHub Desktop.
TimeConverter - converts Strings like "11w8d12h3m12s49ms" into milliseconds
package org.outofrange.timeconverter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeConverter {
private static final Pattern PATTERN = Pattern.compile("(\\d+)([A-Za-z]+)");
private TimeConverter() { }
public static long toMillis(String input) {
long sum = 0;
for (Duration d : getDurationParts(input)) {
sum += d.toMillis();
}
return sum;
}
private static List<Duration> getDurationParts(String input) {
final List<Duration> durations = new ArrayList<>();
final Matcher matcher = PATTERN.matcher(input);
while (matcher.find()) {
final long value = Long.valueOf(matcher.group(1));
final TimeStringUnit timeStringUnit = TimeStringUnit.forChars(matcher.group(2));
durations.add(new Duration(value, timeStringUnit));
}
return durations;
}
private static class Duration {
private final long value;
private final TimeStringUnit timeStringUnit;
public Duration(long value, TimeStringUnit timeStringUnit) {
this.value = value;
this.timeStringUnit = timeStringUnit;
}
public long toMillis() {
return timeStringUnit.toMillis(value);
}
}
private enum TimeStringUnit {
WEEKS("w") { public long toMillis(long d) { return 7 * TimeUnit.DAYS.toMillis(d); } },
DAYS("d") { public long toMillis(long d) { return TimeUnit.DAYS.toMillis(d); } },
HOURS("h") { public long toMillis(long d) { return TimeUnit.HOURS.toMillis(d); } },
MINUTES("m") { public long toMillis(long d) { return TimeUnit.MINUTES.toMillis(d); } },
SECONDS("s") { public long toMillis(long d) { return TimeUnit.SECONDS.toMillis(d); } },
MILLISECONDS("ms") { public long toMillis(long d) { return d; } };
private final String unit;
TimeStringUnit(String unit) {
this.unit = unit;
}
public String getUnit() {
return unit;
}
public long toMillis(long d) {
throw new AbstractMethodError();
}
public static TimeStringUnit forChars(String unit) {
for (TimeStringUnit timeStringUnit : TimeStringUnit.values()) {
if (timeStringUnit.getUnit().equals(unit)) {
return timeStringUnit;
}
}
throw new IllegalArgumentException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment