Coding

Time in C: time(), localtime(), strftime() and clock() Explained

To get the time in C, include <time.h> and call time(NULL), which returns the seconds since the Epoch (1970-01-01 00:00:00 UTC) as a time_t. Convert that value with localtime() or gmtime() and print it with strftime(); use clock() when you want to measure how much processor time a piece of code used.

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

int main(void) {
    time_t now = time(NULL);
    struct tm *local = localtime(&now);
    char text[64];

    if (strftime(text, sizeof text, "%Y-%m-%d %H:%M:%S", local) == 0) {
        fprintf(stderr, "buffer too small\n");
        return 1;
    }
    printf("%s\n", text);
    return 0;
}

Example output (your date and time will differ):

2026-11-26 14:05:09

The three types you work with

Time handling in C is a chain of conversions between three representations.

  • time_t is a single number. Read as an absolute time, it counts seconds since the Epoch, 1970-01-01 00:00:00 UTC. For more on that idea, see Unix timestamp explained.
  • struct tm is the "broken-down" form with separate fields for year, month, day, hour, minute and second.
  • A string is what you show a person. strftime() builds it from a struct tm.

The functions move you between them: time() produces a time_t; localtime() and gmtime() turn a time_t into a struct tm; mktime() turns a local struct tm back into a time_t; strftime() turns a struct tm into text.

time(): get the current time

time() returns the number of seconds since the Epoch. The Linux man page says the tloc argument is obsolescent and should always be NULL in new code, so write time(NULL). With a NULL argument the call cannot fail.

If you do pass a pointer and the call fails, the return value is (time_t) -1. That value is indistinguishable from a legitimate time one second before the Epoch, which is why passing NULL is the simpler pattern.

A time_t is not guaranteed to be a particular integer width. The same man page notes that a 32-bit time_t cannot represent times after 2038-01-19 03:14:08 UTC. To print one portably, cast it, for example printf("%lld\n", (long long)now);.

localtime() and gmtime(): break the time into fields

Both take a pointer to a time_t and return a pointer to a struct tm. gmtime() gives the result in UTC. localtime() gives it in the user's configured time zone. They differ only in the zone: the same time_t gives the same instant either way.

The fields have offsets that trip people up:

FieldMeaningTo print a normal value
tm_yearYears since 1900tm_year + 1900
tm_monMonth, 0 = Januarytm_mon + 1
tm_mdayDay of monthuse as is
tm_hour, tm_min, tm_secTime of dayuse as is
tm_isdstDaylight saving flagpositive means in effect

The man page's own example code sets tm_year = year - 1900 and tm_mon = month - 1, which confirms both offsets.

time_t now = time(NULL);
struct tm *utc = gmtime(&now);
if (utc == NULL) {
    perror("gmtime");
    return 1;
}
printf("%04d-%02d-%02d\n", utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday);

gmtime() and localtime() return NULL on error and set errno; the documented error is EOVERFLOW, meaning the result cannot be represented. Check for NULL before you dereference.

Static buffers and thread safety

The functions asctime(), ctime(), gmtime() and localtime() return pointers to static data. A later call can overwrite it, and the man page states they are not thread-safe. If you need two results at once, or you use threads, use the reentrant versions, which fill a struct tm that you own:

struct tm local_copy;
if (localtime_r(&now, &local_copy) == NULL) {
    perror("localtime_r");
    return 1;
}

localtime_r() is POSIX, so it is available on Linux and macOS but not part of standard C. The man page also recommends calling tzset() before localtime_r() in portable code, because POSIX does not require the reentrant version to initialise the time zone.

strftime(): format the time as text

The signature is:

size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

It writes at most max bytes into s, including the terminating null byte, and returns the number of bytes written excluding that null byte. If the result does not fit, it returns 0 and the contents of the array are undefined. The man page adds that a return of 0 does not always mean an error, since a format can legitimately produce an empty string. Always pass sizeof the buffer, and treat 0 as a failure for any non-empty format.

Common conversion specifiers, as documented in the man page:

