I am making a project that has to keep track of dates associated with books. I store the dates as strings. I need to print out all books that were published after a given date.
Below is a loop similar to what I do in my code which replicates a problem of inconsistently comparing the value of two dates.
#include <time.h>
#include <stdio.h>
#include <string>
#include <ctime>
#include <vector>
int main()
{
std::string comp_against = "11/1995";
std::vector<std::string> dates = {"11/1995", "10/1990", "03/2004", "2/1992", "11/1995"};
for(auto it = dates.begin(); it != dates.end(); ++it)
{
std::string date = *it;
struct tm t1;
struct tm t2;
// parse the dates with mm/YYYY format
strptime(comp_against.c_str(), "%m/%Y", &t1);
strptime(date.c_str(), "%m/%Y", &t2);
std::time_t s1 = mktime(&t1);
std::time_t s2 = mktime(&t2);
printf("%s > %s: %s\n", date.c_str(), comp_against.c_str(), (s2 > s1 ? "true" : "false"));
}
return 0;
}
The output on my computer:
11/1995 > 11/1995: false <- these two are different
10/1990 > 11/1995: false |
03/2004 > 11/1995: true |
2/1992 > 11/1995: false |
11/1995 > 11/1995: true <- these two are different
When I run my actual code, the problem is reversed. When the date "11/1995" is compared against itself at the beginning of the loop on the first iteration, the s2>s1
evaluates to true
rather than false
like the output above and the second comparison evaluates to false
.
EDIT:
If I do the comparison with difftime, I get the same issue. Add printf("%s > %s: %s\n", date.c_str(), comp_against.c_str(), (difftime(s2, s1) > 0.0 ? "true" : "false"));
and printf("\n");
after the printf
in the code above and you get the below output.
11/1995 > 11/1995: false <- different
11/1995 > 11/1995: false |
10/1990 > 11/1995: false |
10/1990 > 11/1995: false |
03/2004 > 11/1995: true |
03/2004 > 11/1995: true |
2/1992 > 11/1995: false |
2/1992 > 11/1995: false |
11/1995 > 11/1995: true |
11/1995 > 11/1995: true <- different