#include <iostream>
#include <ctime>
#include <string>
#include <sstream>
#include <stdexcept>
// #include <sys/time.h>
// invariant: time_str contains today's local wall clock time in the form 'hh:mm:ss'
std::time_t str_to_time_t( const std::string& time_str )
{
constexpr char COLON = ':' ;
enum { UB_HR = 24, UB_MIN = 60, UB_SEC = 60 };
char delimiter ;
const std::time_t now = std::time(nullptr) ;
std::tm tm = *std::localtime( &now );
std::istringstream stm(time_str) ;
if( ( stm >> tm.tm_hour && tm.tm_hour >= 0 && tm.tm_hour < UB_HR ) &&
( stm >> delimiter && delimiter == COLON ) &&
( stm >> tm.tm_min && tm.tm_min >= 0 && tm.tm_min < UB_MIN ) &&
( stm >> delimiter && delimiter == COLON ) &&
( stm >> tm.tm_sec && tm.tm_sec >= 0 && tm.tm_sec < UB_SEC ) &&
( stm >> std::ws && stm.eof() ) )
{
return std::mktime(&tm) ;
}
else throw std::invalid_argument( "invalid time string" ) ;
}
int main() // minimal test driver
{
const std::string test[] = { "2:34:6", "19:74:55", "12x18y0", "23:59:59", "12:0:0" } ;
for( const std::string& s : test )
{
try
{
const std::time_t time_to_set = str_to_time_t(s) ;
const std::tm tm = *std::localtime( &time_to_set );
char cstr[128] ;
std::strftime( cstr, sizeof(cstr), "%A, %Y %B %d %H:%M:%S", &tm ) ;
std::cout << cstr << " (" << time_to_set << ")\n" ;
// const time_val tv { time_to_set, 0 } ;
// settimeofday( &t, nullptr ) ;
}
catch( const std::exception& )
{
std::cerr << "badly formed time string '" << s << "'\n" ;
}
}
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3RpbWU+CiNpbmNsdWRlIDxzdHJpbmc+CiNpbmNsdWRlIDxzc3RyZWFtPgojaW5jbHVkZSA8c3RkZXhjZXB0PgovLyAjaW5jbHVkZSA8c3lzL3RpbWUuaD4KCi8vIGludmFyaWFudDogdGltZV9zdHIgY29udGFpbnMgdG9kYXkncyBsb2NhbCB3YWxsIGNsb2NrIHRpbWUgaW4gdGhlIGZvcm0gJ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