TIME

C provides a function, time(), which reads the computer's system clock to return the system time as a number of seconds since midnight on January the first, 1970. However, this value can be converted to a useful string by the function ctime() as illustrated in the following example;

#include <stdio.h>

#include <time.h>

int main()

{

/* Structure to hold time, as defined in time.h */

time_t t;

/* Get system date and time from computer */

t = time(NULL);

printf ("Today's date and time: %s\n",ctime(&t));

}

The string returned by ctime() is comprised of seven fields;

Day of the week,

Month of the year,

Date of the day of the month,

hour,

minutes,

seconds,

century of the year

terminated by a newline character and null terminating byte. Since the fields always occupy the same width, slicing operations can be carried out on the string with ease. The following program defines a structure 'time' and a function gettime() that extracts the hours, minutes and seconds of the current time and places them in the structure;

#include <stdio.h>

#include <time.h>

struct time

{

int ti_min; /* Minutes */

int ti_hour; /* Hours */

int ti_sec; /* Seconds */

};

void gettime(struct time *now)

{

time_t t;

char temp[26];

char *ts;

/* Get system date and time from computer */

t = time(NULL);

/* Translate dat and time into a string */

strcpy(temp,ctime(&t));

/* Copy out just time part of string */

temp[19] = 0;

ts = &temp[11];

/* Scan time string and copy into time structure */

sscanf(ts,"%2d:%2d:%2d",&now->ti_hour,&now->ti_min,&now->ti_sec);

}

int main()

{

struct time now;

gettime(&now);

printf ("\nThe time is %02d:%02d:%02d",now.ti_hour,now.ti_min,now.ti_sec);

}

The ANSI standard on C does actually provide a function ready made to convert the value returned by time() into a structure;

#include <stdio.h>

#include <time.h>

int main()

{

time_t t;

struct tm *tb;

/* Get time into t */

t = time(NULL);

/* Convert time value t into structure pointed to by tb */

tb = localtime(&t);

printf ("\nTime is %02d:%02d:%02d",tb->tm_hour,tb->tm_min,tb->tm_sec);

}

The structure 'tm' is defined in time.h as;

struct tm

{

int tm_sec;

int tm_min;

int tm_hour;

int tm_mday;

int tm_mon;

int tm_year;

int tm_wday;

int tm_yday;

int tm_isdst;

};

Timers

Often a program must determine the date and time from the host computer's non-volatile RAM. There are several time functions provided by the ANSI standard on C that allow a program to retrieve, from the host computer, the current date and time;

time() returns the number of seconds that have elapsed since midnight on January the 1st 1970. It has the prototype;

time_t time(time_t *timer);

time() fills in the time_t variable sent as a parameter and returns the same value. You can call time() with a NULL parameter and just collect the return value thus;

#include <time.h>

void main()

{

time_t now;

now = time(NULL);

}

asctime() converts a time block to a twenty six character string of the format;

Wed Oct 14 10:23:45 1992\n\0

asctime() has the prototype;

char *asctime(const struct tm *tblock);

ctime() converts a time value (as returned by time()) into a twenty six chracter string of the same format as asctime(). For example;

#include <stdio.h>

#include <time.h>

void main()

{

time_t now;

char date[30];

now = time(NULL);

strcpy(date,ctime(&now));

}

difftime() returns the difference, in seconds, between two values (as returned by time()). This can be useful for testing the elapsed time between two events, the time a function takes to execute, and for creating consistent delays that are irrelevant of the host computer.

An example delay program;

#include <stdio.h>

#include <time.h>

void DELAY(int period)

{

time_t start;

start = time(NULL);

while(time(NULL) < start + period)

;

}

void main()

{

printf ("\nStarting delay now....(please wait 5 seconds)");

DELAY(5);

puts("\nOkay, I've finished!");

}

gmtime() converts a local time value (as returned by time()) to the GMT time and stores it in a time block. This function depends upon the global variable timezone being set.

The time block is a predefined structure (declared in time.h) as follows;

struct tm

