Search code examples
c++mktimetime.h

mktime returns same value every time


I'm trying to convert a time given in the format HHMMSS.SS,DD,MM,YYYY into unix time. The problem is that then calling mktime, the same time_t is returned.

ConvertTime(std::string input)
{
  std::vector<std::string> tokens;

  //splits input into tokens
  Tokenize(input, tokens);

  int hrs = atoi( tokens.at(0).substr(0,2).c_str() );
  int mins = atoi( tokens.at(0).substr(2,2).c_str() );
  int secs = atoi( tokens.at(0).substr(4,2).c_str() );
  int day = atoi( tokens.at(1).c_str() );
  int month = atoi( tokens.at(2).c_str() );
  int year = atoi( tokens.at(3).c_str() );

  struct tm tm = {0};
  time_t msgTime = 0;

  tm.tm_sec = secs;
  tm.tm_min = mins;
  tm.tm_hour = hrs;
  tm.tm_mday = day;
  tm.tm_mon = month-1;
  tm.tm_year = year-1900;
  tm.tm_isdst = -1;
  msgTime = mktime(&tm);
  printf("time: %f\n",msgTime);

}

Input ex:
154831.90,22,07,2016
154832.10,22,07,2016
154832.30,22,07,2016
154832.50,22,07,2016
154832.70,22,07,2016
154832.90,22,07,2016
154833.10,22,07,2016

Output ex:
1469202560.00
1469202560.00
1469202560.00
1469202560.00
1469202560.00
1469202560.00
1469202560.00

I feel like I'm not initialize something, or the values aren't being changed, but the tm struct shouldn't be carrying over between calls of ConvertTime, so I'm not sure what the issue is.


Solution

  • The issue here was in trying to use the time_t (msgTime) value as a double, without casting.

    The solution is to simply cast msgTime to a double like so:

    printf("time %f\n",(double)msgTime);
    

    This makes the function:

    ConvertTime(std::string input)
    {
      std::vector<std::string> tokens;
    
      //splits input into tokens
      Tokenize(input, tokens);
    
      int hrs = atoi( tokens.at(0).substr(0,2).c_str() );
      int mins = atoi( tokens.at(0).substr(2,2).c_str() );
      int secs = atoi( tokens.at(0).substr(4,2).c_str() );
      int day = atoi( tokens.at(1).c_str() );
      int month = atoi( tokens.at(2).c_str() );
      int year = atoi( tokens.at(3).c_str() );
    
      struct tm tm = {0};
      time_t msgTime = 0;
    
      tm.tm_sec = secs;
      tm.tm_min = mins;
      tm.tm_hour = hrs;
      tm.tm_mday = day;
      tm.tm_mon = month-1;
      tm.tm_year = year-1900;
      tm.tm_isdst = -1;
      msgTime = mktime(&tm);
      printf("time: %f\n",(double)msgTime);
    
    }
    
    Input ex:
    154831.90,22,07,2016
    154832.10,22,07,2016
    154832.30,22,07,2016
    154832.50,22,07,2016
    154832.70,22,07,2016
    154832.90,22,07,2016
    154833.10,22,07,2016
    
    Output ex:
    1469202511.00
    1469202512.00
    1469202512.00
    1469202512.00
    1469202512.00
    1469202512.00
    1469202513.00