【问题标题】:Find the difference between two dates in hours?以小时为单位找出两个日期之间的差异?
【发布时间】:2014-02-18 18:53:02
【问题描述】:

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

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

【问题讨论】:

标签: c


【解决方案1】:

我假设你的存储时间是字符串:"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 结构中的值,使用 format 指定的格式。要使用它,您必须使用文档中指定的格式字符串:

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

    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);

下面是我写的代码(读cmets):

#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

【讨论】:

    【解决方案2】:

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

    double difftime(time_t time1, time_t time0);
    

    【讨论】:

      【解决方案3】:

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

      mktime() 应该可以完成工作,如果我没记错的话

      HTH

      【讨论】:

        猜你喜欢
        • 2012-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 2017-06-24
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        相关资源
        最近更新 更多