How do I get the unix timestamp in C as an int?

后端 未结 5 485
借酒劲吻你
借酒劲吻你 2020-12-07 22:05

I would like to get the current timestamp and print it out using fprintf.

5条回答
  •  执念已碎
    2020-12-07 22:59

    Is just casting the value returned by time()

    #include 
    #include 
    
    int main(void) {
        printf("Timestamp: %d\n",(int)time(NULL));
        return 0;
    }
    

    what you want?

    $ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
    Timestamp: 1343846167
    

    To get microseconds since the epoch, from C11 on, the portable way is to use

    int timespec_get(struct timespec *ts, int base)
    

    Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

    The code for both functions is nearly identical:

    #include 
    #include 
    #include 
    #include 
    
    int main(void) {
    
        struct timespec tms;
    
        /* The C11 way */
        /* if (! timespec_get(&tms, TIME_UTC)) { */
    
        /* POSIX.1-2008 way */
        if (clock_gettime(CLOCK_REALTIME,&tms)) {
            return -1;
        }
        /* seconds, multiplied with 1 million */
        int64_t micros = tms.tv_sec * 1000000;
        /* Add full microseconds */
        micros += tms.tv_nsec/1000;
        /* round up if necessary */
        if (tms.tv_nsec % 1000 >= 500) {
            ++micros;
        }
        printf("Microseconds: %"PRId64"\n",micros);
        return 0;
    }
    

提交回复
热议问题