C/C++标准库之转换UTC时间到local本地时间详解

2020-01-06 18:04:17王旭

下面先给出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();

UTC时间秒级UTC获取方法代码:


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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。

参考

NOTE-datetime _mkgmtime timegm - Linux man page Converting Between Local Times and GMT/UTC in C/C++
注:相关教程知识阅读请移步到C++教程频道。