Unix Timestamp in C

C's time() function has returned Unix timestamps since the 1970s — it's where the epoch convention originated. For sub-second precision, use clock_gettime() with CLOCK_REALTIME.

Ad

Code Examples

Current timestamp (seconds)

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

int main(void) {
    time_t now = time(NULL);
    printf("%ld\n", (long)now);
    return 0;
}

time(NULL) returns the current Unix timestamp as a time_t (typically a 64-bit signed integer on modern platforms). Cast to long for printf portability.

Current timestamp (milliseconds) — POSIX

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

int main(void) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long long ms = (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
    printf("%lld\n", ms);
    return 0;
}

clock_gettime with CLOCK_REALTIME gives nanosecond precision. tv_sec is full seconds; tv_nsec is the nanosecond remainder. Divide nanoseconds by 1,000,000 for milliseconds.

Convert timestamp to human-readable string

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

time_t ts = 1708560000;
struct tm *tm_info = gmtime(&ts);  /* UTC */
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", tm_info);
printf("%s\n", buf);  /* 2024-02-22T00:00:00Z */

gmtime converts a time_t to a struct tm in UTC. strftime formats it as a string. Use localtime instead of gmtime for the local timezone.

Thread-safe conversion — gmtime_r / localtime_r

#include <time.h>

time_t ts = time(NULL);
struct tm result;
gmtime_r(&ts, &result);     /* POSIX, thread-safe */
/* localtime_r(&ts, &result); for local timezone */

The reentrant variants gmtime_r and localtime_r are thread-safe — they write into a caller-provided struct tm instead of a static buffer. Prefer these in multi-threaded code.

Year 2038 check — ensure 64-bit time_t

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

int main(void) {
    printf("sizeof(time_t) = %zu bytes\n", sizeof(time_t));
    /* Should print 8 on 64-bit systems */
    return 0;
}

On 32-bit systems or old compilers, time_t may be 32-bit, causing overflow in January 2038. Modern 64-bit Linux/macOS systems use 64-bit time_t, safe until year 292 billion.

Note

C is where Unix timestamps originated — time() has been part of the C standard library since C89. On POSIX systems (Linux, macOS), clock_gettime() is the modern choice for high-resolution timestamps. On Windows, use GetSystemTimeAsFileTime() and convert from the Windows epoch (January 1, 1601). Always cast time_t to long or long long for printf — the underlying size is implementation-defined.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter