Find the difference between two dates in hours?

前端 未结 3 584
长情又很酷
长情又很酷 2021-01-28 13:55

For example I can calculate the difference of these two dates by looking at them but i have no clue when it comes to calculating this in a program.

Dates: A is 201

3条回答
  •  北海茫月
    2021-01-28 14:48

    I assume your stores time as strings: as "2014/02/12 13:26:33"

    To calculate time difference you need to use: double difftime( time_t time_end, time_t time_beg);

    the function difftime() computes difference between two calendar times as time_t objects (time_end - time_beg) in seconds. If time_end refers to time point before time_beg then the result is negative. Now the problem is difftime() doesn't accepts strings. We can convert string into time_t structure defined in time.h in two steps as I also described in my answer: How to compare two time stamp in format “Month Date hh:mm:ss”:

    1. Use char *strptime(const char *buf, const char *format, struct tm *tm); to convert char* time string into struct tm.

      The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. To use it you have to using format string specified in documentation:

      For your time format I am explaining format strings:

      1. %Y: 4-digit year. Can be negative.
      2. %m: Month [1-12]
      3. %d: Day of the month [1–31]
      4. %T: 24 hour time format with seconds, same as %H:%M:%S (you can also use %H:%M:%S explicitly)

      So function call will be as follows:

      //          Y   M  D  H  M  S 
      strptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi) 
      

      Where tmi is a struct tm structure.

    2. Step two would be to use: time_t mktime(struct tm *time);

    Below is the code I have written(read comments):

    #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;
    }
    

    Compile and run:

    $ gcc -Wall  time_diff.c 
    $ ./a.out 
    46.142500
    

提交回复
热议问题