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
Look at
strptime()
It converts an ASCII string formatted date/time into a
struct tm
FIRST- use difftime to compare:
you can simply use
difftime()
function to compare time and return1
or-1
as follows:SECOND- Convert string into time:
If you have difficulty to convert
string
intotime_t
struct, you can use two functions in sequence:char *strptime(const char *buf, const char *format, struct tm *tm);
function. to convert string intostruct tm
Example: to convert date-time string
"Mar 21 11:51:20 AM"
intostruct tm
you need three formate strings:time_t mktime (struct tm * timeptr);
function to convertstruct tm*
totime_t
Below Is my example program:
And it works as you desire:
To calculate difference between two dates read: How do you find the difference between two dates in hours, in C?
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: