Format specifier to print time(0) in C

前端 未结 5 1629
南方客
南方客 2021-01-22 06:18

We can declare a variable to hold the current time from the system using:

time_t now = time(0);

time(0) can also be use in genera

5条回答
  •  情话喂你
    2021-01-22 07:05

    time_t is defined by C standard, C11, 7.27.1/3 as:

    [...] which are real types capable of representing times;

    That means it could be int, long, unsigned long, double or any other real type. Basically it's an implementation's choice. Similarly, it doesn't define what units time_t returns either, C11, 7.27.2.4/3:

    The time function returns the implementation’s best approximation to the current calendar time. The value (time_t)(-1) is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.

    You'll have to read what your implementation says. The glibc implementation I have on my Linux says, the unit returned by time_t is in seconds. So you could convert it to uintmax_t and print:

    time_t tvalue = time(0);
    printf("%ju", (uintmax_t)tvalue);
    

    Or you could use difftime() which returns a double as difference between two time_t values so that you don't have to worry about the underlying type of time_t.

提交回复
热议问题