Reputation: 45
For a project im developing i need to find a diference between two dates to check which is more recent, and i was doing just fine but i found a little bug.
for the dates im using struct tm, this is the code:
it works in every date except when i want to compare a date in the end of the month like (31/5/2016) with the following day (1/6/2016), it returns me 0 days and it should return 1. but if i change it to 30/5/2016 it returns 1 day instead of 2. The thing is may is 31 days not 30.. so it works in some months and in others it doesnt work.. does anyone know how to get past this?
thanks in advance and sorry for my bad english, it isn't my native language
Upvotes: 2
Views: 83
Reputation: 75062
The value 0, not 1, in secondDate.tm_mon
will stand for January.
Try this:
struct tm firstDate, secondDate;
firstDate.tm_hour = 0;
firstDate.tm_min = 0;
firstDate.tm_sec = 0;
firstDate.tm_mon = 5 - 1;
firstDate.tm_mday = 30;
firstDate.tm_year = 2016 - 1900; //difference between current year and 1900
secondDate.tm_hour = 0;
secondDate.tm_min = 0;
secondDate.tm_sec = 0;
secondDate.tm_mon = 6 - 1;
secondDate.tm_mday = 1;
secondDate.tm_year = 2016 - 1900;
time_t fDate = mktime(&firstDate); // 31/5/2016
time_t sDate = mktime(&secondDate); // 1/6/2016
int diff = (difftime(fDate, sDate));
printf("%d", diff / 86400);
Upvotes: 2