Code Snippet

MSDN Channel 9 Video "Corrinne Yu: Principal Engine Architect, Halo Team Microsoft

视频

(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]


转载于:https://www.cnblogs.com/IS2120/p/6745665.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值