Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 135 ยท Standard Library

Time and Date

Work with time in C - read the clock with time, break it into a struct tm with localtime and gmtime, format dates with strftime, do date math with mktime and time code with clock.

Programs need time for all sorts of jobs: stamping log lines, showing today's date, computing how many days are left until a deadline, or measuring how fast a function runs. C's tools for all of this live in <time.h>. They're small and a little old-fashioned, but they're available on every platform, from microcontrollers to servers.

The library revolves around three representations of time, and most of the work is converting between them: a time_t (a single number counting seconds), a struct tm (a broken-down calendar date with year, month, day, hour and so on) and formatted text made by strftime. For measuring durations there are two more clocks: clock() for processor time and C11's timespec_get for precise wall-clock time.

Our server's clock runs in UTC, so local time and UTC are the same in the examples below. On your own computer, localtime uses your time zone.

time_t and time()

time(NULL) returns the current calendar time as a time_t. On every mainstream system that's the number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC, stored in a 64-bit integer (the C standard itself only says it's a real type that represents time, so don't assume more than you need). Because it's just a number, two time_t values are easy to subtract with difftime, which returns the difference in seconds as a double.

C The current time in several forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Print a time_t by casting it to long long and using %lld; there's no dedicated format specifier. ctime is handy for quick debugging, but its format is fixed (Sat Oct 17 19:33:03 2026), English-only, and it ends with a newline. For anything users see, use strftime.

Note: Systems that store time_t as a signed 32-bit number overflow on 2038-01-19 at 03:14:07 UTC, the Year 2038 problem. Modern 64-bit Linux, macOS and Windows use a 64-bit time_t, which is good for billions of years, but old embedded systems and file formats with 32-bit timestamps are still out there.

struct tm: breaking time into fields

localtime(&t) converts a time_t into your local calendar time and gmtime(&t) into UTC. Both return a pointer to a struct tm with these int members:

Member Meaning Range
tm_year years since 1900 126 means 2026
tm_mon months since January 0โ€“11
tm_mday day of the month 1โ€“31
tm_hour, tm_min hours, minutes 0โ€“23, 0โ€“59
tm_sec seconds 0โ€“60 (60 allows a leap second)
tm_wday days since Sunday 0โ€“6
tm_yday days since January 1 0โ€“365
tm_isdst daylight saving time flag > 0 yes, 0 no, < 0 unknown

Two fields catch everyone at least once: tm_year counts from 1900 and tm_mon starts at 0. Always add 1900 and 1 when printing them yourself.

C Reading the fields of struct tm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The epoch line always prints 1970-01-01 00:00 UTC, a Thursday. The first block depends on when you run it.

Warning: localtime, gmtime and ctime return pointers to a shared static buffer: the next call overwrites the result of the previous one, and they aren't safe to use from several threads. Copy the struct right away (struct tm t = *localtime(&now);), or use the re-entrant versions that write into your own struct: localtime_r/gmtime_r on POSIX, localtime_s on Windows, and C23 standardizes localtime_r and gmtime_r.

Formatting dates with strftime

strftime(buffer, size, format, tm) is printf for dates. Conversion specifiers start with %; everything else is copied as is. It returns the number of characters written (not counting '\0'), or 0 if the result didn't fit, in which case the buffer's contents are undefined.

Specifier Meaning Example
%Y / %y year, 4 digits / 2 digits 2026 / 26
%m, %d month 01โ€“12, day 01โ€“31 03, 09
%H, %I, %p hour 00โ€“23, hour 01โ€“12, AM/PM 14, 02, PM
%M, %S minute, second 05, 59
%A / %a weekday name, full / short Monday / Mon
%B / %b month name, full / short March / Mar
%j day of the year 001โ€“366 068
%F, %T %Y-%m-%d, %H:%M:%S (C99) 2026-03-09, 14:05:59
%z, %Z UTC offset, time zone name +0000, UTC
%c, %x, %X locale's date and time, date, time
%% a literal %

The ISO 8601 format %Y-%m-%dT%H:%M:%SZ (with a UTC time) is the safest choice for logs and files: it's unambiguous everywhere and sorts correctly as text. 03/04/2026 means March 4 in the US and April 3 in most of the world.

C Formatting a fixed date with strftime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

mktime fills in tm_wday and tm_yday, which is why %A correctly says Monday even though the code never set a weekday. The month and weekday names come from the current locale. A C program starts in the "C" locale (English names) until it calls setlocale(LC_ALL, "") from <locale.h> to adopt the user's language settings.

Date arithmetic with mktime

mktime converts a local struct tm back to a time_t, and it normalizes out-of-range fields along the way: day 32 of January becomes February 1, and minute -30 borrows an hour. That makes it the standard library's date calculator. To find the date 100 days from now, add 100 to tm_mday and call mktime; no month-length tables needed.

C Days between dates and adding days

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It counts 344 days between the two dates, finds that 45 days after 2026-12-20 is Wednesday 2027-02-03, and that February 2028 ends on Tuesday the 29th. Day 0 of a month means "the day before day 1", a neat trick for finding the last day of the previous month.

Dividing a difftime result by 86400 is only safe when both times are at the same time of day and daylight saving time doesn't shift them; that's why make_date uses noon and the result is rounded with %.0f. Days with a DST change are 23 or 25 hours long in local time.

