These C examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
#include <time.h>
time_t now = time(NULL);
Convert a timestamp to UTC
time_t seconds = 1700000000;
struct tm *utc = gmtime(&seconds);
Production note
time_t is the conventional Unix-time type, but its width and range depend on the platform. Use the UTC conversion functions when the output must not depend on the host timezone.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: What type should I use for Unix timestamps in C?
- A: 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.
- Q: How do I get milliseconds in C?
- A: 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.