The standard doesn't define what type time_t
is; it only has to be a real type capable of representing times. It could be an integer type or a floating-point type (it can't be complex -- fortunately). And it's not necessarily a number of seconds, or milliseconds, or any simple units. It could in principle use ranges of bits to represent months, seconds, days, hours, minutes, and years in that order in binary coded decimal. The most common representation is a 32-bit or 64-bit signed integer representing seconds since 1970-01-01 00:00:00 UTC.
If you want a completely portable way to print a time_t
value, you can detect what kind of type time_t
is:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
int main(void) {
time_t now = time(NULL);
printf("At the sound of the tone, the time will be ... \a");
if ((time_t)1 / 2 != 0) {
// time_t is a floating-point type; convert to long double
printf("%Lf\n", (long double)now);
}
else if ((time_t)-1 > (time_t)0) {
// time_t is an unsigned integer type
printf("%ju\n", (uintmax_t)now);
}
else {
// time_t is a signed integer type
printf("%jd\n", (intmax_t)now);
}
}
This assumes a C99 or later implementation. If you're stuck with a pre-C99 implementation that doesn't support <stdint.h>
and/or the %ju
and %jd
formats (which you can detect this by testing __STDC_VERSION__
), you can convert to long
or unsigned long
rather than [u]intmax_t
. (MinGW probably won't handle printing a long double
value correctly, but MinGW uses a signed integer type for time_t
so that's not an issue.)
This will print a raw value that isn't meaningful unless you happen to know how time_t
is represented (both what type it is and how it represents the current time). On my system, the current time is 1416589039
, which is the number of seconds since 1970-01-01 00:00:00 UTC (a very common representation).
If you want to know what time it is rather than the raw value returned by the time()
function, you should use the functions in <time.h>
to generate a human-readable representation of the current time. For example:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
int main(void) {
time_t now = time(NULL);
char s[100];
strftime(s, sizeof s, "%F %H:%M:%S %Z", localtime(&now));
printf("The time is now %s\n", s);
}
which prints (at the moment on my system):
The time is now 2014-11-21 08:57:19 PST