Code for obtaining UTC time accurate to microsecond in C ++

Source: Internet
Author: User

In the daily development process, the statistics of time functions are often used. It is often used to obtain the UTC time from January 1, 1970 to the present, however, in windows, there is no function available that can be precise to a subtle level. This document provides a solution to this type of problem.

Next we will first giveC ++ implementationCode:Copy codeThe Code is as follows: # 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)/0000000ll );

Return (0 );
}
// Obtain the number of seconds since January 1, 1970 in UTC
Static time_t timeconversion: getutccaressing ()
{
Timeval TV;
Gettimeofday (& TV );
Return (time_t) TV. TV _sec * (time_t) 1000000 + TV. TV _usec );
}
# Endif

Next we will provideUsage:
Timeval TV;
Gettimeofday (& TV );
Or call: getutccaressing ();

Note:The code in this article has been tested in both vs2008 and vs2010, so you can use it with confidence.
Appendix: This document also provides the code for obtaining the method in seconds of UTC:Copy codeThe Code is as follows: time_t timep;
Struct TM * P;
Time (& timep );
P = localtime (& timep );
Timep = mktime (P );
Printf ("% d \ n", timep );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.