C-Unix-Timestamp-Snippets

C-Beispiele zum Holen des aktuellen Unix-Timestamps, Umwandeln von Epoch-Sekunden in ein lesbares Datum mit strftime() und Erzeugen von Timestamps aus Kalenderdaten mit timegm().

C timestamp basics

C represents Unix time as time_t, a signed integer type defined in <time.h>. On 64-bit systems time_t is 64 bits and immune to the Year 2038 overflow. On 32-bit systems it is still 32 bits on many platforms; check sizeof(time_t) to confirm. The standard function time(NULL) returns the current Unix time in seconds.

gmtime vs localtime

gmtime() converts a time_t to a struct tm in UTC. localtime() converts to the host system's local timezone. Always use gmtime() when you need a reproducible, timezone-independent result. Both functions return a pointer to a shared static struct; copy the result with a struct tm local variable if you need it across function calls.

C production notes

Prefer clock_gettime(CLOCK_REALTIME) over gettimeofday() for sub-second precision; POSIX marks gettimeofday() as obsolescent. Use timegm() (GNU/BSD) or a portable equivalent when converting calendar dates to UTC timestamps; mktime() interprets its input as local time, which silently produces wrong results in non-UTC environments.

  • Check sizeof(time_t) on embedded targets; 32-bit time_t wraps in January 2038
  • Use gmtime_r() and localtime_r() in multi-threaded code to avoid data races
  • strftime() format strings are locale-independent; prefer %Y-%m-%d over %x for interoperability
  • timegm() is not in POSIX; use _mkgmtime() on Windows or implement manually with mktime() + UTC offset

Frequently checked C details

What type should I use for Unix timestamps in C?
Use time_t for second precision and int64_t (from <stdint.h>) when you need to store milliseconds or nanoseconds. Avoid int or long because their sizes are platform-dependent.
How do I get milliseconds in C?
Use clock_gettime(CLOCK_REALTIME, &ts) from <time.h>. The result is in ts.tv_sec (seconds) and ts.tv_nsec (nanoseconds). Compute milliseconds as ts.tv_sec * 1000LL + ts.tv_nsec / 1000000.