關於日期的常用演算法有很多,但如果掌握了基本的演算法,難一點的可以分解為簡單的,各個擊破。
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;}
轉載請標明出處:http://blog.csdn.net/u012027907