{

int tm_sec;

int tm_min;

int tm_hour;

int tm_mday;

int tm_mon;

int tm_year;

int tm_wday;

int tm_yday;

int tm_isdst;

};

tm_mday records the day of the month, ranging from 1 to 31; tm_wday is the day of the week with Sunday being represented by 0; the year is recorded less 1900; tm_isdst is a flag to show whether daylight saving time is in effect. The actual names of the structure and its elements may vary from compiler to compiler, but the structure should be the same in essence.

mktime() converts a time block to a calendar format. It follows the prototype;

time_t mktime(struct tm *t);

The following example allows entry of a date, and uses mktime() to calculate the day of the week appropriate to that date. Only dates from the first of January 1970 are recognisable by the time functions.

#include <stdio.h>

#include <time.h>

#include <string.h>

void main()

{

struct tm tsruct;

int okay;

char data[100];

char *p;

char *wday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ,

"prior to 1970, thus not known" };

do

{

okay = 0;

printf ("\nEnter a date as dd/mm/yy ");

p = fgets(data,8,stdin );

p = strtok(data,"/");

if (p != NULL)

tsruct.tm_mday = atoi(p);

else

continue ;

p = strtok(NULL,"/");

if (p != NULL)

tsruct.tm_mon = atoi(p);

else

continue ;

p = strtok(NULL,"/");

if (p != NULL)

tsruct.tm_year = atoi(p);

else

continue ;

okay = 1;

}

while(!okay);

tsruct.tm_hour = 0;

tsruct.tm_min = 0;

tsruct.tm_sec = 1;

tsruct.tm_isdst = -1;

/* Now get day of the week */

if (mktime(&tsruct) == -1)

tsruct.tm_wday = 7;

printf ("That was %s\n",wday[tsruct.tm_wday]);

}

mktime() also makes the neccessary adjustments for values out of range, this can be utilised for discovering what the date will be in n number of days time thus;

#include <stdio.h>

#include <time.h>

#include <string.h>

void main()

{

struct tm *tsruct;

time_t today;

today = time(NULL);

tsruct = localtime(&today);

tsruct->tm_mday += 10;

mktime(tsruct);

printf ("In ten days it will be %02d/%02d/%2d\n", tsruct->tm_mday,tsruct->tm_mon + 1,tsruct->tm_year);

}

This program uses Julian Dates to decide any day of the week since the 1st of October 1582 when the Gregorian calendar was introduced.

char *WDAY(int day, int month, int year)

{

/* Returns a pointer to a string representing the day of the week */

static char *cday[] = { "Saturday","Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday" };

double yy;

double yt;

double j;

int y1;

int y4;

int x;

yy = year / 100;

y1 = (int)(yy);

yt = year / 400;

y4 = (int)(yt);

x = 0;

if (month < 3)

{

year--;

x = 12;

}

j = day + (int)(365.25*year);

j += (int)(30.6001 * (month + 1 + x)) - y1 + y4;

if (yy == y1 && yt != y4 && month < 3)

j++;

j = 1 + j - 7 * (int)(j/7);

if (j > 6)

j -= 7;

return(cday[j]);

}

With time() and difftime() we can create a timer for testing the execution times of functions thus;

#include <stdio.h>

#include <time.h>

main()

{

time_t now;

time_t then;

double elapsed;

int n;

now = time(NULL);

/* This loop is adjustable for multiple passes */

for(n = 0; n < 5000; n++)

/* Call the function to test */

func();

then = time(NULL);

elapsed = difftime(then,now);

printf ("\nElapsed seconds==%lf\n",elapsed);

}

By way of time() and ctime() the current system date and time can be retrieved from the host computer thus;

#include <stdio.h>

#include <time.h>

main()

{

time_t now;

char *date;

int n;

/* Get system time */

now = time(NULL);

/* Convert system time to a string */

date = ctime(&now);

/*Display system time */

printf ("\nIt is %s",date);

}

time_t is a type defined in time.h as the type of variable returned by time(). This type may vary from compiler to compiler, and therefore is represented by the type "time_t".

 

  Header Files, Debugging, and Errors.

 

Links:  Home C Programming Guide C++ programming Guide

Contact Me