例如,我可以通过查看这两个日期来计算它们的差异,但在程序中计算时我不知道。
日期:A 是2014/02/12(y/m/d) 13:26:33
且 B 是2014/02/14(y/m/d) 11:35:06
那么小时差是 46。
我假设你将时间存储为字符串:as"2014/02/12 13:26:33"
要计算时差,您需要使用:double difftime( time_t time_end, time_t time_beg);
功能difftime()
将两个日历时间之间的差异计算为time_t
对象(time_end - time_beg
) 很快。如果time_end
指之前的时间点time_beg
那么结果是否定的。现在的问题是difftime()
不接受字符串。我们可以将字符串转换为time_t结构体定义于time.h正如我在回答中所描述的那样,分为两个步骤:如何比较“月日 hh:mm:ss”格式的两个时间戳:
-
Use char *strptime(const char *buf, const char *format, struct tm *tm);转换char*
时间串入struct tm.
The strptime()
函数使用 format 指定的格式将 buf 指向的字符串转换为存储在 tm 指向的 tm 结构中的值。要使用它,您必须使用文档中指定的格式字符串:
对于您的时间格式,我正在解释格式字符串:
- %Y:4 位数年份。可以为负数。
- %m:月份 [1-12]
- %d:一月中的某一天 [1–31]
- %T:带秒的 24 小时时间格式,与 %H:%M:%S 相同(您也可以显式使用 %H:%M:%S)
所以函数调用如下:
// Y M D H M S
strptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi)
Where tmi
is a struct tm
结构。
第二步是使用:time_t mktime(struct tm *time);
下面是我写的代码(阅读评论):
#define _GNU_SOURCE //to remove warning: implicit declaration of ‘strptime’
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
char* time1 = "2014/02/12 13:26:33"; // end
char* time2 = "2014/02/14 11:35:06"; // beg
struct tm tm1, tm2; // intermediate datastructes
time_t t1, t2; // used in difftime
//(1) convert `String to tm`: (note: %T same as %H:%M:%S)
if(strptime(time1, "%Y/%m/%d %T", &tm1) == NULL)
printf("\nstrptime failed-1\n");
if(strptime(time2, "%Y/%m/%d %T", &tm2) == NULL)
printf("\nstrptime failed-2\n");
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
t2 = mktime(&tm2);
//(3) Convert Seconds into hours
double hours = difftime(t2, t1)/60/60;
printf("%lf\n", hours);
// printf("%d\n", (int)hours); // to display 46
return EXIT_SUCCESS;
}
编译并运行:
$ gcc -Wall time_diff.c
$ ./a.out
46.142500
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)