1 import java.util.*; 2 import java.lang.Math; 3 4 class Date1{ 5 private int year; 6 private int month; 7 private int day; 8 Date1(){ 9 year=1900; 10 month=1; 11 day=1; 12 } 13 Date1(int y,int m,int d){ 14 this.year=y; 15 this.month=m; 16 this.day=d; 17 } 18 public int getYear(){ 19 return year; 20 } 21 public int getMonth(){ 22 return month; 23 } 24 public int getDay(){ 25 return day; 26 } 27 public boolean equals(Date1 d2){ //判断两个日期是否相等 28 if(this.year==d2.year&&this.month==d2.month&&this.day==d2.day) 29 return true; 30 else 31 return false; 32 } 33 public long getTime(){ //计算从调用该方法的对象所表示的日期到历元的时间,单位是毫秒 34 Calendar c=Calendar.getInstance(); //Calendar类的对象的创建方式 35 c.set(getYear(), getMonth(),getDay()); //设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值 36 return c.getTimeInMillis(); //计算时间,返回值是long型 37 } 38 39 //上面的方法用Date类的getTime方法也可以做,但是没有把输入的时间接收的方法.故用Calendar类 40 public int compareTo(Date1 c2){ //计算天数差 41 long t1=this.getTime(); 42 long t2=c2.getTime(); 43 return (int)(Math.abs(t1-t2)/3600/24/1000); //所得到的时间差的绝对值除以1000换算为秒,除以3600换算为小时,除以24换算为天 44 } 45 } 46 public class Test3 { 47 public static void main(String args[]){ 48 int y1=0,m1=0,d1=0,y2=0,m2=0,d2=0; 49 Scanner input=new Scanner(System.in); 50 System.out.println("请输入2个日期(eg:2013 04 17),年月日以空格分隔"); 51 y1=input.nextInt(); 52 m1=input.nextInt(); 53 d1=input.nextInt(); 54 y2=input.nextInt(); 55 m2=input.nextInt(); 56 d2=input.nextInt(); //两个日期分别的年月日 57 Date1 date1=new Date1(y1,m1,d1); //题目要求输入年月日作为构造时的参数 58 Date1 date2=new Date1(y2,m2,d2); 59 if(date1.equals(date2)){ //判断是否相等 60 System.out.println("两个日期相等"); 61 } 62 else 63 System.out.println("两个日期不相等"); 64 System.out.println("相差天数:"+date1.compareTo(date2)); //判断相差天数 65 } 66 }