找出两个小时之间的差异小时数?

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

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

您可以使用difftime()来计算C两次之间的差异。 但是它使用mktimetm

 double difftime(time_t time1, time_t time0); 

一个简单的(不谈时区)方法是将自1970年1月1日以来的两个日期(日期时间)转换为数据。 建立差异和(tada)的差距为3600

如果我记得正确,mktime()应该做的工作

HTH

我假设您的商店时间为字符串: "2014/02/12 13:26:33"

要计算你需要使用的double difftime( time_t time_end, time_t time_beg);double difftime( time_t time_end, time_t time_beg);

函数difftime()计算两个日历时间之间的差异作为time_t对象( time_end - time_beg ),以秒为单位。 如果time_end指的是time_end之前的时间点,则结果为负。 现在的问题是difftime()不接受字符串。 我们可以在两个步骤中将字符串转换为time.h中定义的time_t结构,正如我在答案中所描述的: 如何比较格式为“Month Date hh:mm:ss”的两个时间戳 :

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

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

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

    1. %Y:4位数年份。 可以是消极的。
    2. %m:月[1-12]
    3. %d:每月的某一天[1-31]
    4. %T:24小时时间格式(秒),与%H相同:%M:%S(您还可以使用%H:%M:%S显式)

    所以函数调用如下:

     // YMDHMS 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  #include  #include  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