How to get the current date and time with milliseconds accuracy in C

1 Answer

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

int main() {
    struct timeval tv;

    // Get current time with microseconds
    gettimeofday(&tv, NULL);

    // Convert to a time_t (seconds since the Epoch)
    time_t now = tv.tv_sec;

    // DateTime struct
    struct tm *tm = localtime(&now);

    // Format the datetime string with milliseconds
    char datetime_str[32];
    sprintf(datetime_str, "%04d-%02d-%02d %02d:%02d:%02d.%03d",
            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
            tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000));

    printf("%s\n", datetime_str);

    return 0;
}



/*
run:
 
2024-12-06 10:21:58.344
 
*/

 



answered Dec 6, 2024 by avibootz
...