Skip to content

Instantly share code, notes, and snippets.

@l0rinc
Created April 7, 2017 19:23
Show Gist options
  • Save l0rinc/ce37874348bf7c478fb83645b907d7b8 to your computer and use it in GitHub Desktop.
Save l0rinc/ce37874348bf7c478fb83645b907d7b8 to your computer and use it in GitHub Desktop.
package com.crossover.trial;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public class TimeParser {
public LocalDateTime parseDuration(String duration, LocalDateTime now) {
for (Matcher m = Pattern.compile("(\\d+) (\\w)s?").matcher(duration);m.find();)
now = addTime(now, m.group(2), Integer.parseInt(m.group(1)));
return now;
}
private LocalDateTime addTime(LocalDateTime now, String timeUnit, int amount) {
switch (timeUnit) {
case "minute": return now.minusMinutes(amount);
case "hour": return now.minusHours(amount);
case "day": return now.minusDays(amount);
case "week": return now.minusWeeks(amount);
case "month": return now.minusMonths(amount);
case "year": return now.minusYears(amount);
default: throw new IllegalArgumentException(timeUnit);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment