Format specifiers for implementation-defined types like time_t

c, printf, time-t, typedef

Solution

Generally, the way to display the value of a `time_t` is to break down its components to a `struct tm` using `gmtime` or `localtime` and display those or convert them as desired with `strftime`, or `ctime` to go directly from `time_t` to a string showing local time.

If you want to see the raw value for some purpose, the C standard specifies that `time_t` is real, which means it is integer or floating-point (C 2011 (N1570) 6.2.5 17). Therefore, you should be able to convert it to `double` and print that. There is some possibility that `time_t` can represent values that `double` cannot, so you might have to guard against that if you want to take care regarding exotic implementations. Since `difftime` returns the difference of two `time_t` objects as a `double`, it seems C does not truly support `time_t` with more precision than a `double`.

Problem

I want to make my code more platform-/implementation-independent. I don't know what a `time_t` will be implemented as on the platform when the code is being compiled. How do I know the type of `t` to determine what format specifier to use? ``` ... time_t t = time(NULL); printf("%s", t); ... ```

Original source

Related problems