We help IT Professionals succeed at work.

C++ compare timestamp in string format

ltswimmer
ltswimmer asked
on
I have a string in this format YYYYMMDDhhmmss, how to compare this string with current time in C++?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2012
Commented:
Given that this very format allows numeric comparison (less, greater and equal all apply), you could simply format the current time as a string of the same format and use 'strcmp()' with its less, greater and equal return values, e.g.

char acCurTime[16];
char acOtherTime[16] = "YYYYMMDDhhmmss";

strftime(acCurTime,"%Y%m%d%H%M%S",localtime(time(NULL)));

int nRetVal = strcmp(acOtherTime,acCurTime);

Open in new window


Alternatively, you could parse the string into a 'struct tm' for comparison purposes, yet the caveat is that you cannot guarantee for some of the fields, i.e. 'tm_isdst' is indeterminable from such input data.
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
Sorry, it is possible to determine whether it is DST or not, but the means are a bit over the top.
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
Oh, another side note, if you use a 'std::string' instead, the 'compare()' member will return the same results as 'strcmp()'

Author

Commented:
Thanks to jkr for the simple solution.  I originally used difftime() for comparison which is more complex.

It works. You will need to add a parameter for strftime() because this function doesn't allow 3 parameters.

strftime(acCurTime,14, "%Y%m%d%H%M%S",localtime(time(NULL)));