mktime每次都返回相同的值

时间:2016-07-27 20:23:03

标签: c++ mktime time.h

我正在尝试将格式为HHMMSS.SS,DD,MM,YYYY的时间转换为unix时间。问题是然后调用mktime,返回相同的time_t。

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

我觉得我没有初始化某些东西,或者值没有被改变,但是tm结构不应该在ConvertTime的调用之间进行,所以我不确定是什么问题。

1 个答案:

答案 0 :(得分:1)

这里的问题是尝试将time_t(msgTime)值用作double,而不进行强制转换。

解决方案是简单地将msgTime转换为double,如下所示:

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

这使得功能:

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