2011-11-08 69 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; 
} 

}