Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

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
...