Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 "Month Date hh:mm:ss"?

I am writing program in C and C++ and the time is in displayable string format.

Example :

time1 = "Mar 21 11:51:20"
time2 = "Mar 21 10:20:05"

I want to compare time1 and tme2 and find out whether time2 is after time1 or not and I need output as true or false, like below:

 if time2 > time1 then 
       i need output as 1 
 or 
       0 or -1 anything

I used difftime(time2,time1) , but it returns the delta time diff between time1 and time2.
I want to check greater or not.

For any help, thanks in advance

like image 402
user2196448 Avatar asked Jan 14 '23 21:01

user2196448


2 Answers

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?

like image 176
Grijesh Chauhan Avatar answered Jan 16 '23 10:01

Grijesh Chauhan


Look at strptime()

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

like image 28
K Scott Piel Avatar answered Jan 16 '23 11:01

K Scott Piel