67 lines
1.5 KiB
Java
67 lines
1.5 KiB
Java
package creation;
|
|
|
|
public class MyDate {
|
|
public final int day, month, year;
|
|
|
|
public MyDate(int day, int month, int year) {
|
|
if (!isValid(day, month, year)) {
|
|
throw new IllegalArgumentException("Invalid date");
|
|
}
|
|
this.day = day;
|
|
this.month = month;
|
|
this.year = year;
|
|
}
|
|
|
|
public String asJsonArray() {
|
|
return "[" + year + ", " + month + ", " + day + "]";
|
|
}
|
|
|
|
public String asReadableString() {
|
|
return twoDigit(day) + "." + twoDigit(month) + "." + twoDigit(year);
|
|
}
|
|
|
|
public MyDate previous() {
|
|
if (isValid(day - 1, month, year)) {
|
|
return new MyDate(day - 1, month, year);
|
|
}
|
|
for (int possibleDay = 31; possibleDay >= 28; possibleDay--) {
|
|
if (isValid(possibleDay, month - 1, year)) {
|
|
return new MyDate(possibleDay, month - 1, year);
|
|
}
|
|
}
|
|
return new MyDate(31, 12, year - 1);
|
|
}
|
|
|
|
public MyDate ago(int number) {
|
|
MyDate d = this;
|
|
for (int i=0; i<number; i++) {
|
|
d = d.previous();
|
|
}
|
|
return d;
|
|
}
|
|
|
|
private static String twoDigit(int x) {
|
|
String s = ""+x;
|
|
while (s.length() < 2) {
|
|
s = "0"+s;
|
|
}
|
|
return s;
|
|
}
|
|
|
|
private boolean isValid(int day, int month, int year) {
|
|
int[] monthLengths = new int[] { 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
|
|
if (month < 1 || month > 12) {
|
|
return false;
|
|
}
|
|
int length = monthLengths[month - 1];
|
|
if (day < 1 || day > length) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private boolean isLeapYear(int year) {
|
|
return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
|
|
}
|
|
}
|