繁体   English   中英

找出两个日期之间的时差(以小时为单位)?

[英]Find the difference between two dates in hours?

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

日期:A是2014/02/12(y/m/d) 13:26:33而B是2014/02/14(y/m/d) 11:35:06则时差为46。

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

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

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

  1. 使用char *strptime(const char *buf, const char *format, struct tm *tm); char*时间字符串转换为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 <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

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

double difftime(time_t time1, time_t time0);

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

如果我正确记住,mktime()应该可以完成工作

高温超导

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM