56

I do not know the data type of time_t. Is it a float double or something else? Because if I want to display it I need the tag that corresponds with it for printf. I can handle the rest from there for displaying time_t but I need to know the data type that corresponds with it.

4 Answers4

43

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));
dan04
  • 87,747
  • 23
  • 163
  • 198
  • 5
    That assumes the platform supports (long long). It is precisely when it does not that you need to know that time_t is only 32-bit. – Ian Goldby Aug 15 '12 at 08:53
  • 4
    It also assumes that `long long` is large enough to hold the value. As far as the standard says `time_t` can be the number of yoctoseconds since the first Monty Python episode was aired (which will make it larger than 64 bits). – skyking Oct 26 '16 at 07:08
  • 1
    @skyking is not lying. You would need at least a 111-bit number to hold such a value (roughly 1.5e33). Until they put `long long long long` into the standard, you can prepare for the future by storing all your `time_t`s in a `uint64_t[2]`. –  Feb 15 '18 at 23:28
31

Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
19

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);
r0estir0bbe
  • 699
  • 2
  • 7
  • 23
user2483388
  • 315
  • 2
  • 9
2

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

Sniggerfardimungus
  • 11,583
  • 10
  • 52
  • 97
  • 6
    I know your comment is old, but you need to use `printf ("%f\n", (double) time(NULL));` because printf is a vararg function. – sjoelund.se Jan 15 '14 at 15:04