我希望以下方法可以返回在当天的某个特定时间之前剩余的秒数。例如,如果当前时间是“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 );
}