/*
*Date 存储 年-月-日 信息
*原则:一切从用户角度出发
*功能:
1) 初始化
1.传入年/月/日
2.不传,今天
2)多少天后的年月日
3)多少天前的年月日
*/
import java.util.Calendar ;
public class Date{
private int year;
private int month;
private int day;
private static final int[] DAYS_OF_MONTH = {31,28,31,30,31,30,31,31,30,31,30,31};
//构造方法
//年支持的范围[1840-2020]
//月支持的范围[1,12]
//日支持的范围
public Date(int year, int month, int day){
if(year<1840 || year>2021)
{
System.err.println("年支持的范围是[1840,2021]");
return;
}
if(month<1||month>12)
{
System.err.println("无此月份");
return;
}
if(day<1||day>calaDayOfMonth(year,month))
{
System.err.println("天数不对");
return;
}
this.year = year;
this.month = month;
this.day = day;
}
//final 不可变
private static final int calaDayOfMonth(int year, int month)
{
if(month!=2)
{
return DAYS_OF_MONTH[month-1];
}
if(isLeapYear(year))
{
return 29;
}
else
{
return 28;
}
}
private static boolean isLeapYear(int year){
if(year%4==0&&year%100!=0)
{
return true;
}
else if(year%400==0)
{
return true;
}
else{
return false;
}
}
public Date immutableafter(int days){
Date other = new Date(year,month,day);
day+=days;
while(day>calaDayOfMonth(year,month))
{
day-=calaDayOfMonth(year,month);
month+=1;
if(month>12)
{
month = 1;
year+=1;
}
}
return other;
}
public Date immutablebefore(int days)
{
Date other = new Date(year,month,day);
day=days-day;
while(day>calaDayOfMonth(year,month-1))
{
day-=calaDayOfMonth(year,month-1);
month-=1;
if(month<=1)
{
day=day-31;
month=12;
year-=1;
}
}
if(day<calaDayOfMonth(year,month-1))
{
month-=1;
day=calaDayOfMonth(year,month)-day;
}
if(day==calaDayOfMonth(year,month-1))
{
month-=2;
day=calaDayOfMonth(year,month);
}
return other;
}
//todo:实现a-b相差多少天
public static int diff(Date a,Date b){
int re=0;//re为相差几天的天数
Calendar date1 = Calendar.getInstance();
date1.set(a.year,a.month,a.day);
//date1.set(y1,m1,d1);
System.out.println(date1.getTime());
long mis1 = (long)date1.getTime().getTime();
Calendar date2 = Calendar.getInstance();
date2.set(b.year,b.month,b.day);
//date1.set(y2,m2,d2);
System.out.println(date2.getTime());
long mis2 = (long)date2.getTime().getTime();
if(mis1>mis2)
{
System.out.println("相差的天数为:"+(mis1-mis2)/1000/60/60/24);
re=(int)(mis1-mis2)/1000/60/60/24;
}
else if(mis1==mis2)
{
System.out.println("同一天");
re=0;
}
else
{
System.out.println("相差的天数为:"+(mis2-mis1)/1000/60/60/24);
re=(int)(mis2-mis1)/1000/60/60/24;
}
return re;
}
public String toString(){
return String.format("%04d-%02d-%02d",year,month,day);
}
public static void main(String[] args){
Date now1 = new Date(2019,7,20);//Date实例化两个不同的now
Date now2 = new Date(2020,7,31);
int re = diff(now1,now2);
System.out.println(re);
//Date r = d.after(300);
//Date before = now.immutablebefore(900);
//Date after = now.immutableafter(300);
//System.out.println(after);
//System.out.println(before);
//System.out.println(now);
}
}