What is Time of Day Function in C Library?

Question: What is Time of Day Function in Standard C Library?

Answer: Standard library provides collection of functions for dealing with time of the day and current date. ‘time()’ function is prototyped below

    time_t time(time_t *returned_value);

On many implementations, time_t value is defined as signed 32-bit quantity. Note that argument passed to ‘time()’ if not NULL, then it can be used to store time value. If the implementation can’t provide date and time or if the time is too large to be represented in a time_t variable, value -1 is returned.

It might be used to compute no. of seconds that have elapsed from some arbitrary chosen epoch, for ex. 00:00:00 January 1, 2014. Beware that don’t temp to call ‘time()’ twice to difference two values obtained to determine elapsed time because standard doesn’t require that resulting value should represent seconds.

Functions prototyped below are used to manipulate ‘time_t’ values,

advertisement
advertisement
    char *ctime(time_t const *time_value);
    double difftime(time_t tm1, time_t tm2);

Notice that ‘ctime()’ function takes pointer-to-time_t, converts it and returns as string. Let’s consider a simple C program

/* time.c -- program displays current date and time of day */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(void)
{
    time_t *returned_value, tm1;
    time_t *p2tm = &tm1;
    char *str; /* for current date and time of the day */
 
    tm1 = time(NULL);
 
    /* time conversion function */
    str = ctime(p2tm);
 
    str = ctime(p2tm);
    printf("current date and time of the day: %s\n", str);
 
    return 0;
}
current date and time of the day: Thu Jul  3 19:03:56 2014

Notice the output obtained is a string in which day value takes two positions even if first can be space and each of time values takes two positions. Further, spacing in string is fixed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.