【发布时间】:2013-02-28 01:22:10
【问题描述】:
我希望以下方法可以返回当前日期中未来特定时间之前剩余的秒数。例如,如果当前时间是“19:00”,GetRemainedSeconds("19:01") 应该返回 60,表示在给定时间之前还有 60 秒。调用 GetRemainedSeconds("18:59") 应该返回 -60。问题是以下函数显示随机行为。有时它会返回正确的值,有时则不会(即使在同一台机器上运行)。这段代码有什么问题?
int GetRemainedSeconds ( const std::string &timeString, bool &isValid )
{
struct tm when;
char* p;
p = strptime ( timeString.c_str(), "%H:%M", &when );
if ( p == NULL || *p != '\0' )
{
std::cout << "Invalid 24h time format" << std::endl;
isValid = false;
return 0;
}
struct tm now;
isValid = true;
time_t nowEpoch = time ( 0 ); // current epoch time
struct tm tmpTime;
now = *localtime_r ( &nowEpoch, &tmpTime );
when.tm_year = now.tm_year;
when.tm_mon = now.tm_mon;
when.tm_mday = now.tm_mday;
when.tm_zone = now.tm_zone;
when.tm_isdst = now.tm_isdst;
time_t whenEpoch = mktime ( &when );
return ( whenEpoch - nowEpoch );
}
【问题讨论】: