Meysam
Meysam

Reputation: 18117

How to get the remained seconds until a specified time

I'd expect the following method to return the number of seconds remained until a specific time in future within the current day. e.g if current time is "19:00", GetRemainedSeconds("19:01") should return 60 indicating that 60 seconds is remained until the given time. Calling GetRemainedSeconds("18:59") should return -60. The problem is that the following function is showing random behavior. Sometimes it returns correct value, sometime it does not (even when run on the same machine). What's the problem with this code?

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 );
}

Upvotes: 0

Views: 829

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129314

You need to set when.tm_sec to something (probably zero). It contains whatever junk happens to be on the stack from the previous call, which is not what you want.

And yes, you also should set the when.tm_isdst to something meaningful.

Upvotes: 2

user2088639
user2088639

Reputation:

Here's one problem:

when.tm_isdst = when.tm_isdst;

You're setting when.tm_isdst to itself, which is just some uninitialized garbage.

I think you meant to say:

when.tm_isdst = now.tm_isdst;

Upvotes: 0

Related Questions