C Programming/C Reference/time.h/time_t


The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard <time.h> header. ISO C defines time_t as an arithmetic type, but does not specify any particular type, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values.

Implementation edit

Unix and POSIX-compliant systems implement time_t as an integer or real-floating type [1] (typically a 32- or 64-bit integer) which represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a signed 32-bit time_t type are susceptible to the Year 2038 problem.[2]

In addition to the time() function, ISO C also specifies other functions and types for converting time_t system time values into calendar times and vice versa.

Example edit

The following C code retrieves the current time, formats it as a string, and writes it to the standard output.

#include <stdio.h>
#include <time.h>

/*
 * The result should look something like
 * Fri 2008-08-22 15:21:59 WAST
 */

int main(void)
{
    time_t     now;
    struct tm *ts;
    char       buf[80];

    /* Get the current time */
    now = time(NULL);

    /* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
    ts = localtime(&now);
    strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
    puts(buf);

    return 0;
}


Conversion to civil time edit

Using GNU date, a given time_t value can be converted into its equivalent calendar date:

$ date -ud@1234567890
Fri Feb 13 23:31:30 UTC 2009

Similarly, using BSD date:

$ date -ur 1234567890
Fri Feb 13 23:31:30 UTC 2009

References edit

  1. The Open Group Base Specifications Issue 7 sys/types.h. Retrieved on 2009-02-13.
  2. The Year 2038 problem, Roger M. Wilcox. Retrieved on 2011-03-11.