How to use strftime() to format time like a Unix timestamp in C

1 Answer

0 votes
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    struct timeval tv;
    
    gettimeofday(&tv, NULL);
    
    struct tm *tm;
    char strf[64], snpr[64];

    if ((tm = localtime(&tv.tv_sec)) != NULL) {
        strftime(strf, sizeof strf, "%Y-%m-%d %H:%M:%S.%%06u %z", tm);
        snprintf(snpr, sizeof snpr, strf, tv.tv_usec);
        printf("%s", snpr); 
    }

    return 0;
}



/*
run:

2023-11-22 19:48:33.877383 +0000

*/

 



answered Nov 22, 2023 by avibootz

Related questions

...