Note: Standard C has no function that converts a UTC struct tm back to time_t (the inverse of gmtime). C23 adds timegm, which glibc, macOS and the BSDs have offered for years; on Windows it's called _mkgmtime. Parsing date text is also missing from the standard: POSIX has strptime, or you can read the numbers with sscanf(text, "%d-%d-%d", &y, &m, &d) and validate them.

Measuring elapsed time

There are two different questions you can ask when timing code, and C has a clock for each:

  • How much processor time did my program use? clock() returns CPU time in ticks; divide by CLOCKS_PER_SEC (1,000,000 on POSIX systems) to get seconds. It doesn't advance while the program is sleeping or waiting for input.
  • How much real time passed? time() only has one-second resolution. C11's timespec_get(&ts, TIME_UTC) fills a struct timespec with seconds and nanoseconds. POSIX's clock_gettime(CLOCK_MONOTONIC, &ts) is better still for durations, because a monotonic clock never jumps when someone changes the system time.
C Timing code with clock and timespec_get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

There are 25,997 primes below 300,000. The two times are close here because the program does nothing but compute; the exact numbers change from run to run and depend on the machine. A program that waits for input or sleeps uses almost no CPU time while its wall-clock time keeps growing, and a program with several busy threads can use more CPU seconds than wall seconds. You'll use these timing tools again in Sorting and Searching Algorithms to compare sorting algorithms.

Tip: When you benchmark, repeat the work enough times that it takes at least a tenth of a second, run it a few times, and make sure the result is used (here it's printed). Otherwise the optimizer may remove the computation entirely, and you'll time nothing.

Date and time programs

Four small programs that come up again and again. They use fixed values instead of the current time, so the output is always the same and you can check it by hand. Replace the fixed values with time(NULL) and localtime when you want a live clock.

  • 12-hour clock (AM/PM). strftime does it with %I:%M %p, but doing it by hand shows the rule: hour 0 becomes 12 AM, hours 13 to 23 subtract 12, and noon is 12 PM.
  • Seconds to hours, minutes and seconds. Divide by 3600, then take the remainder and divide by 60. This is also how a digital clock or a stopwatch display is formatted.
  • UTC (GMT) from a time_t. gmtime converts a time_t to UTC fields. On your own machine, printing the same time_t with both localtime and gmtime shows your zone's offset (the demo server runs in UTC, so both would match).
  • Calendar of a year. You need the weekday of the 1st of each month and the length of the month, including the leap-year rule from C Programs. mktime fills in tm_wday, so you do not need a weekday formula.
C AM/PM, hours to seconds, UTC and a year calendar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The February calendars show the leap-year rule: 2024 ends on the 29th, 2025 on the 28th. tm_wday counts from 0 (Sunday), so the first row is indented by three spaces per weekday, and a newline follows every Saturday, which is when first.tm_wday + day is divisible by 7. The .tm_hour = 12 avoids daylight-saving edge cases around midnight. To print a whole year, loop month from 0 to 11 and call print_month each time. A digital clock is printf("\r%02d:%02d:%02d", ...) inside a loop that sleeps a second between iterations; the carriage return \r rewrites the same terminal line.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A struct tm has tm_year = 126 and tm_mon = 0. Which date is it?

    tm_year counts years since 1900, so 126 is 2026, and tm_mon counts from 0, so 0 is January.
  2. 2. You call localtime twice and store both pointers, then print the first one. What do you see?

    localtime returns a pointer to a shared static struct that every call overwrites. Copy the struct (struct tm t = *localtime(&now)) or use localtime_r.
  3. 3. What does strftime return when the formatted date doesn't fit into the buffer?

    Unlike snprintf, strftime returns 0 when the result plus the terminating null character doesn't fit, and the buffer contents are then indeterminate.
  4. 4. You set tm_mday = 31 and tm_mon = 3 (April) and call mktime. What happens?

    mktime normalizes out-of-range fields, so April 31 becomes May 1. That's what makes adding days with tm_mday so convenient.
  5. 5. A program sleeps for 2 seconds, then computes for 0.1 seconds. Roughly what does clock() measure for the whole run?

    clock() measures CPU time used by the program. Sleeping uses no CPU, so only the computation counts. Use timespec_get or clock_gettime for wall-clock durations.

Summary

  • time(NULL) returns the current time as a time_t, usually seconds since 1970-01-01 UTC; print it as (long long) with %lld, and subtract times with difftime.
  • localtime and gmtime break a time_t into a struct tm. Remember tm_year + 1900 and tm_mon + 1, and copy the result or use localtime_r, because the returned buffer is shared.
  • strftime formats dates with %Y, %m, %d, %H, %M, %S, %A, %B and more; it returns 0 if the buffer is too small. ISO 8601 (%Y-%m-%dT%H:%M:%SZ) is the safest format for logs and files.
  • mktime converts a local struct tm to time_t and normalizes fields, so adding to tm_mday is the easy way to do date arithmetic.
  • Measure CPU time with clock() / CLOCKS_PER_SEC, and wall-clock time with C11 timespec_get or POSIX clock_gettime(CLOCK_MONOTONIC, ...).

Next: Random Numbers, where you'll generate dice rolls, pick values in a range without bias and shuffle arrays.