Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compare to string dates

I need to compare 2 string dates to see if one date is later then another. The date format for both dates is at the bottom. i can rearrange this for what ever is easiest. I have boost but it doesn't have to be, ive been through so many examples and can't seem to wrap my brain around getting it to work. Thanks in advance basically i want

2012-12-06 14:28:51

if (date1 < date2) {
 // do this
}
else {
 // do that
}  
like image 355
user1054513 Avatar asked Jul 02 '26 02:07

user1054513


2 Answers

It looks like the date format your using is already in lexicographical order and a standard string comparison will work, something like:

std::string date1 = "2012-12-06 14:28:51";
std::string date2 = "2012-12-06 14:28:52";
if (date1 < date2) {
    // ...
}
else {
    // ...
}

You will need to make sure that spacing and punctuation is consistent when using this format, in particular something like 2012-12-06 9:28:51 will break the comparison. 2012-12-06 09:28:51 will work though.

like image 101
DRH Avatar answered Jul 04 '26 01:07

DRH


You're lucky - your dates are already in the proper format to do a standard string comparison and get the correct results. All the parts go from most significant to least significant, and you're using 24-hour times.

If these are std::strings you can use the < just as you have in your sample. If they're C-style character array strings, use strcmp.

like image 40
Mark Ransom Avatar answered Jul 04 '26 01:07

Mark Ransom