2011-11-08 98 views
0

我是C++的新手,所以我想知道是否有一些庫可以幫助您更流利地處理日期。在C++中添加日期

我有一個相當簡單的任務。我有一個不同的值的開始日期,我必須得到什麼日期,當我增加日期隨機數天。

我想mktimetime_t對象接縫對我所要做的事有幫助。如果他們是答案可以有人給我一個良好的指導鏈接?

回答

1

一天通常是86400秒(leap seconds除外)。您可以添加到time_t,並得到一個新的time_t等等,那麼你可以使用mktime & localtime將其轉換爲struct tm這是顯示與strftime並且可能是可解析與strptime

0

我剛剛寫了我自己的函數,將Days,Months和Years添加到現有的DATE類中。我無法測試它,但也許它可以幫助:

bool DATE::add(int Day, int Month, int Year){ 
int DaysPerMonth[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 
this -> Day += Day; 
while(this -> Day > DaysPerMonth[ this-> Month ]){ 
    if((this -> Year % 4 == 0 && this -> Year % 100 != 0) || this -> Year % 400 == 0){ 
     DaysPerMonth[2] = 29; 
    } 
    this -> Day -= DaysPerMonth[ this-> Month ]; 
    this -> Month++; 
    if(this -> Month > 12){ 
     this -> Month = 1; 
     this -> Year++; 
    } 
} 
this -> Month = (this -> Month + (Month % 12)); 
this -> Year = (this -> Year + Year + (Month/12)); 
if((this -> Year % 4 == 0 && this -> Year % 100 != 0) || this -> Year % 400 == 0){ 
    DaysPerMonth[2] = 29; 
    // check pathologic case wether date is 1 of March and added Year targets switchyear 
    if(this -> Day == 1 && this -> Month == 3){    
     this -> Day = 29; 
     this -> Month = 2; 
    } 
} 
if(this -> Month < 1 || this -> Month > 12 || this -> Day < 1 || this -> Day > DaysPerMonth[this->Month]){ 
    valid = false; 
    cerr << "something went wrong, calculated Date is: " << this -> Day << "."<< this -> Month << "." << this -> Year << endl << flush; 
    return false; 
}else{ 
    return true; 
} 

}