视频
(2010/3/11 修改成 youku)
c/c++求两个日期之间的间隔天数
/**
//z 2014-04-22 13:19:45 L.253 BG57IV3@XCL T1903383406.K.F253293061 [T269,L3801,R176,V5040]
参见msdn tm time_t
注意有效范围,里面的year不能太早,否则计算不准确
*/
int day_distance_1(const int year1,const int month1,const int day1,const int year2,const int month2,const int day2)
{
struct tm tm1;
tm1.tm_year = year1 - 1900;
tm1.tm_mon = month1 - 1;
tm1.tm_mday = day1;
tm1.tm_hour = 0;
tm1.tm_min = 0;
tm1.tm_sec = 0;
struct tm tm2;
tm2.tm_year = year2 - 1900;
tm2.tm_mon = month2 - 1;
tm2.tm_mday = day2;
tm2.tm_hour = 0;
tm2.tm_min = 0;
tm2.tm_sec = 0;
time_t time1;
time_t time2;
time1 = mktime(&tm1);
time2 = mktime(&tm2);
double diff = difftime(time1,time2);
return (int)(diff/(3600*24));
}
/**
这个方法的计算范围很大
*/
int day_distance_2(const int year1,const int month1,const int day1,const int year2,const int month2,const int day2)
{
int nd, nm, ny; //new_day, new_month, new_year
int od, om, oy; //old_day, oldmonth, old_year
nm = (month2 + 9) % 12;
ny = year2 - nm/10;
nd = 365*ny + ny/4 - ny/100 + ny/400 + (nm*306 + 5)/10 + (day2 - 1);
om = (month1 + 9) % 12;
oy = year1 - om/10;
od = 365*oy + oy/4 - oy/100 + oy/400 + (om*306 + 5)/10 + (day1 - 1);
return od - nd;
}
int main()
{
cout << day_distance_1(2012,1,14,2011,9,21) << endl;
cout << day_distance_2(2012,1,14,2011,9,21) << endl;
}
//z 2014-04-22 13:19:45 L.253 BG57IV3@XCL T1903383406.K.F253293061 [T269,L3801,R176,V5040]