Question

I have date time in character pointer -

char *connectTime = "2013-10-19 01:10:00";

then I fetched current time that'll be disconnect time.

time_t disconnectTime;
disconnectTime = time(NULL);

Now, I want to subtract connectTime from disconnectTime. I googled but couldn't implement it. Please help.

Was it helpful?

Solution

You can use strptime() to convert connectTime to a struct tm and then use mktime() on the latter to convert the it to a time_t.

char * connectTime = "2013-10-19 01:10:00";
struct tm tmConnect = {0};
time_t timeConnect;
char * pc = strptime(connectTime, "%Y-%m-%d %H:%M:%S", &tmConnect);
if ((NULL == pc) || ('\0' != *(pc + strlen(connectTime))) /* The second condition assume connectTime does not hold any more characters after "... 01:10:00". */
{
  perror("strptime() failed");
  /* handle error */
}
else
{
  timeConnect = mktime(&tmConnect);
}

To then calculate the difference in seconds use difftime(), as mentioned by in Grijesh Chauhan's comment:

time_t disconnectTime;
disconnectTime = time(NULL);
double diff = difftime(disconnectTime, timeConnect);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top