📄 ndate.java
字号:
/**
* <p> 类:NDate 定义一个日期类 </p>
* @author 肖磊
* @version 1.0
* <p> 该类定义的对象只接收1年1月1日~9999年12月31日之间的日期 </p>
*/
public class NDate
{
// 以下是日期类域的定义--------------------------------------------
private int year;
private int month;
private int day;
// 以下为构造方法的定义--------------------------------------------
public NDate()
{
year = 1900; month = 1; day = 1;
}
public NDate(int year,int month,int day)
{
setYear(year);
setMonth(month);
setDay(day);
}
// 以下为设置和读取域的方法----------------------------------------
public void setYear(int y)
{
if(y>=1 && y<=9999)
year = y;
else
year = 1900;
}
public int getYear()
{
return year;
}
public void setMonth(int m)
{
if(m>=1 && m<=12)
month = m;
else
month = 1;
}
public int getMonth()
{
return month;
}
public void setDay(int d)
{
if(d>=1 && d<=daysOfMonth())
day = d;
else
day = 1;
}
public int getDay()
{
return day;
}
// 以下为实现日期运算的方法定义 -----------------------------------
public boolean isLeapYear() // 判断当前日期所在年是否为闰年
{
return ((year%4==0)&&(year%100!=0))||(year%400==0);
}
public int daysOfMonth() // 获取当前日期所在月的天数
{
int d;
if(month==2)
{
if(isLeapYear()) d = 29;
else d = 28;
}
else
{
if((month<=7&&month%2==0)||(month>7&&month%2!=0))
d = 30;
else
d = 31;
}
return d;
}
public void inc() // 日期增加1天
{
day++;
if(day>daysOfMonth())
{
month++;
day = 1;
if(month>12)
{
year++;
month = 1;
}
}
}
public void dec() // 日期减少1天
{
day--;
if(day==0)
{
month--;
day = daysOfMonth();
if(month==0)
{
year--;
month = 12;
}
}
}
public int compareTo(NDate nd) // 比较两个日期大小,-1表示小于参数,0相等,1大于
{
int flag;
if(year > nd.year) flag = 1;
else if(year < nd.year) flag = -1;
else
{
if(month > nd.month) flag = 1;
else if(month < nd.month) flag = -1;
else
{
if(day > nd.day) flag = 1;
else if(day < nd.day) flag = -1;
else flag=0;
}
}
return flag;
}
public void change(int days) // 日期对象加上天数后的日期,days为负数表示减去天数
{
if(days>0)
for(int i=1;i<=days;i++) inc();
else
for(int i=1;i<=-1*days;i++) dec();
}
public int subtract(NDate nd) // 日期对象减去另一日期对象
{
int dist=0;
NDate t = new NDate(nd.year,nd.month,nd.day);
if(compareTo(t) > 0)
while(compareTo(t)!=0) { t.inc(); dist++; }
else if(compareTo(t) < 0)
while(compareTo(t)!=0) { t.dec(); dist--; }
return dist;
}
// 以下为转换为字符串方法------------------------------------------
public String toString()
{
return year+"-"+month+"-"+day;
}
}
// 下面是NDate类的测试类 --------------------------------------------
class NDateTester
{
public static void main(String args[])
{
NDate nd1 = new NDate(2000,1,1);
NDate nd2 = new NDate(2001,1,1);
System.out.println("nd1="+nd1);
System.out.println("nd1.leap="+nd1.isLeapYear());
System.out.println("nd1.days="+nd1.daysOfMonth());
System.out.println("nd2.days="+nd2.daysOfMonth());
System.out.println("nd1==nd2 ="+nd1.compareTo(nd2));
System.out.println("nd1 - nd2="+nd1.subtract(nd2));
nd1.change(5);
System.out.println("nd1+5="+nd1);
}
}
// 程序结束 ---------------------------------------------------------
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -