November 2005
Beginner to intermediate
594 pages
16h 23m
English
You want to know the amount of time elapsed between two date/time points.
If both date/time points falls between the years of 1970 and 2038, you can use a
time_t type and the difftime function from the <ctime>
header. Example 5-6 shows how to compute
the number of days elapsed between two dates.
Example 5-6. Date and time arithmetic with time_t
#include <ctime>
#include <iostream>
#include <cstdlib>
using namespace std;
time_t dateToTimeT(int month, int day, int year) {
// january 5, 2000 is passed as (1, 5, 2000)
tm tmp = tm();
tmp.tm_mday = day;
tmp.tm_mon = month - 1;
tmp.tm_year = year - 1900;
return mktime(&tmp);
}
time_t badTime() {
return time_t(-1);
}
time_t now() {
return time(0);
}
int main() {
time_t date1 = dateToTimeT(1,1,2000);
time_t date2 = dateToTimeT(1,1,2001);
if ((date1 == badTime()) || (date2 == badTime())) {
cerr << "unable to create a time_t struct" << endl;
return EXIT_FAILURE;
}
double sec = difftime(date2, date1);
long days = static_cast<long>(sec / (60 * 60 * 24));
cout << "the number of days between Jan 1, 2000, and Jan 1, 2001, is ";
cout << days << endl;
return EXIT_SUCCESS;
}The program in Example 5-6 should output :
the number of days between Jan 1, 2000, and Jan 1, 2001, is 366
Notice that the year 2000 is a leap year because even though it is divisible by 100; it is also divisible by 400, thus it has 366 days.
The time_t type is an implementation defined arithmetic type. This means it ...