0

I'm trying to fetch time value in %Y-%m-%d %H:%M:%S format from mysql and store it in time_t. I'm using two functions for that.

#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;  
}

But it seems to me that it does not parse the minutes and hour correctly. Is this is a possible bug or am I missing something.

This is the output.

Parsed time is : 2009-8-2 6:33:34Converted time is: 2009-08-02 06:33:34
sandun dhammika
  • 881
  • 3
  • 12
  • 31
  • and I'd figured out that using localtime() instead of gmtime() would correct the second output. But first one is not fixed. – sandun dhammika May 19 '14 at 02:58
  • 1
    I believe `strftime` function is expecting minutes value of two digits for the `%M` format. I suspect if the minutes portion had a leading zero,( e.g. `:03:` instead of `:3:`), you'd get the expected value. – spencer7593 May 19 '14 at 03:13
  • 1
    @spencer7593: on Mac OS X 10.9.3, `strptime()` is OK with the missing leading zero. – Jonathan Leffler May 19 '14 at 03:39
  • I'd figured out the error. It when convert time into gm time and fetch into the tm structure. – sandun dhammika May 19 '14 at 03:53

0 Answers0