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