Created
April 7, 2017 21:06
-
-
Save l0rinc/514130495af82d5991f710c0d6016423 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.Arrays; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import static org.junit.Assert.assertEquals; | |
public class Solution { | |
public static void main(String[] args) { | |
class Data { | |
private String input; | |
private LocalDateTime expected; | |
private Data(String input, LocalDateTime expected) { | |
this.input = input; | |
this.expected = expected; | |
} | |
} | |
LocalDateTime now = LocalDateTime.now(); | |
Arrays.asList( | |
new Data("0 minutes ago", now.minusMinutes(0)), | |
new Data("1 minute ago", now.minusMinutes(1)), | |
new Data("2 minutes ago", now.minusMinutes(2)), | |
new Data("11 hours, 39 minutes ago", now.minusHours(11).minusMinutes(39)), | |
new Data("1 day ago", now.minusDays(1)), | |
new Data("2 days, 12 hours ago", now.minusDays(2).minusHours(12)), | |
new Data("1 week ago", now.minusWeeks(1)), | |
new Data("1 week, 1 day ago", now.minusWeeks(1).minusDays(1)), | |
new Data("3 weeks, 5 days ago", now.minusWeeks(1).minusDays(3)), | |
new Data("1 month ago", now.minusMonths(1)), | |
new Data("2 months ago", now.minusMonths(2)), | |
new Data("2 months, 1 week ago", now.minusMonths(2).minusWeeks(1)), | |
new Data("5 month, 3 weeks ago", now.minusMonths(5).minusWeeks(3)), | |
new Data("1 year ago", now.minusYears(1)), | |
new Data("2 years ago", now.minusYears(2)), | |
new Data("2 year, 1 week ago", now.minusYears(2).minusWeeks(1)), | |
new Data("2 years, 2 weeks ago", now.minusYears(2).minusWeeks(2)) | |
).forEach(it -> assertEquals(it.expected.getMinute(), new Solution.TimeParser().parseDuration(it.input, now).getMinute())); | |
} | |
public static class TimeParser { | |
public LocalDateTime parseDuration(String duration, LocalDateTime now) { | |
for (Matcher m = Pattern.compile("(\\d+) ([a-rt-z]+)").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