对于我正在开发的项目,我需要找到两个日期之间的差异,以检查哪个更新,我做得很好,但我发现了一个小bug。
对于使用struct tm的日期,这是代码:
struct tm firstDate, secondDate;
firstDate.tm_hour = 0;
firstDate.tm_min = 0;
firstDate.tm_sec = 0;
firstDate.tm_mon = 5;
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;
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);
它适用于每个日期,除非我想比较月末(如2016年5月31日)和第二天(2016年6月1日)的日期,它会返回0天它应该返回1.但如果我将其更改为2016年5月30日它返回1天而不是2.事情可能是31天而不是30 ..所以它在几个月工作,而在其他人它不工作..有谁知道如何摆脱这个?
提前感谢,抱歉我的英语不好,这不是我的母语
答案 0 :(得分:2)
secondDate.tm_mon
中的值0而不是1将代表1月。
试试这个:
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);