public class MyDate {
public int year;
public int month;
public int day;
//1.必须得校验传入参数的合法性
// year : 1 <= year
// month : 1 <= month <= 12
// day : 1 <= day <= 每个月的天数
//2. 如果不符合,应该怎么办
// 抛异常
public MyDate(int year, int month, int day) {
if (year < 1){
RuntimeException exception = new RuntimeException("year 参数错误");
throw exception;
}
if (month < 1 || month > 12){
throw new RuntimeException("month 参数错误");
}
if (day < 1 || day > getMonthDay(year,month)){
throw new RuntimeException("day 参数错误");
}
this.year = year;
this.month = month;
this.day = day;
}
//用于复制from对象
public MyDate(MyDate from){
this.year =from.year;
this.month = from.month;
this.day = from.day;
}
private int getMonthDay(int year,int month) {
switch (month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:return 31;
case 4:
case 6:
case 9:
case 11:return 30;
case 2:
if(isLeapYear(year))
return 29;
else
return 28;
default:
return -1;
}
}
private boolean isLeapYear(int year) {
return ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 );
}
@Override
public String toString() {
return String.format("%4d-%02d-%02d",year,month,day);
}
public int 计算相差天数(MyDate from){
if(this.compareTo(from) <= 0 ){
throw new RuntimeException("from 的日期必须是当前日期之前");
}
int count = 0;
MyDate fromCopy = new MyDate(from);
while(fromCopy.compareTo(this) < 0){
fromCopy.increment();
System.out.println(fromCopy);
count ++;
}
return count;
}
private void increment() {
if(day < getMonthDay(year,month)){
day ++;
return;
}else{
day = 1;
if(month < 12) {
month++;
}else {
month = 1;
year ++;
}
return;
}
}
//定义一个方法比较(this,other)
//规定,如果this < from 返回任意负数
//如果 this == from 返回0
//如果 this > from 返回任意正数
public int compareTo(MyDate from){
if(year != from.year){
// if (year > from.year){
// return 1;
// }else {
// return -1;
// }
return year - from.year;
}
//说明year == from.year
if (month != from.month) {
return month - from.month;
}
//说明year == from.year && month == from.month
return day - from.day;
}
}
具体使用:
public class MyDateTest {
public static void main(String[] args) {
MyDate from = new MyDate(2021,2,1);
MyDate to = new MyDate(2021,2,15);
//System.out.println(to.compareTo(from));
System.out.printf("从 %s 到 %s 经过了 %d 天\n",from,to,to.计算相差天数(from));
}
}
运行结果如下: