找出两个日期之间的小时差?

use*_*783 1 c

例如,我可以通过查看这两个日期来计算它们的差异,但在程序中计算时我不知道。

日期:A2014/02/12(y/m/d) 13:26:33和 B2014/02/14(y/m/d) 11:35:06则相差 46 个小时。

Gri*_*han 6

我假设你将时间存储为字符串:as"2014/02/12 13:26:33"

\n\n

要计算时差,您需要使用:double difftime( time_t time_end, time_t time_beg);

\n\n

该函数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\x9dtime.h

\n\n
    \n
  1. 用于char *strptime(const char *buf, const char *format, struct tm *tm);char*时间字符串转换为struct tm.

    \n\n
    \n

    strptime()函数使用 format 指定的格式将 buf 指向的字符串转换为存储在 tm 指向的 tm 结构中的值。要使用它,您必须使用文档中指定的格式字符串:

    \n
    \n\n

    对于您的时间格式,我正在解释格式字符串:

    \n\n
      \n
    1. %Y:4 位数年份。可以为负数。
    2. \n
    3. %m:月份 [1-12]
    4. \n
    5. %d:一个月中的第几天 [1\xe2\x80\x9331]
    6. \n
    7. %T:带秒的 24 小时时间格式,与 %H:%M:%S 相同(您也可以显式使用 %H:%M:%S)
    8. \n
    \n\n

    所以函数调用如下:

    \n\n
    //          Y   M  D  H  M  S \nstrptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi) \n
    Run Code Online (Sandbox Code Playgroud)\n\n

    哪里tmistruct tm结构。

  2. \n
  3. 第二步是使用:time_t mktime(struct tm *time);

  4. \n
\n\n

下面是我写的代码(阅读评论):

\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}\n
Run Code Online (Sandbox Code Playgroud)\n\n

编译并运行:

\n\n
$ gcc -Wall  time_diff.c \n$ ./a.out \n46.142500\n
Run Code Online (Sandbox Code Playgroud)\n