例如,我可以通过查看这两个日期来计算它们的差异,但在程序中计算时我不知道。
日期:A2014/02/12(y/m/d) 13:26:33和 B2014/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定义的结构,正如我在回答中所述: How to Compare two time stamp in format \xe2\x80\x9cMonth Date hh:mm:ss\xe2\x80\x9d:time.h
用于char *strptime(const char *buf, const char *format, struct tm *tm); 将char*时间字符串转换为struct tm.
\n\n\n该
\nstrptime()函数使用 format 指定的格式将 buf 指向的字符串转换为存储在 tm 指向的 tm 结构中的值。要使用它,您必须使用文档中指定的格式字符串:
对于您的时间格式,我正在解释格式字符串:
\n\n所以函数调用如下:
\n\n// Y M D H M S \nstrptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi) \nRun Code Online (Sandbox Code Playgroud)\n\n哪里tmi有struct tm结构。
下面是我写的代码(阅读评论):
\n\n#define _GNU_SOURCE //to remove warning: implicit declaration of \xe2\x80\x98strptime\xe2\x80\x99\n#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\nint main(void){\n char* time1 = "2014/02/12 13:26:33"; // end\n char* time2 = "2014/02/14 11:35:06"; // beg\n struct tm tm1, tm2; // intermediate datastructes \n time_t t1, t2; // used in difftime\n\n //(1) convert `String to tm`: (note: %T same as %H:%M:%S) \n if(strptime(time1, "%Y/%m/%d %T", &tm1) == NULL)\n printf("\\nstrptime failed-1\\n"); \n if(strptime(time2, "%Y/%m/%d %T", &tm2) == NULL)\n printf("\\nstrptime failed-2\\n");\n\n //(2) convert `tm to time_t`: \n t1 = mktime(&tm1); \n t2 = mktime(&tm2); \n //(3) Convert Seconds into hours\n double hours = difftime(t2, t1)/60/60;\n printf("%lf\\n", hours);\n // printf("%d\\n", (int)hours); // to display 46 \n return EXIT_SUCCESS;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n编译并运行:
\n\n$ gcc -Wall time_diff.c \n$ ./a.out \n46.142500\nRun Code Online (Sandbox Code Playgroud)\n