首页 > 代码库 > 日期问题

日期问题

public class MyDate {
private int year,month,day;
private static int thisYear;
static
{ thisYear=2012;
}
public MyDate(int year,int month,int day)
{ this.set(year,month,day);
}

public MyDate()
{ this(1970,1,1);
}
public MyDate(MyDate d)
{ this.set(d);
}
public void set(int year, int month, int day)
{
this.year=year; //出s.year 指当前对象的成员变量, year 指參数
this.month=(month>=1&&month<=12) ? month:1;
this.day=(day>=1&&day<=31)?day:1; //this引用不能省略
}
public void set(MyDate d) //设置日期值, 重载
{ set(d.year,d.month,d.day); //调用同名成员方法,不能使用this0
}
public int getYear() //获得年份
{ return this.year;
}
public int getMonth()
{ return this.month; } //获得月份
public int getDay()
{ return this.day;} //获得当月日期
public String toString()
{ // return year+"年"十String.format("%02d",month)+"月"+ String.format("%02d",day)+"日";
return year+"年"+month+"月"+ day+"日";
}
public static int getThisYear() //获得今年年份,静态方法
{ return thisYear; //访间静态成员变量
}
public static boolean isLeapYear(int year) //判断指定年份是否为闰年, 静态方法
{ return year%400==0||year%100!=0 &&year%4==0;
}
public boolean isLeapYear() //判断当前日期的年份是否闰年, 重载
{ return isLeapYear(this.year); //调用静态方法
}
public boolean equlals(MyDate d) //比较当前日期值与 d是否相等(只是值相等)。
{
return this==d||d!=null&&this.year==d.year &&this.month==d.month &&this.day==d.day;
}
public static int daysOfMonth(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: return MyDate.isLeapYear(year) ?29 : 28;
default: return 0;
}
}
public int daysOfMonth()
{ return daysOfMonth(this.year,this.month);
}
public void tomorrow() //明天
{
this.day++;
if(this.day>this.daysOfMonth())
{ this.day=1;
this.month++;
if(this.month>12)
{ this.month=1;
this.year++;
}
}
}
public MyDate yestoday()//昨天
{
MyDate date=new MyDate(this);
date.day--;
if(date.day==0)
{ date.month--;
if(date.month==0)
{ date.month=12;
date.year--;
}
date.day=daysOfMonth(date.year,date.month);
}
return date;
}

public boolean before(MyDate d)            //boolean只有两种情况,0和1
{
return (d.year>this.year)||(d.year==this.year&&d.month>this.month)||(d.year==this.year&&d.month==this.month&&d.day>this.day)
}
}

class MyDate_ex
{
public static void main(String args[])
{
System.out.println("今年是"+MyDate.getThisYear()+",闰年?"+MyDate.isLeapYear(MyDate.getThisYear()));
MyDate d1=new MyDate(2012,12,31);
MyDate d2=new MyDate(d1);
System.out.println("d1:"+d1+",d2:"+d2+",d1==d2?"+(d1==d2)+",d1.equals(d2)?"+d1.equals(d2));
System.out.print(d1+"的明天是");
d1.tomorrow();
System.out.println(d1+"\n"+d1+"的昨天是"+(d2=d1.yestoday()));
// MyDate d3=new MyDate(2014,12,31);
System.out.println(",d2>d1?"+d1.before(d2));
System.out.println(d1);
System.out.println(d2);
}
}

日期问题