fork download
  1. #include <iostream>
  2. #include <ctime>
  3. #include <string>
  4. #include <sstream>
  5. #include <stdexcept>
  6. // #include <sys/time.h>
  7.  
  8. // invariant: time_str contains today's local wall clock time in the form 'hh:mm:ss'
  9. std::time_t str_to_time_t( const std::string& time_str )
  10. {
  11. constexpr char COLON = ':' ;
  12. enum { UB_HR = 24, UB_MIN = 60, UB_SEC = 60 };
  13.  
  14. char delimiter ;
  15. const std::time_t now = std::time(nullptr) ;
  16. std::tm tm = *std::localtime( &now );
  17.  
  18. std::istringstream stm(time_str) ;
  19. if( ( stm >> tm.tm_hour && tm.tm_hour >= 0 && tm.tm_hour < UB_HR ) &&
  20. ( stm >> delimiter && delimiter == COLON ) &&
  21. ( stm >> tm.tm_min && tm.tm_min >= 0 && tm.tm_min < UB_MIN ) &&
  22. ( stm >> delimiter && delimiter == COLON ) &&
  23. ( stm >> tm.tm_sec && tm.tm_sec >= 0 && tm.tm_sec < UB_SEC ) &&
  24. ( stm >> std::ws && stm.eof() ) )
  25. {
  26. return std::mktime(&tm) ;
  27. }
  28. else throw std::invalid_argument( "invalid time string" ) ;
  29. }
  30.  
  31. int main() // minimal test driver
  32. {
  33. const std::string test[] = { "2:34:6", "19:74:55", "12x18y0", "23:59:59", "12:0:0" } ;
  34. for( const std::string& s : test )
  35. {
  36. try
  37. {
  38. const std::time_t time_to_set = str_to_time_t(s) ;
  39. const std::tm tm = *std::localtime( &time_to_set );
  40. char cstr[128] ;
  41. std::strftime( cstr, sizeof(cstr), "%A, %Y %B %d %H:%M:%S", &tm ) ;
  42. std::cout << cstr << " (" << time_to_set << ")\n" ;
  43. // const time_val tv { time_to_set, 0 } ;
  44. // settimeofday( &t, nullptr ) ;
  45. }
  46. catch( const std::exception& )
  47. {
  48. std::cerr << "badly formed time string '" << s << "'\n" ;
  49. }
  50. }
  51. }
  52.  
Success #stdin #stdout #stderr 0s 3432KB
stdin
Standard input is empty
stdout
Sunday, 2013 September 15 02:34:06 (1379212446)
Sunday, 2013 September 15 23:59:59 (1379289599)
Sunday, 2013 September 15 12:00:00 (1379246400)
stderr
badly formed time string '19:74:55'
badly formed time string '12x18y0'