时间是一个非常重要的信息,比如写LOG时,就需要把时间输出来,跟踪程序是什么时候出错的。或者当你开发一个银行交易系统时,就要记录当前交易的时间,以便后面可以输出报表,打印给信用卡用户。根据不同的需求,可能需要使用不同的时间,目前有UTC( Coordinated Universal Time)和本地时间。UTC是格林威治时间,也就是全球标准时间。本地时间就是相对于UTC而言的,比如中国北京是在东8区,相对于UTC就多了8个小时。一般使用到的时间都是使用本地时间,也就是调用函数GetLocalTime。
获取UTC时间:
void GetSystemTime(
LPSYSTEMTIME lpSystemTime
);
获取本地时间:
void GetLocalTime(
LPSYSTEMTIME lpSystemTime
);
二者都是Windows API ,使用样例:
#include <stdio.h>
#include <stdlib.h>
//获取 秒级时间
#include <time.h>
inline void GetDate(char* pTimeBuf, unsigned int dwSize)
{
if (pTimeBuf == NULL)
{
return;
}
time_t tTime = time(NULL);
struct tm* ptReflash = localtime(&tTime);
strftime(pTimeBuf, dwSize, "%Y-%m-%d %H:%M:%S", ptReflash);
}
//获取 毫秒级时间
#include <Windows.h>
inline void Mc_GetLocalTime(char* pTimeBuf, unsigned int dwSize)
{
if (pTimeBuf == NULL)
{
return;
}
SYSTEMTIME sys = {0};
GetLocalTime( &sys );
sprintf_s(pTimeBuf, dwSize,"%4d-%02d-%02d %02d:%02d:%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);
}
//获取 毫秒级时间
inline void Mc_GetSystemTime(char* pTimeBuf, unsigned int dwSize)
{
if (pTimeBuf == NULL)
{
return;
}
SYSTEMTIME sys = {0};
GetSystemTime( &sys );
sprintf_s(pTimeBuf, dwSize,"%4d-%02d-%02d %02d:%02d:%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);
}
int main()
{
// 本地时间
char achTimeBuf[40] = {0};
Mc_GetLocalTime(achTimeBuf, 40);
printf("\n[GetLocalTime] %s\n", achTimeBuf);
// UTC时间
Mc_GetSystemTime(achTimeBuf, 40);
printf("\n[GetSystemTime] %s\n", achTimeBuf);
//
GetDate(achTimeBuf, 40);
printf("\n[strftime] %s\n", achTimeBuf);
system("pause");
return 0;
}
结果:
注意
It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times. Instead, you should
- Convert the SYSTEMTIME structure to a FILETIME structure.
- Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
- Use normal 64-bit arithmetic on the ULARGE_INTEGER value.
The system can periodically refresh the time by synchronizing with a time source. Because the system time can be adjusted either forward or backward, do not compare system time readings to determine elapsed time. Instead, use one of the methods described in Windows Time.