Created
April 7, 2017 19:23
-
-
Save l0rinc/ce37874348bf7c478fb83645b907d7b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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