ctime.h

How can i get UTCTime in millisecond since January 1, 1970 in c language


Is there any way to get milliseconds and its fraction part from 1970 using time.h in c language?


Solution

  • This works on Ubuntu Linux:

    #include <sys/time.h>
    
    ...
    
    struct timeval tv;
    
    gettimeofday(&tv, NULL);
    
    unsigned long long millisecondsSinceEpoch =
        (unsigned long long)(tv.tv_sec) * 1000 +
        (unsigned long long)(tv.tv_usec) / 1000;
    
    printf("%llu\n", millisecondsSinceEpoch);
    

    At the time of this writing, the printf() above is giving me 1338850197035. You can do a sanity check at the TimestampConvert.com website where you can enter the value to get back the equivalent human-readable time (albeit without millisecond precision).