• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 898
  • Last Modified:

C++ compare timestamp in string format

I have a string in this format YYYYMMDDhhmmss, how to compare this string with current time in C++?
  • 3
1 Solution
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";


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.
Sorry, it is possible to determine whether it is DST or not, but the means are a bit over the top.
Oh, another side note, if you use a 'std::string' instead, the 'compare()' member will return the same results as 'strcmp()'
ltswimmerAuthor 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)));
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now