2016-12-14 35 views
1

如何計算兩個日期之間的日期。日期ar保存在整數變量(數組)中。如果有一些功能會很好。如果否,我嘗試使用for循環,但沒有找到正確的算法。C++中兩個日期的區別

#include <iostream> 

int stoi(std::string s); 
int main(){ 
    /* 5th november of 2013 */ 
    int days1[0] = 05; 
    int days1[1] = 11; 
    int days1[2] = 2013; 
    /* 7th october of 2016 */ 
    int days2[0] = 07; 
    int days2[1] = 10; 
    int days2[2] = 2016; 
    int days = date(days1,days2); 
    std::cout << days << std::endl; 
    return 0; 
} 
int date(int dates1[], int date2[]){ 
    int days = 0; 
    /* Task: how much days is past */ 
    /* Days in each month must be real (31 or 30 or 29/28) */ 
    /* there can't be constant as 31 days on each month or 365 days in year */ 
    return days; 
} 
+0

計算時間,因爲例如起始日期以秒爲01.01.1970到當前的日期。用這兩個日期做這個。然後減去兩者,然後計算結果爲分鐘/小時/天或月份。 – user743414

+0

你可以使用std :: chrono :: duration –

+0

使用Boost。它有一個日期時間處理模塊。 –

回答

0
#include <iostream> 
#include <ctime> 
#include <cmath> 


auto date(int date1[], int date2[]){ 
    std::tm dur[2] {{0,0,0,date1[0],date1[1]-1,date1[2]-1900},{0,0,0,date2[0],date2[1]-1,date2[2]-1900}}; 
    std::time_t t1 {std::mktime(dur)}, t2 {std::mktime(dur+1)}; 
    if (t1 != (std::time_t)(-1) && t2 != (std::time_t)(-1)){ 
     return std::difftime(t2, t1)/(60 * 60 * 24); 
    }else{ 
     return (double)INFINITY; 
    //alternative: throw exception 
    } 
} 
int main(){ 
    /* 5th november of 2013 */ 
    int days1[] = {5,11,2013}; 
    /* 7th october of 2016 */ 
    int days2[] = {7,10,2016}; 
    auto days = date(days1,days2); 
    if(std::isinf(days)){ 
     std::cout << "cannot convert to time_t" << std::endl; 
    }else{ 
     std::cout << days << std::endl; 
    } 
    return 0; 
} 

這應該打印1067