请教高手:怎样计算char之间的时间差?

ghostxinghe 2005-08-18 11:11:34
怎样计算两个char的时间差(单位秒)
举例:char string1[20]="2005-08-15 12:00:00";
char string2[20]="2005-08-15 13:34:23";
strcpy(string1,"2005-08-15 12:00:00");
strcpy(string2,"2006-03-07 13:12:34");

请问怎样计算string2与string1的时间差(秒)
...全文
157 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
chillming 2005-10-25
  • 打赏
  • 举报
回复
include <stdio.h>
#include <time.h>
#include <string.h>

int main(void)
{
time_t t1,t2;
double result;
struct tm tm;
char date[20],time[20];

char string1[20]="2005-08-15 12:00:00";
char string2[20]="2005-08-15 12:00:30";

sscanf(string1,"%s %s",date,time);
sscanf(date"%d-%d-%d",&(tm.tm_year), &(tm.tm_mon),&(tm.tm_mday));
sscanf(date"%d:%d:%d",&(tm.tm_hour), &(tm.tm_min),&(tm.tm_sec));
t1 = mktime(&tm);


sscanf(string2,"%s %s",date,time);
sscanf(date"%d-%d-%d",&(tm.tm_year), &(tm.tm_mon),&(tm.tm_mday));
sscanf(date"%d:%d:%d",&(tm.tm_hour), &(tm.tm_min),&(tm.tm_sec));
t2 = mktime(&tm);

result =difftime(t2,t1);
printf("%f\n",result);

return 0;

}
chillming 2005-10-25
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <time.h>
#include <string.h>

int main(void)
{
time_t t1,t2;
double result;
struct tm tm;
char date[20],time[20];

char string1[20]="2005-08-15 12:00:00";
char string2[20]="2005-08-15 12:00:30";

sscanf(string1,"%s %s",date,time);
sscanf(date"%d-%d-%d",tm.tm_year, tm.tm_mon,tm.tm_mday);
sscanf(date"%d:%d:%d",tm.tm_hour, tm.tm_min,tm.tm_sec);
t1 = mktime(&tm);


sscanf(string2,"%s %s",date,time);
sscanf(date"%d-%d-%d",tm.tm_year, tm.tm_mon,tm.tm_mday);
sscanf(date"%d:%d:%d",tm.tm_hour, tm.tm_min,tm.tm_sec);
t2 = mktime(&tm);

result =difftime(t2,t1);
printf("%f\n",result);

return 0;

}


你修改一下吧,我没有gcc过的
jixingzhong 2005-08-18
  • 打赏
  • 举报
回复
可能上面的的程序还有问题,不过基本的思路是有了 ...
jixingzhong 2005-08-18
  • 打赏
  • 举报
回复
或者直接来 :

char s[20];
while (string1[i++] != '\0' ) //因为是等厂的,所以这样也可以了
{
if (string1[i]>='0'&&string1[i]<='9') //是数字,就执行做差的运算 !
s[i]= string2[i]-string1[i];
else s[i] = string1[i];
}
jixingzhong 2005-08-18
  • 打赏
  • 举报
回复
转换成 time_t格式,
用 difftime() 就可以了 ...
darkstar21cn 2005-08-18
  • 打赏
  • 举报
回复
先转成struct tm,然后转成time_t,就可以直接减了,得到的就是你想要的结果。
bugebear3 2005-08-18
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <time.h>

int main(void)
{
size_t i,j;
double result;

char string1[20]="2005-08-15 12:00:00";
char string2[20]="2005-08-15 12:00:30";

i = (time_t)string1;
j = (time_t)string2;

result =difftime(j,i);
printf("%f\n",result);

return 0;
}

----------------------------------------------------------
但结果怎么总是-28?
ghostxinghe 2005-08-18
  • 打赏
  • 举报
回复
能请各位大师说的具体一些嘛?

先转成struct tm,然后转成time_t,就可以直接减了,得到的就是你想要的结果。
~~~~~~~~~~~~~具体怎么转换这两个类型?

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