如何获得剩余的秒数,直到指定的时间
问题描述:
我期望以下方法返回到当前日期之后的特定时间内剩余的秒数。例如如果当前时间是“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);
}
答
您需要设置when.tm_sec
的东西(可能是零)。它包含了前一次调用发生的任何垃圾,这不是你想要的。
是的,你也应该设置when.tm_isdst
有意义的东西。
答
这里有一个问题:
when.tm_isdst = when.tm_isdst;
你设置when.tm_isdst
它本身,这只是一些初始化的垃圾。
我想你的意思是说:
when.tm_isdst = now.tm_isdst;
你是对的,这是一个错字。 – Meysam 2013-03-12 14:11:37