如何获得指定时间之前的剩余秒数

How to get the remained seconds until a specified time

本文关键字:余秒数 何获得 定时间      更新时间:2023-10-16

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