How to format struct timeval into a printable human-readable format in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h> 
#include <sys/time.h>

int main() {
    struct timeval tv;

    gettimeofday(&tv, NULL);
    
    time_t nowtime = tv.tv_sec;
    struct tm *nowtm = localtime(&nowtime);
    
    char nowtmbuf[64];
    strftime(nowtmbuf, sizeof nowtmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
    puts(nowtmbuf);
    
    char nowtmusecbuf[128];
    snprintf(nowtmusecbuf, sizeof nowtmusecbuf, "%s.%06ld", nowtmbuf, tv.tv_usec);
    puts(nowtmusecbuf);
    
    return 0;
}
 
 
 
/*
run:

2024-11-28 14:44:20
2024-11-28 14:44:20.872068

*/

 



answered Nov 28, 2024 by avibootz
...