次のメソッドが、現在の日付内の将来の特定の時刻までの残りの秒数を返すことを期待しています。たとえば、現在の時刻が「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 );
}