在c ++中添加日期到日期

时间:2011-11-08 14:24:20

标签: c++ date

我是c ++的新手,所以我想知道是否有一些库可以帮助更好地处理日期。

我有一个相当简单的任务。我有一个不同值的开始日期,我必须得到当我将日期增加一个随机天数时的日期。

我认为mktimetime_t个对象接缝对我要做的事情很有帮助。如果他们是答案,有人可以给我一个好导游的链接吗?

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

一天通常是86400秒(leap seconds除外)。您可以将其添加到time_t并获取新的time_t等。然后您可以使用mktime& localtime将其转换为可struct tm显示的strftime,可以使用strptime进行解析

答案 2 :(得分:1)

嗯,有Boost Date and time module。如果您的编译器足够新,那么就有C ++ 11 chrono命名空间。

答案 3 :(得分:1)

我刚编写了自己的函数,将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;
}

}