http://cpp.gantep.edu.tr
C++ resources. Faculty of Engineering, University of Gaziantep
 MAIN  -  Tutorials  -  Howtos  -  nmPrimer  -  Misc  -  Links  -  Contacts
Last modified: Mon, 16 Nov 2009 18:55:56 +0200

Complete: ###################- (95%)

Using Date-Time Functions
1.   time() Function
2.   Types and Constants
3.   List of Functions
4.   Examples
5.   Working with milli seconds and micro seconds

1.   time() Function

Several C functions are called date and time functions. The declarations of all date and time functions, symbolic constants and standard structures are included in the header file <ctime>.

The time() function returns the number of seconds elapsed since 00:00 01/01/1970 from the system clock. The syntax for the time() function is:

  time_t time(time_t *timer);
Here
  • time_t   is the arithmetic type (defined as long int by default in most compilers) that is used to represent time.
  • timer   is a pointer variable pointing to a memory storage that can hold the calendar time returned by this function.
Note that the time() returns -1 if the calendar time is not available on the computer.

You can get the number of seconds elapsed (since 01/01/1970) in two ways:

  1. by using return value
      time_t t;
      .
      .
      t = time(NULL);
      cout << "time: " << t; 
    

  2. by passing a parameter
      time_t t;
      .
      .
      time(&t);
      cout << "time: " << t;
    
An example of using the time() function is given below.

time1.cpp: Example use of the time() function:
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
// Example use of the time() function:
#include <iostream>
#include <cstdlib>
#include <ctime>

int main ()
{

  double sum=0.0;

  time_t t0 = time (NULL);
  std::cout << t0/(3600*24) << " days have past since 01/01/1970\n";

  std::cout << "This will just take a minute or so ...\n";
  for (long i=1; i<=1e10L; i++) sum += rand()/(RAND_MAX+1.0);
  std::cout << "mean = " << sum/1e10L << std::endl;

  time_t t1 = time (NULL);
  std::cout << "That took " << t1-t0 << " seconds.\n";

  return 0;
}
14564 days have past since 01/01/1970
This will just take a minute or so ...
mean = 0.499999
That took 117 seconds.

 Note that
For 32 bit machines, the maximum value returned by the time() function is 2147483647 since time_t is a redefinition of the long type. This value corresponds the date Jan 19th, 2038. After this date 32 bit machines may have timing problems!

2.   Types and Constants

CLK_TCK or CLOCKS_PER_SEC
These two macro constants are equivalent and define the number of clock ticks per second used by the clock() function.
See also the content of the files: <ctime>, <time.h>, <bits/time.h>.

clock_t and time_t
These are the data types returned by the clock() and time() functions respectively. They are generally defined as long int.

tm
Structure returned or used by asctime(), gmtime(), localtime() and mktime().
The tm structure definition is:

  /* structure to store date and time information */
  typedef struct {
     int tm_hour;   /* hour (0 - 23) */
     int tm_isdst;  /* daylight saving time enabled/disabled */
     int tm_mday;   /* day of month (1 - 31) */
     int tm_min;    /* minutes (0 - 59) */
     int tm_mon;    /* month (0 - 11 : 0 = January) */
     int tm_sec;    /* seconds (0 - 59) */
     int tm_wday;   /* Day of week (0 - 6 : 0 = Sunday) */
     int tm_yday;   /* Day of year (0 - 365) */
     int tm_year;   /* Year less 1900 */
  }

3.   List of ANSI C Functions

The Following are the ANSI C library with time and date related functions. All functions are defined in <ctime> which includes <time.h>.
See also: cplusplus.com/ref/ctime and http://www.cppreference.com/wiki/c/date/start.

Table 1: Date-Time functions
Function Decleration Description
char *asctime(const struct tm *tp); Converts data pointed by tp to a string containing time and date in readable format. tp is a pointer to a tm structure as the ones returned by gmtime and localtime. The returned string has the following format:
Www Mmm dd hh:mm:ss yyyy

Here, Www is the weekday, Mmm is the month in letters, dd is the day of the month, hh:mm:ss is the time and yyyy is the year.
clock_t clock(void); Returns the number of clock ticks elapsed. The macro constant called CLK_TCK defines the relation between clock tick and second (clock ticks per second). On failure, the function returns -1.
char *ctime(const time_t *timer); Converts timer to a string containing time and date adjusted to local time zone in readable format. The returned string has the format: Www Mmm dd hh:mm:ss yyyy.
double difftime(time_t timer1, time_t timer2); Evaluates the time difference timer2 - timer1 in seconds.
struct tm *gmtime(const time_t *timer); Converts timer to tm structure adjusting to UTC (formerly known as GMT, Greenwich Mean Time) timezone. timer is pointer to a time_t value, usually returned by time function.
struct tm *localtime(const time_t *timer); Converts timer to tm structure adjusting to the local time zone. timer is pointer to a time_t value.
time_t mktime(struct tm *ptm); Checks the members of the tm structure passed as parameter ptm adjusting the values if the ones provided are not in the possible range or they are incomplete or mistaken and then translates that structure to a time_t value (seconds elapsed since Jan 1, 1970) that is returned. ptm is pointer to a tm structure that contains data to be computed.
time_t time(time_t *timer); Get the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC from the system clock. timer is the location where to store the retrieved value. If this is NULL the value is not stored.

