Return to Topic Menu | Computer Science Main Page | MathBits.com |Terms of Use

 

Time and Date Functions 

Required header:  #include <time.h>

A computer executes instructions at a very steady rate of time -- once every clock tick. 

We will be using the time( ) function which utilizes
a new data type:   time_t.

time_t rightNow;  // defines a time variable

time(NULL) returns the number of seconds elapsed since 00:00:00 hours, GMT (Greenwich Mean Time),
January 1, 1970.  

Example:

#include<iostream.h>
#include<time.h>

int main(void)
{
     time_t  getTime;  //declare a time variable called getTime
    
getTime = time(NULL);  //get seconds

     cout<<"The number of seconds since 1-1-1970: "
            << getTime;

     return 0;
}

Screen:

The number of seconds since 1-1-1970:  85430133124

(Number will change with each run!!)

 

 

<time.h>

 

time_t is a data type 

defined in the <time.h> header file and is an unsigned long int.

 

 

In C++, a time variable holds the number of seconds since midnight, January 1, 1970.  This is when C++ thinks time began.  

Using the time function to create "pauses" in output -- this will pause 3 seconds
(works in 1 second intervals only)

   time_t start, now;

   time(&start);
   do
   {
           time(&now);
   }
   while((now - start) < 3);

 
 
The clock function can also be used to create more controlled delays or pauses.
 

clock_t start;
start = clock( );
while((clock( ) - start) < .05 * CLOCKS_PER_SEC)
{
 }