C++中获取UTC时间精确到微秒的实现代码
C++中获取UTC时间精确到微秒的实现代码
发布时间:2016-12-28 来源:查字典编辑
摘要:在日常开发过程中经常会使用到时间类函数的统计,其中获取1970年至今的UTC时间是比较常使用的,但是在windows下没有直接能够精确到微妙...

在日常开发过程中经常会使用到时间类函数的统计,其中获取1970年至今的UTC时间是比较常使用的,但是在windows下没有直接能够精确到微妙级的函数可用。本文提供方法正好可以解决这类需求问题。

下面先给出C++实现代码:

复制代码 代码如下:

#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);

}

//获取1970年至今UTC的微妙数

static time_t TimeConversion::GetUtcCaressing()

{

timeval tv;

gettimeofday(&tv);

return ((time_t)tv.tv_sec*(time_t)1000000+tv.tv_usec);

}

#endif

接下来给出使用方法:

timeval tv;

gettimeofday(&tv);

或者直接调用:GetUtcCaressing();

最后说明:本文代码在vs2008与VS2010下都进行了测试,可放心使用

附录:本文同时给出UTC时间秒级UTC获取方法代码:

复制代码 代码如下:

time_t timep;

struct tm *p;

time(&timep);

p=localtime(&timep);

timep = mktime(p);

printf("%dn",timep);

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C语言学习
热门C语言学习
编程开发子分类