Format specifier to print time(0) in C

前端 未结 5 1624
南方客
南方客 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:15

    As already said, standard does not specifies what time_t is. If you want to be sure to use it in a portable way, first convert it to long and then print it as a long. That way your program won't suffer the Year 2038 problem even if 32 bits architectures are still available at that time :-) ...

    time_t t = time(NULL);
    long lt = (t > 0) ? t : (unsigned int) t;
    printf("%ld", lt);
    

    It should work for time_t being a 32 bits signed of insigned integer or a 64 bit integer. My formule will break when time_t will be a negative 64 bits integer, but contact me at that time and I should then be wise enough to find a better solution :-)

    EDIT :

    As noted by chux this is bad if int is only 16 bits. Here is a robust even if ugly way

    union {
        long l;
        unsigned char[1] c;
    } ul;
    time_t t = time(NULL);
    ul.l = 0;
    ul.c[0] = 255;
    if (ul.l < 0) { /* endianness test */
        ul.l = 0;
        memcpy(&ul.l, t&, sizeof(time_t));
    }
    else {
        ul.l = 0;
        memcpy(&ul.l + sizeof(long) - sizeof(time_t), &t, sizeof(time_t));
    }
    printf("%lu", (unsigned long) ul.l);
    

    It should work in any configuration provided sizeof(long)>=sizeof(time_t)

    EDIT 2:

    chux's proposal seems to work on any reasonable cases. There are certainly pathological cases where it could break but on a normal implementation

    time_t t = time(NULL);
    long lt = (t > 0) ? t : t * 1u;
    printf("%ld", lt);
    

    should give correct result.

提交回复
热议问题