如何获得指定时间之前的剩余秒数
How to get the remained seconds until a specified time
我希望下面的方法返回当前天内某个特定时间之前的剩余秒数。例如,如果当前时间是"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 != ' ' )
{
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;
相关文章:
- 自一周开始以来的秒数?
- 你如何从霍华德·欣南特约会中获得秒数
- 如何从 boost::p osix_time::p time 获取秒数
- Qt 在可预测的秒数后跳过 UDP 数据包
- 提升::p osix_time::microsec_clock 以微秒分辨率将秒数提高一倍
- 无法将带有秒数的字符串转换为从epoch转换为date_time
- 如何直接从 FILETIME 结构获取/设置和获取秒数
- 打印时,继续为我创建的数组获得不同的输出
- 使用计时比较C++的持续时间/秒数并不像预期的那样工作
- 我如何计算到C++下周六的秒数
- 在特定秒数后停止循环的有效方法
- C :转换为int和添加时,我的角色数组获得了奇怪的值
- 如何使用 C 连续输出自计算开始以来的秒数
- 提升time_duration总秒数计算
- 计时计时器无法正确转换秒数
- LCD和RTC_DS1307-无法正确打印LCD上的1-9位秒数
- 计算C中NSDates之间的秒数
- 将自上周日午夜以来的秒数转换为日期和时间
- 提升日期时间转换和添加秒数
- 如何获得指定时间之前的剩余秒数