How to compare two time stamp in format “Month Date hh:mm:ss” to check +ve or -ve value

后端 未结 3 1112
半阙折子戏
半阙折子戏 2020-11-30 14:20

I checked the stackoverflow site for my answer, i did not get, so i am posting it here.

My problem is:

How to compare two time stamp in format

相关标签:
3条回答
  • 2020-11-30 15:02

    FIRST- use difftime to compare:

    you can simply use difftime() function to compare time and return 1 or -1 as follows:

    int comparetime(time_t time1,time_t time2){
     return difftime(time1,time2) > 0.0 ? 1 : -1; 
    } 
    

    SECOND- Convert string into time:

    If you have difficulty to convert string into time_t struct, you can use two functions in sequence:

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

      Example: to convert date-time string "Mar 21 11:51:20 AM" into struct tm you need three formate strings:

      %b : Month name, can be either the full name or an abbreviation
      %d : Day of the month [1–31].
      %r : Time in AM/PM format of the locale. If not available in the locale time format, defaults to the POSIX time AM/PM format: %I:%M:%S %p.

    2. time_t mktime (struct tm * timeptr); function to convert struct tm* to time_t

    Below Is my example program:

    #include <stdio.h>
    #include <time.h>
    int main(void){
        time_t t1, t2;
        struct tm *timeptr,tm1, tm2;
        char* time1 = "Mar 21 11:51:20 AM";
        char* time2 = "Mar 21 10:20:05 AM";
    
        //(1) convert `String to tm`:  
        if(strptime(time1, "%b %d %r",&tm1) == NULL)
                printf("\nstrptime failed\n");          
        if(strptime(time2, "%b %d %r",&tm2) == NULL)
                printf("\nstrptime failed\n");
    
        //(2)   convert `tm to time_t`:    
        t1 = mktime(&tm1);
        t2 = mktime(&tm2);  
    
         printf("\n t1 > t2 : %d", comparetime(t1, t2));
         printf("\n t2 > t1 : %d", comparetime(t2, t1));
         printf("\n");
         return 1;
    }
    

    And it works as you desire:

     $ ./a.out 
     t1 > t2 : 1
     t2 > t1 : -1
    

    To calculate difference between two dates read: How do you find the difference between two dates in hours, in C?

    0 讨论(0)
  • 2020-11-30 15:10

    Here is a very easy way solution to solve your problem. If in your case the comparing depends on the time. If so, you can turn your time variables into string so you can compare them as a string. ONLY if the base of the comparison is the hour and minute and second elements and/or the day. It will look like this:

    string time1 = "Mar 21 11:51:20";
    string time2 = "Mar 21 10:20:05";
    
    cout<<time1<< endl;
    cout<<time2<< endl;
    cout<<endl;
    
    if(time1>time2)cout<<time1<< endl;
    else cout << time2 << endl;
    
    0 讨论(0)
  • 2020-11-30 15:26

    Look at strptime()

    It converts an ASCII string formatted date/time into a struct tm

    0 讨论(0)
提交回复
热议问题