I make a simple program to calculate the number of day between two days:
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <utility>
using namespace std;
int main(){
struct tm t1 = {0,0,0,28,2,104};
struct tm t2 = {0,0,0,1,3,104};
time_t x = mktime(&t1);
time_t y = mktime(&t2);
cout << difftime(y,x)/3600/24 << endl;
}
The output is 4 however, my expected result is 1. May I know where is the problem is ?
In a struct tm
, months are counted from 0
to 11
(not 1
to 12
), thus 2
is March and 3
is April, you code output the number of days between March the 28th and April 1st, which is 4.
The correct version would be:
struct tm t1 = {0, 0, 0, 28, 1, 104};
struct tm t2 = {0, 0, 0, 1, 2, 104};
By the way, 2004 is a leap year and thus February had 29 days, there were two days between February the 28th and March the 1st (not one).
difftime
gives you the number of seconds between 02/28/2004 00:00:00
and 03/01/2004 00:00:00
(the first day is accounted for in the difference).