2014-02-18 100 views
-2

例如我可以通过查看它们来计算这两个日期的差异,但是当涉及到在程序中计算这些时,我不知道。在几个小时内找出两个日期之间的差异?

日期:A是2014/02/12(y/m/d) 13:26:33和B是2014/02/14(y/m/d) 11:35:06然后以小时差为46

+1

是你得到这样的输入作为一个字符串? – Linuxios

+2

[你有什么尝试?](http://stackoverflow.com/help/mcve) –

+4

你检查过这个问题吗? http://stackoverflow.com/questions/13932909/difference-between-two-dates-in-c – stamanuel

回答

1

您可以使用difftime()C两个时间之间计算差。但它使用mktimetm

double difftime(time_t time1, time_t time0); 
0

一件容易的(更不用谈时区)的方法是,因为1/1/1970到两个日期(日期时间)转换为secounds。在建3600

mktime(差别和(田田)devide)应该做的工作,如果我remeber正确

HTH

0

我假设你的存储时间为字符串:为"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.h定义为我也在我的答案描述time_t结构:How to compare two time stamp in format “Month Date hh:mm:ss”

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

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

    您的时间格式我解释格式字符串:

    1. %Y:4位数的年份。可以是负面的。
    2. %M:月[1-12]
    3. %d:该月的天[1-31]
    4. %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) 
    

    tmistruct tm结构。

  2. 第二步是使用: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