SpecifierOutput
%YFour-digit year
%mMonth, 01 to 12
%dDay of month, 01 to 31
%HHour on a 24-hour clock, 00 to 23
%MMinute, 00 to 59
%SSecond, 00 to 60 (60 allows for a leap second)
%FSame as %Y-%m-%d
%TSame as %H:%M:%S
%A, %BFull weekday and month names in the current locale
%jDay of year, 001 to 366
%pAM or PM in the current locale
%ZTime zone name or abbreviation
%zUTC offset as +hhmm or -hhmm

To print a UTC timestamp in a machine-friendly form, pair gmtime() with %F and %T:

char stamp[32];
strftime(stamp, sizeof stamp, "%FT%TZ", gmtime(&now));

Example output: 2026-11-26T14:05:09Z. The literal T and Z are copied through unchanged. Use gmtime() here, because the trailing Z claims the time is UTC. Python has a similar format-code system, covered in Python datetime strftime format.

mktime(): go from fields back to time_t

mktime() converts a local broken-down time into a time_t. It ignores your tm_wday and tm_yday inputs and recomputes them, and it normalises out-of-range fields: according to the man page, 40 October becomes 9 November. That makes date arithmetic easy: add 30 to tm_mday, call mktime(), and read the corrected fields.

Set tm_isdst to a negative value to let mktime() decide whether daylight saving applies. On failure it returns (time_t) -1, which is also a valid time one second before the Epoch, so the man page's example detects failure by checking whether tm_wday was changed.

clock(): measure processor time

clock() returns an approximation of the processor time your program has used so far. Divide the difference between two calls by CLOCKS_PER_SEC to get seconds:

clock_t start = clock();
/* work to measure */
clock_t end = clock();
double seconds = (double)(end - start) / CLOCKS_PER_SEC;
printf("%.3f s of CPU time\n", seconds);

Points from the man page that matter in practice:

  • It measures CPU time, not wall-clock time. Time spent sleeping or waiting for input or the network is not counted.
  • The starting value is arbitrary under the C standard, so always subtract a value taken earlier in the same program.
  • If the value is unavailable or cannot be represented, it returns (clock_t) -1.
  • On Linux, time used by waited-for child processes is not included.
  • On a 32-bit system with CLOCKS_PER_SEC equal to 1,000,000, the value wraps about every 72 minutes.

For elapsed wall-clock time between two time() calls, difftime(end, start) returns the difference in seconds as a double. Its resolution is one second, so it is too coarse for timing short code.

Common mistakes

  • Printing tm_year or tm_mon directly. You get 126 and 10 for November 2026. Add 1900 and 1.
  • Using the pointer from localtime() later. The next call overwrites it. Copy the struct if you need it to last.
  • Ignoring the return of strftime(). A too-small buffer gives 0 and undefined contents.
  • Timing with clock() a program that mostly waits. It reports CPU time, so it will under-report a program blocked on I/O.
  • Labelling local time as UTC. Appending Z to a localtime() result is wrong unless your zone is UTC.

If the output is the wrong time zone

localtime() uses the time zone configured for the user, as the man page describes. If the output looks hours off, print %Z and %z alongside the time to see which zone and offset C is using, then compare with your system settings. When you need a result that does not depend on the machine's configuration, use gmtime().

Frequently asked questions

How do I get the current time in C?
Call time(NULL) from <time.h>. It returns a time_t, the number of seconds since the Epoch (1970-01-01 00:00:00 UTC). Pass the value to localtime() or gmtime() to get year, month, day, hour, minute and second fields, or to strftime() through a struct tm to print it.
Why does my year print as 126 instead of 2026?
The tm_year field of struct tm counts years since 1900, so 2026 is stored as 126. Add 1900 when you read it. The tm_mon field is also offset: it runs from 0 (January) to 11 (December), so add 1 to print a calendar month number.
What is the difference between time() and clock() in C?
time() returns wall-clock calendar time in seconds since the Epoch. clock() returns the processor time your program has used, which you divide by CLOCKS_PER_SEC to get seconds. A program that sleeps or waits on input uses wall-clock time without using processor time, so the two can differ a lot.
Is localtime() thread-safe?
No. localtime(), gmtime(), ctime() and asctime() return pointers to static data that a later call can overwrite. Use localtime_r() or gmtime_r() in threaded code, which write into a struct tm that you supply.

Sources