在MFC下做开发,有时需要记录当前系统时间,使用CTime保存时间,用函数GetCurrentTime()来获取时间是个办法。但是在MFC中有2个GetCurrentTime函数,一不留神就容易混淆。
CTime currentTime = GetCurrentTime();
CTime currentTime2 = CTime::GetCurrentTime();
GetCurrentTime()在文件winbase.h中,实际执行的是GetTickCount(),这是Windows API,用来返回从系统开机到现在间隔的毫秒数,超过49天之后,将会溢出。winbase.h中对该函数宏定义如下,建议采用GetTickCount64代替GetTickCount
Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
#define GetCurrentTime() GetTickCount()
__drv_preferredFunction("GetTickCount64", "GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem")
WINBASEAPI
DWORD
WINAPI
GetTickCount(
VOID
);
CTime::GetCurrentTime() 函数的定义在atltime.inl文件中,实际通过调用::_time64()函数来获取时间
ATLTIME_INLINE CTime WINAPI CTime::GetCurrentTime() throw()
{
return( CTime( ::_time64( NULL ) ) );
}
::_time64在atltime.inl文件中定义如下,当传入的指针为NULL时,只返回系统当前时间。
/***
*__time64_t _time64(timeptr) - Get current system time and convert to a
* __time64_t value.
*
*Purpose:
* Gets the current date and time and stores it in internal 64-bit format
* (__time64_t). The time is returned and stored via the pointer passed in
* timeptr. If timeptr == NULL, the time is only returned, not stored in
* *timeptr. The internal (__time64_t) format is the number of seconds
* since 00:00:00, Jan 1 1970 (UTC).
*
*Entry:
* __time64_t *timeptr - pointer to long to store time in.
*
*Exit:
* returns the current time.
*
*Exceptions:
*
*******************************************************************************/
__time64_t __cdecl _time64 (
__time64_t *timeptr
)
{
__time64_t tim;
FT nt_time;
GetSystemTimeAsFileTime( &(nt_time.ft_struct) );
tim = (__time64_t)((nt_time.ft_scalar - EPOCH_BIAS) / 10000000i64);
if (tim > _MAX__TIME64_T)
tim = (__time64_t)(-1);
if (timeptr)
*timeptr = tim; /* store time if requested */
return tim;
}
_time64() 实际上是调用GetSystemTimeAsFileTime()来获取系统时间
GetSystemTimeAsFileTime函数在MSDN定义如下:
Retrieves the current system date and time. The information is in Coordinated Universal Time (UTC) format.
void WINAPI GetSystemTimeAsFileTime( _Out_ LPFILETIME lpSystemTimeAsFileTime );
typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *PFILETIME;
FILETIME相当于一个64位整型数,到这里就可以看出,虽然两个函数同名,但是时间上返回的时间值是不一样。
GetCurrentTime() 返回的是距离系统启动时的微秒数
CTime::GetCurrentTime() 才是返回的当前系统时间