Skip to content
systemcoding.dev
Systems Programming

Get Unix epoch seconds with time and time_t

Read the current Unix epoch seconds with time(NULL) on glibc 2.41, and build 32-bit targets with _TIME_BITS=64 so time_t survives the year 2038.

1 min read
Summarize in AI

time(NULL) returns the number of seconds since 1970-01-01 00:00:00 UTC, as a time_t. The call is simple. The part that bites is the width of time_t, which is 64 bits on x86-64 and arm64 but 32 bits by default on 32-bit Linux, where it overflows in January 2038.

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

int main(void) {
    time_t now = time(NULL);
    printf("sizeof(time_t) = %zu\n", sizeof now);
    printf("epoch = %lld\n", (long long)now);
    return 0;
}
Text
sizeof(time_t) = 8
epoch = 1795442709

The epoch value will differ on your machine. Cast to long long before printing, because there is no portable printf length modifier for time_t.

On a 32-bit target, glibc 2.34 and later let you ask for the 64-bit type with -D_TIME_BITS=64, which must be paired with -D_FILE_OFFSET_BITS=64, as explained in the glibc manual. Mixing objects built with different values of the flag changes struct layouts, so set it for every file of a build and every library you link, not just one.

time has one-second resolution and follows the wall clock, so it jumps when someone sets the date. For elapsed time use clock_gettime(CLOCK_MONOTONIC, ...) instead.

Taggedcglibc
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.