如果时间戳转换日期需要比较则采用函数:struct tm *localtime_r(const time_t *timep, struct tm *result);
和localtime函数的区别:localtime_r可重复调用,给用户的是一个临时结果buffer,const time_t *timep参数不同,返回结果也不同;localtime不管调用多少次,给用户的是一个static结果buffer,结果以最后一次调用为准;
例子:
void TestTimeFun_Localtime_r()
{
time_t tm1;
time(&tm1);//可以为任意时间戳
while(1)
{
time_t tm2;
tm2 = time(NULL);
struct tm tm1p, tm2p;
struct tm* tm1pp, *tm2pp;
tm1pp = &tm1p;
tm2pp = &tm2p;
localtime_r(&tm1, tm1pp);
localtime_r(&tm2, tm2pp);
std::cout<<"tm1 min:"<<tm1p.tm_min<<std::endl;
std::cout<<"tm2 min:"<<tm2p.tm_min<<std::endl;
sleep(60);
}
}
//结果:
//tm1 min:1
//tm2 min:1
//tm1 min:1
//tm2 min:2
//tm1 min:1
//tm2 min:3
void TestTimeFun_Localtime()
{
time_t tm1;
time(&tm1);
while(1)
{
time_t tm2;
tm2 = time(NULL);
struct tm* tm1pp, *tm2pp;
tm1pp = localtime(&tm1);
tm2pp = localtime(&tm2);//以最后一次为准,如果是传tm1为参,则输出始终为起始值
std::cout<<"tm1 min:"<<tm1pp->tm_min<<std::endl;
std::cout<<"tm2 min:"<<tm2pp->tm_min<<std::endl;
sleep(60);
}
}
//结果:
//tm1 min:1
//tm2 min:1
//tm1 min:2
//tm2 min:2
//tm1 min:3
//tm2 min:3