1

我在字符指针中有日期时间-

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

然后我获取了将断开连接时间的当前时间。

time_t disconnectTime;
disconnectTime = time(NULL);

现在,我想从 disconnectTime 中减去 connectTime。我用谷歌搜索但无法实施。请帮忙。

4

1 回答 1

3

您可以使用strptime()to 转换connectTime为 a struct tm,然后使用mktime()后者将它转换为 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);
}

然后计算使用秒数的差异difftime(),如Grijesh Chauhan的评论中所述:

time_t disconnectTime;
disconnectTime = time(NULL);
double diff = difftime(disconnectTime, timeConnect);
于 2013-10-19T11:26:51.220 回答