4.   Examples

time2.cpp: Using the asctime() and localtime() functions
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
// Using the asctime() and localtime() functions
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  time_t t;
  struct tm *timeinfo;

  time (&t);
  timeinfo = localtime (&t);
  cout << "Current date and time are\n" << asctime(timeinfo) << endl;

  return 0;
}
Current date and time are
Wed Nov 11 11:14:10 2009

time3.cpp: Using the ctime() function
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
// Using the ctime() function
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  time_t t;

  time(&t);
  cout << "Current date and time are\n" << ctime(&t) << endl;

  return 0;
}
Current date and time are
Wed Nov 11 11:16:47 2009

time4.cpp: Using the clock() function
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
// Using the clock() function
#include <iostream>
#include <ctime>
using namespace std;

void wait(int sec){
  clock_t end;
  end =  clock() + sec * CLOCKS_PER_SEC;
  while( clock() < end) {}
}

int main()
{
  int n;
  cout << "Starting countdown...\n";
  for (n=10; n>0; n--){
    cout << "n = " << n << endl;
    wait(1);  // wait one second after printing
  }

  cout << "done." << endl;
  return 0;
}
Starting countdown...
n = 10
n = 9
n = 8
n = 7
n = 6
n = 5
n = 4
n = 3
n = 2
n = 1
done.

time5.cpp: Real-time displayer
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
// Real-time displayer
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main()
{
  time_t t;
  struct tm *tinfo;

  cout << "CTRL+C to quit!" << endl;

  while(true)
  {
     time(&t);
     tinfo = localtime(&t);

     cout << setw(2) << setfill('0') <<  tinfo->tm_hour << ':';
     cout << setw(2) << setfill('0') <<  tinfo->tm_min << ':';
     cout << setw(2) << setfill('0') <<  tinfo->tm_sec << '\r';
  }

  return 0;
}
CTRL+C to quit!
11:27:47

time6.cpp: Weekday calculator
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
 28:
 29:
 30:
 31:
 32:
 33:
 34:
// Weekday calculator
#include <iostream>
#include <ctime>
#include <string>
using namespace std;

int main()
{
  time_t t;
  struct tm * timeinfo;
  int year, month ,day;
  string weekday[] = { "Sunday", "Monday",
                       "Tuesday", "Wednesday",
                       "Thursday", "Friday", "Saturday"};

  // prompt user for date
  cout << "Enter  year: "; cin >> year;
  cout << "Enter month: "; cin >> month;
  cout << "Enter   day: "; cin >> day;

  // get current timeinfo and modify it to user's choice
  t = time(NULL);
  timeinfo = localtime(&t);
  timeinfo->tm_year = year - 1900;
  timeinfo->tm_mon  = month - 1;
  timeinfo->tm_mday = day;

  // call mktime: timeinfo->tm_wday will be set
  mktime(timeinfo);

  cout << "That day is a " << weekday[timeinfo->tm_wday] << endl;

  return 0;
}
Enter  year: 2003
Enter month: 8
Enter   day: 1
That day is a Friday

5.   Working with milli seconds and micro seconds

Sometimes it is necessary to work with milli second (ms) or micro second (μs) time intervals. In GCC, there are function and structural definitions to work with ms and μs. One can use the gettimeofday() function defined in <sys/time.h>.

time_usec.cpp: Getting micro and milli seconds
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
 28:
 29:
// Lower units of seconds
// Compiled with g++ (GCC) 4.3.3
#include <iostream>
#include <ctime>
#include <sys/time.h>

int main()
{
  struct   timeval  tv;
  struct   timezone tz;
  struct   tm      *tm;
  long int hh, mm, ss, us;
  double   ms;

  gettimeofday(&tv, &tz);
  tm = localtime(&tv.tv_sec);

  hh = tm->tm_hour;        // hours
  mm = tm->tm_min;         // minutes
  ss = tm->tm_sec;         // seconds

  us = tv.tv_usec;         // micro seconds
  ms = tv.tv_usec*1.0e-3;  // mili seconds

  std::cout << hh << ':'  << mm << ':'  << ss << '\n'
            << us << '\t' << ms << std::endl;

 return 0;
}
10:41:42
657312  657.312

When we run the program, the number of seconds was 42. In fact this value is somewhere between 42 and 43. The number 657312 in the output indicates the time difference in micro-seconds between the 42nd and 43rd second. Hence the value was 42 s + 657312 μs = 42.657312 s.
please send us you comments/questions/corrections