Skip to content

Instantly share code, notes, and snippets.

@JohnnyNonsense
Created November 19, 2014 10:15
DailyProgrammer, Weekly #17, Saturday Birthday
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class SaturdayBirthday {
public static class Info {
private static final DateTimeFormatter dtf
= DateTimeFormatter.ofPattern("EEE, d MMM yyyy");
private final LocalDate birthday;
private final LocalDate current;
private final LocalDate future;
public Info(LocalDate current, LocalDate birthday, LocalDate future) {
this.current = current;
this.birthday = birthday;
this.future = future;
}
@Override
public String toString() {
return dtf.format(future) + " (" + getDaysToFuture()
+ " days, age " + getAgeFuture() + ")";
}
private long getDaysToFuture() {
Duration duration = Duration.between(current.atTime(0, 0),
future.atTime(0, 0));
return duration.toDays();
}
private int getAgeFuture() {
Period period = Period.between(birthday, future);
return period.getYears();
}
}
public Info solve(String bday) {
DateTimeFormatter[] formats = {
DateTimeFormatter.ofPattern("yyyy-MM-dd"),
DateTimeFormatter.ofPattern("d MMM yyyy"),
DateTimeFormatter.ofPattern("dd.MM.yyyy"),
DateTimeFormatter.ofPattern("MMM d, yyyy")
};
for (DateTimeFormatter dft : formats) {
try {
LocalDate birthday = LocalDate.parse(bday, dft);
LocalDate now = LocalDate.now();
int offset = 0;
while (true) {
LocalDate test = birthday.plusYears(offset);
if (test.isAfter(now)
&& test.getDayOfWeek() == DayOfWeek.SATURDAY) {
Info info = new Info(now, birthday, test);
return info;
}
offset++;
}
} catch (DateTimeParseException dtpe) {
}
}
return null;
}
public static void main(String[] args) {
SaturdayBirthday problem = new SaturdayBirthday();
String[] bdays = {"11 May 1968", "11.05.1968", "1968-05-11",
"May 11, 1968"};
for (String bday : bdays) {
SaturdayBirthday.Info info = problem.solve(bday);
if (info != null) {
System.out.println(bday + " -> " + info);
} else {
System.out.println(bday + " -> <parse error>");
}
}
}
}
@JohnnyNonsense
Copy link
Author

output:
11 May 1968 -> Sat, 11 May 2019 (1634 days, age 51)
11.05.1968 -> Sat, 11 May 2019 (1634 days, age 51)
1968-05-11 -> Sat, 11 May 2019 (1634 days, age 51)
May 11, 1968 -> Sat, 11 May 2019 (1634 days, age 51)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment