計算兩個日期之間的天數差C++/java
阿新 • • 發佈:2017-08-17
new abs ear == 關於 ostream logs col 多少
1--Java
分析:調用java中Calendar類
int days(Date date1,Date date2){ Calendar cal = new Calendar.getInstance(); cal.setTime(date1); int time1 = cal.get(Calendar.DAY_OF_YEAR); cal.setTime(date2); int time2 = cal.get(Calendar.DAY_OF_YEAR); //long days = Math.abs(time1-time2)/(24*3600*1000); return Math.abs(day1-day2); }
2--java
int days(Date date1,Date date2){ long time1 = Math.abs(date1.getTime()-date2.getTime()); return (int)time1/(24*3600*1000); }
分析:首先要知道關於閏年的概念,每四年一潤,四百年潤,且不能被100整除。因為,閏年二月有29天,全年共計366天。
偽代碼:首先將日期字符串的年,月,日分開,類型為yyyy-mm-dd,得到兩個日期,year1,month1,day1,year2,month2,day2
如果年份,月份相同:
return day1-day2;(大減小)
如果年份相同,月份不同:
計算date1,該年過了多少天D1;date2,該年過了多少天D2
return D1-D2;
如果,年份不同:
D1=date1 是該年的第多少天
D2=date2距離該年該年結束還有多少天
D3=兩個年份之間相差的整年數是多少天
return D1+D2+D
#include <iostream> using namespace std; public bool stringToDate(string date,int &year,int &month,int&day){ year = atoi(date.substr(0,4).c_str()); month=atio(date.substr(5,2).c_str()); day=atio(date.substr(8,2).c_str()); Day[12]={31,29,31,30,31,30,31,31,30,31,30,31}; if(isLear(year)) Day[1]=29; return year>0&&month>0&&month<=12&&day<=Day[month-1]; } public bool isLeap(int year){ return ((year%4==0)||(year%400==0))&&(year&100!=0); } public int daysInYear(int year,int month ,int day){ int days = day; int Day[12]={31,28,31,30,31,30,31,31,30,31,30,31}; if(isLeap(year)) Day[1]=29; for(int i=0;i<month-1;i++){ days+=Day[i]; } return days; } public between_days(string date1,string date2){ if(stringToDate(date1,int &year1,int &month1,int &day1)&&stringToDate(string date2,int &year2,int &month2,int &day2)){ if(year1==year2&&month1==month2){ return day1>day2?day1-day2:day2-day1; } else if(year1==year2){ int d1 = daysInYear(year1,month1,day1); int d2 = daysInYear(year2,month2,day2); return d1>d2?d1-d2:d2-d1; } else{ if(year1<year2){ swap(year1,year2); swap(month1,month2); swap(day1,day2); } int D1=0; for(int j=year2+1;j<year1;j++){ if(isLeap(j)) D1+=366; else D1+=365; } int D2=daysInYear(year1,month1,day1); if(isLeap(year2)) D2=D2+366-daysInYear(year2,month2,day2); else D2=D2+365-daysInYear(year2,month2,day2); return D1+D2; } } }
計算兩個日期之間的天數差C++/java