关于日期的常用算法有很多,但如果掌握了基本的算法,难一点的可以分解为简单的,各个击破。
1)判断一年是否为闰年:
//判断一年是否为闰年
static boolean IsLeapYear(int year){
return (year % 400 == 0 || year % 4 == 0 && year % 100 != 0);
}
2)获得某一年的总天数:(闰年366天,非闰年355)
//获得某一年的总天数
static int GetAllDays(int year){
return (IsLeapYear(year)? 366: 365);
}
3)获得某年、某月的最大天数
//获得某年、某月的最大天数
static int GetMaxDay(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 (IsLeapYear(year)? 29: 28);
default:
return -1;
}
}
4)获得某年、某月、某日是这一年的第几天
//获得某年、某月、某日是这一年的第几天
static int GetDays(int year,int month,int day){
int sum = 0;
for(int i = 1; i < month ; i++){
sum += GetMaxDay(year,i);
}
return sum+day;
}
5)获得某年某月的下一天
//获得某年某月某日的下一天
static void GetNextDay(int year,int month,int day){
if(day != GetMaxDay(year,month)){
day++;
}else
{
if(month != 12)
{month++; day = 1;}
else
{year++; month = day =1;}
}
}
6)获得某年某日的前一天
//获得某年某月某日的前一天
static void GetPreDay(int year,int month,int day){
if(day != 1){
day--;
}else{
if(month != 1){
month--;
GetMaxDay(year,month);
}
else{
year--;month = 12;day = 31;
}
}
}
7)获得某年某月某日n天后的日期
//获得某年某月某日n天之后的日期
static void GetXDay(int year,int month,int day,int X){
for(int i = 1; i<= X; i++){
if(day != GetMaxDay(year,month)){
day++;
}else{
if(month != 12){
month++;day = 1;
}else{
year++;
month = day = 1;
}
}
}
System.out.println(X+" 天后是:"+year+"-"+month+"-"+day);
}
8)比较日期大小
//比较日期大小
static int CompareDay(int year1,int month1,int day1, int year2,int month2,int day2){
return year1 != year2? (year1-year2):(month1 != month2 ? (month1-month2): day1-day2);
}
9)求日期之差
//求日期之差
static int GetDateDiff1(int year1,int month1,int day1,int year2,int month2,int day2){
int sum = GetAllDays(year1) - GetDays(year1,month1,day1);
for(int i = year1+1; i < year2; i++ ){
sum += GetAllDays(i);
}
sum += GetDays(year2,month2,day2);
return sum;
}
static int GetDateDiff(int year1,int month1,int day1,int year2,int month2,int day2){
if(CompareDay(year1,month1,day1,year2,month2,day2) > 0){
return -GetDateDiff1(year2,month2,day2,year1,month1,day1);
}else if(CompareDay(year1,month1,day1,year2,month2,day2) < 0){
return GetDateDiff1(year1,month1,day1,year2,month2,day2);
}
return 0;
}