0

我正在尝试从 mysql 获取 %Y-%m-%d %H:%M:%S 格式的时间值并将其存储在 time_t 中。我为此使用了两个函数。

#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/* convert string time stamp format to time_t and return */
time_t timestamp_to_ctime(const char* time_stamp )
{
   time_t _return;
   struct tm tm_struct ; 
   strptime(time_stamp ,"%Y-%m-%d %H:%M:%S",&tm_struct);
   _return  = mktime(&tm_struct);   return
   _return;
}

/* convert time_t format into time-stamp format */ 
const char* ctime_to_timestamp(time_t time_t_input) 
{
   char* _return = (char*) malloc(MAX_TIME_STRING_LENGTH);
   struct tm* tm_struct ;   tm_struct = gmtime(&time_t_input);
   strftime( _return, MAX_TIME_STRING_LENGTH,"%Y-%m-%d %H:%M:%S",tm_struct);
   // free (tm_struct);
   return _return;  
}


#define TIME_STRING "2009-08-02 12:3:34"

int main(int argc,char** argv)
{
  time_t time_t_struct ;
  time_t_struct = timestamp_to_ctime(TIME_STRING);

  struct tm* ptr_tm ;
  ptr_tm = gmtime(&time_t_struct);

  printf( "Parsed time is : %d-%d-%d %d:%d:%d" , ptr_tm->tm_year+1900,\
        ptr_tm->tm_mon+1 ,  ptr_tm->tm_mday,ptr_tm->tm_hour,\
        ptr_tm->tm_min,ptr_tm->tm_sec);


  // check the next function //
  const char * timestamp_string = ctime_to_timestamp(time_t_struct);
  printf("Converted time is: %s ", timestamp_string);
  return 0;  
}

但在我看来,它没有正确解析分钟和小时。这是一个可能的错误还是我错过了什么。

这是输出。

Parsed time is : 2009-8-2 6:33:34Converted time is: 2009-08-02 06:33:34
4

0 回答 0