package chapter04.myapp;
import java.sql.Date;
public class BirthDate {
private int year;
private int month;
private int day;
String date;
/**
* 必须合法日期才能一起赋值
* @param year
* @param month
* @param day
*/
public BirthDate(int year,int month,int day){
if(month >=1 && month <= 12 &&day >= 1 &&day <= getLastDay(year,month) && year!=0){
this.year = year;
this.month = month;
this.day = day;
}
}
/**
* 判断传入年份是否闰年
* @param year
* @return
*/
private boolean isLeap(int year){
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return true;
return false;
}
/**
* 返回某个年某个月的最后一天
*/
private int getLastDay(int year,int month){
int LastDay = 30;
if(month == 1||month == 3||month == 5||month == 7||month == 8||month == 10||month == 12){
LastDay = 31;
}else if ( month == 2){
if (isLeap(year))
LastDay = 29;
else
LastDay = 28;
}
return LastDay;
}
/**
* 返回当前年月日
* 当前日期不合法,直接返回null
*/
public String getDate(){
if(month >=1 && month <= 12 &&day >= 1 &&day <= getLastDay(year,month)&& year!=0 ){
date = "当前:"+ year + "-" + month + "-" + day;
return date;
}
return null;
}
/**
* 返回当前日期下一天
* @return
*/
public String getNextDate(){
if(getDate() == null){
return null;
}
if (day == getLastDay(year,month)&&month == 12){
int year1 = year + 1;
if (year1 == 0){
year1 = 1;
}
String date = "下一天:"+ year1 + "-" + 1 + "-" + 1;
return date;
}else if(day == getLastDay(year,month)&&month != 12){
int month1 = month +1;
date = "下一天:"+year + "-" + month1 + "-" + 1;
return date;
}
else{
int day1 = day + 1;
date = "下一天:"+year + "-" + month + "-" + day1;
return date;
}
}
/**
* 返回当前日期上一天
* @return
*/
public String getPrevDate(){
if(getDate() == null){
return null;
}
if(year == 1&& month == 1&&day ==1){
this.day = 31;
this.month = 12;
this.year = -1;
date = "上一天:"+year + "-" + month + "-" + day;
return date;
}else if(month == 1&& day == 1){
year -=1;
month = 12;
day = 31;
date = "上一天:"+year + "-" + month + "-" + day;
return date;
}else if(day !=1){
day -=1;
date = "上一天:"+ year + "-" + month + "-" + day;
return date;
}else {
month = month -1;
day = getLastDay(year,month);
date = "上一天:"+ year + "-" + month + "-" + day;
return date;
}
}
}
日期类 java
最新推荐文章于 2024-11-03 11:01:20 发布