PDA

View Full Version : C convert date string to seconds


bog frog
02-07-2006, 09:22 PM
Hello, I'm trying to convert a date string to it's corresponding system time in seconds (in a long) but my calculation is about 18 hours off. I'm at a loss right now for what could be wrong - any help would be appreciated..

The input format is: YYYYMMDDHHMMSS

When I compare this value to my current time GetTime() function, they are about 18 hours when they should only be an hour at most.


long CMyApp::GetTime( CString sTime ) {

struct tm t;
time_t t_of_day;

static char time_buffer[10];
char *pEnd;

// populate tmobject from param
t.tm_year = atoi( sTime.Mid( 0, 4 ) ) - 1900;
t.tm_mon = atoi( sTime.Mid( 4, 2 ) ) - 1;
t.tm_mday = atoi( sTime.Mid( 6, 2 ) );
t.tm_hour = atoi( sTime.Mid( 8, 2 ) );
t.tm_min = atoi( sTime.Mid( 10, 2 ) );
t.tm_sec = atoi( sTime.Mid( 12, 2 ) );
t.tm_isdst = 0;

// convert to time_t
t_of_day = mktime(&t);

// needs time_t
sprintf( time_buffer, "ud", t_of_day ); // percent sign normally before ud, this board stripped it out

// return as long
return strtol( time_buffer, &pEnd, 0 );
}

long CMyApp::GetTime() {

static char time_buffer[10];
time_t now;
char *pEnd;

now = time ( NULL );
sprintf( time_buffer, "ud", now ); // percent sign normally before ud, this board stripped it out

return strtol( time_buffer, &pEnd, 0 );

}

bog frog
02-10-2006, 09:58 PM
I figured it out by piecing together some examples I found, hope it helps someone:


// accepts YYYYMMDDHHMMSS - doesn't need much validation in my app
// because it's not needed, even so it defaults
// to current if it is not correct length
long MyApp::GetTime( CString sTime ) {

// simple validation check, if it's not 14 in length
// then return the current time (we just accept it and
// process it)
if( sTime.GetLength() != 14 )
return GetTime();

static char time_buffer[10];
char *pEnd;

// convert CString to char*
char * data_char= new char[sTime.GetLength()+1];
strcpy(data_char, sTime);

time_t t_of_day;
struct tm aTime= {0};

// fill char*
sscanf(data_char, "%4d%2d%2d%2d%2d", &aTime.tm_year, &aTime.tm_mon, &aTime.tm_mday, &aTime.tm_hour, &aTime.tm_min, &aTime.tm_sec);

// fix up to struct tm base values:
aTime.tm_year -=1900;
aTime.tm_mon -= 1;

// adjust for 24 hour clock
if (aTime.tm_hour == 24)
{
aTime.tm_hour = 0;
}

// make time value
t_of_day = mktime(&aTime);

// convert time_t to char
sprintf( time_buffer, "%ud", t_of_day );

// dealloc
delete data_char;

// return timestamp in seconds as long value
return strtol( time_buffer, &pEnd, 0 );
}