Skip to content

Instantly share code, notes, and snippets.

@bdurrer
Created March 25, 2019 08:00
Show Gist options
  • Save bdurrer/7c1d8cad2105bb5a107914c0b9702244 to your computer and use it in GitHub Desktop.
Save bdurrer/7c1d8cad2105bb5a107914c0b9702244 to your computer and use it in GitHub Desktop.
Java port of the "ms" npm library (on github: zeit/ms)
package com.swiss.pegma.middleware.core.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateUtils {
private static final Pattern READABLE_DURATION_PATTERN = Pattern.compile("([0-9]+)[\\s]*([a-zA-Z]+)");
/**
* Parses a human readable duration string in format {amount}{unit}.
* This is adapted from the NPM "MS" library.
*
* @param durationString {amount}{unit}, eg. 20min
* @return the duration in milliseconds
* @params defaultDurationString fallback duration, if the durationString is empty or null
* @see <a href="https://github.com/zeit/ms/">GitHub</a>
*/
public static long parseHumanReadableDuration(String durationString, String defaultDurationString) {
if (StringUtils.isBlank(durationString) && StringUtils.isBlank(defaultDurationString)) {
throw new RuntimeException("Unable to parse empty duration, fallback string was also empty");
}
Matcher matcher = READABLE_DURATION_PATTERN.matcher(
StringUtils.isBlank(durationString) ? defaultDurationString : durationString);
if (!matcher.matches() || matcher.groupCount() < 2) {
throw new RuntimeException("Unable to parse duration " + durationString);
}
final long time = Long.parseLong(matcher.group(1));
String unit = matcher.group(2);
long multiSec = 1000;
long multiMin = multiSec * 60;
long multiHour = multiMin * 60;
long multiDay = multiHour * 24;
long multiWeek = multiDay * 7;
long multiYear = multiDay * 365;
switch (unit) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return time * multiYear;
case "weeks":
case "week":
case "w":
return time * multiWeek;
case "days":
case "day":
case "d":
return time * multiDay;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return time * multiHour;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return time * multiMin;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return time * multiSec;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return time;
default:
throw new RuntimeException("Unknown duration format of" +
(StringUtils.isBlank(durationString) ? defaultDurationString : durationString));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment