Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

5.3. Performing Date and Time Arithmetic

Problem

You want to know the amount of time elapsed between two date/time points.

Solution

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.

Discussion

The time_t type is an implementation defined arithmetic type. This means it ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page