【问题标题】:How to get the remained seconds until a specified time如何获得指定时间之前的剩余秒数
【发布时间】: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 );
}

【问题讨论】:

    标签: c++ datetime epoch


    【解决方案1】:

    这里有一个问题:

    when.tm_isdst = when.tm_isdst;
    

    您将when.tm_isdst 设置为自身,这只是一些未初始化的垃圾。

    我想你的意思是:

    when.tm_isdst = now.tm_isdst;
    

    【讨论】:

      【解决方案2】:

      您需要将when.tm_sec 设置为某个值(可能为零)。它包含上一次调用的堆栈中碰巧出现的任何垃圾,这不是您想要的。

      是的,您还应该将when.tm_isdst 设置为有意义的值。

      【讨论】:

        猜你喜欢
        • 2018-05-01
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多