📄 date.java
字号:
package myPackage;
import java.io.*;
public class Date {
private int year; // 年
private int month; // 月
private int day; // 日
private int amount ; // 用于 日期+整数
private int count; // 日期减日期得到的天数
public Date( ){ //定义缺省值的构造方法
setDate(2004,10,5);
}
//定义具有指定值的构造方法
public Date(int year,int month,int day){
setDate(year,month,day);
}
public void setDate(int year,int month,int day){ //用于设置年月日
this.year=year;
this.month=month;
this.day=day;
}
public int getYear( ){ //获取年
return year;
}
public int getMonth(){ //获取月
return month ;
}
public int getDay( ){ //获取日
return day ;
}
public void displayDate(){ // 输出年月日
System.out.println(year+"年"+month+"月"+day+"日");
}
public void DayOfMonth(int month,int year){ //判断某年某月的天数
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
amount=31;
if(month==4||month==6||month==9||month==11)
amount=30;
if(month==2)
{ if(year%4==0) //判断是否为闰年
{ if(year%100!=0)
amount=29;
else
{if(year%400==0)
amount=29;
else
amount=28;
}
}
else
amount=28;
}
}
public void Add (int days) { //在某个日期上加上一整数,计算其后的日期
while(days!=0){
DayOfMonth(month,year); // 将天数一天一天加到原日期里,
if(amount!=day) // 若满一个月则月份加一
day++; // 若满一年则年份加一
else
{ day=1; // 直到要加的整数减为零
if(month!=12)
month++;
else
{ month=1;
year++;
}
}
days--;
}
}
public void Sub(int a,int b,int c){ //计算两个日期相差的天数
int temp; //将a,b,c设置为较大的日期,以便于计算
if(a<year||(a==year&&b<month)||(a==year&&b==month&&c<day))
{ temp=a;a=year;year=temp;
temp=b;b=month;month=temp;
temp=c;c=day;day=temp;
}
System.out.print(year+"年"+month+"月"+day+"日与"+a+"年"+b+"月"+c+"日");
count=0;
while(a!=year||b!=month||c!=day) // 用较小的日期连续加一,直到两个日期相等
{ count++;
DayOfMonth(month,year); //它是加法的逆运算,算法一样,只是控制循环的条件不同
if(amount!=day)
day++;
else
{ day=1;
if(month!=12)
month++;
else
{ month=1;
year++;
}
}
}
System.out.println("相隔"+count+"天");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -