C++ to get the UTC time accurate to microseconds of the implementation code

  • 2020-04-01 23:34:57
  • OfStack

Statistics of time class functions are often used in daily development, and it is common to obtain UTC time from 1970 to present, but there is no function that can be directly accurate to the subtle level available under Windows. This article provides a solution to this type of requirement problem.

So let me give you C++ implementation code :

#ifndef UTC_TIME_STAMP_H_
#define UTC_TIME_STAMP_H_

#include <windows.h>
#include <sys/timeb.h>
#include <time.h> 

#if !defined(_WINSOCK2API_) && !defined(_WINSOCKAPI_)
struct timeval
{
long tv_sec;
long tv_usec;
};
#endif

static int gettimeofday(struct timeval* tv)
{
    union {
             long long ns100;
             FILETIME ft;
    } now;
    GetSystemTimeAsFileTime (&now.ft);
    tv->tv_usec = (long) ((now.ns100 / 10LL) % 1000000LL);
    tv->tv_sec = (long) ((now.ns100 - 116444736000000000LL) / 10000000LL);

    return (0);
}
//Gets the subtleties of UTC from 1970 to the present
static time_t TimeConversion::GetUtcCaressing()
{
    timeval tv;
    gettimeofday(&tv); 
    return ((time_t)tv.tv_sec*(time_t)1000000+tv.tv_usec);
}
#endif

So let's say that Method of use :
The timeval TV;
The gettimeofday (& TV);  
Or simply call: GetUtcCaressing();

Finally: This code in vs2008 and VS2010 have been tested, can be used safely
Appendix: this paper also gives the code of UTC time and second UTC acquisition method:

time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep);
timep = mktime(p);
printf("%dn",timep); 


Related articles: