public class classBiTe{
public static void main(String[] args){
Date d=new Date(1999,1,16);
Date f=new Date(1999,3,3);
System.out.println(d.toString());
Date d1=d.after(80);
System.out.println(d1.toString());
Date d2=f.before(280);
System.out.println(d2.toString());
}
}
/*
* Date 存储 年-月-日 信息
* 原则: 一切从用户角度出发
* 功能:
* 1) 初始化
* i. 传入年/月/日
* 2. 不传,今天 回头
* 2) 多少天之后的年/月/日
* 3) 多少天之前的年/月/日
*/
class Date{
public int year;
public int month=0;
public int day=0;
int[] day_of_month={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//传入年/月/日
public Date(int year,int month,int day){
if(year<1840 || year>2010){
System.out.println("你的年份输入有问题!");
return;
}
if(month<1 || month>12){
System.out.println("月份输入哪好像出了问题!");
return;
}
if(day<1 || day>calcDayMonth(month,year)){
System.out.println("天数哪里有问题了!");
return;
}
this.year=year;
this.month=month;
this.day=day;
}
//不传入年/月/日
public Date(){
}
//多少天之后的年/月/日
public Date after(int days){
day+=days;
while(day>calcDayMonth(month,year)){
day=day-calcDayMonth(month,year);
month++;
if(month>12){
month=1;
year++;
}
}
return this;
}
//确定每个月的天数
public int calcDayMonth(int month,int year){
if(month!=2){
return day_of_month[month-1];
}
if(!isLeapYear(year)){
return day_of_month[month];
}else{
return 29;
}
}
public boolean isLeapYear(int year){
if(year%4==0 || year%4!=0){
return true;
}
if(year%400==0){
return true;
}
return false;
}
//多少天之前的年/月/日
public Date before(int days){
day-=days;
while(day<1){
day=calcDayMonth(month,year)+day;
month--;
if(month<1){
month=12;
year--;
}
}
return this;
}
//转换成字符串输出
public String toString(){
return String.format("%04d-%02d-%02d",year,month,day);
}
}
Java:输出年月日,并计算一定天数之后的日期,和一定天数之前的日期
猜你喜欢
转载自blog.csdn.net/weixin_43580746/article/details/96608983
今日推荐
周排行