我在字符指针中有日期时间 -
char *connectTime = "2013-10-19 01:10:00";
然后我获取当前时间,这将是断开时间。
time_t disconnectTime;
disconnectTime = time(NULL);
现在,我想从disconnectTime中减去connectTime。我用Google搜索但无法实现它。 请帮忙。
答案 0 :(得分:3)
您可以使用strptime()
将connectTime
转换为struct tm
,然后对后者使用mktime()
将其转换为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);