Knowledge · Systems

    Reference

    C and C++ Unix timestamps

    Quick answer: On POSIX, read calendar time with time() or high-resolution clock_gettime(CLOCK_REALTIME, &ts). Break epochs into fields with gmtime_r/localtime_r, then format with strftime. Never mix wall-clock and monotonic clocks when persisting user-visible timestamps. Audit time_t width on embedded toolchains — 32-bit survives only until Y2038.

    time() vs clock_gettime() vs gettimeofday()

    time(3) returns seconds since the epoch as time_t. It is simple but offers no sub-second data.clock_gettime provides seconds plus nanoseconds for CLOCK_REALTIME (subject to NTP adjustments) or monotonic clocks for measuring intervals. gettimeofday is legacy; POSIX labels it legacy — prefer clock_gettime on new code. On Windows UCRT, use _time64 and friends when targeting 64-bit epochs consistently.

    struct tm breakdown

    struct tm holds calendar fields. Beware: tm_mon is 0-based while tm_year is years since 1900. Always zero the struct before use or call the *_r variants with an explicit result buffer for thread safety.

    strftime format codes (selected)

    CodeMeaning
    %YFour-digit year
    %mMonth 01–12
    %dDay of month
    %HHour 00–23 (UTC with gmtime)
    %MMinute
    %SSecond
    %zNumeric timezone offset
    %ZTimezone name (non-portable)

    POSIX vs Windows highlights

    MSVC and MinGW differ on which POSIX functions are available without feature macros. When cross-compiling, centralize time access behind a small abstraction and unit-test DST transitions using recorded vectors. Filesystems may store NTFS times in 100-ns intervals — do not confuse those counters with Unix epoch without documented conversion.

    Example: epoch to formatted UTC

    #include <stdio.h>
    #include <time.h>
    
    int main(void) {
      time_t now = time(NULL);
      struct tm utc;
      gmtime_r(&now, &utc);
      char buf[64];
      strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &utc);
      puts(buf);
      return 0;
    }

    Key takeaways

    • Use *_r functions on POSIX for thread-safe field breakdown.
    • Monotonic clocks measure duration; wall clocks answer "what time is it?"
    • Verify time_t size in firmware builds; assume nothing.
    • Prefer clock_gettime over gettimeofday for new code.
    • Centralize Windows vs POSIX differences behind one module.

    Written by Unix Calculator Editorial Team — Last verified May 2026.

    Timestamp converter

    Get the Unix Timestamp Cheatsheet

    One email. Instant cheatsheet. No drip sequence.

    Advertisement