CTime 是 MFC 封裝的時間類,提供直觀的時間操作接口。獲取當前系統時間並格式化輸出:
CString str;
CTime tm = CTime::GetCurrentTime(); // 靜態成員函數獲取當前時間
str = tm.Format(_T("現在時間是 %Y 年 %m 月 %d 日 %X"));
AfxMessageBox(str);
Format 方法支持豐富的格式化字符:%Y 四位年、%m 雙位月、%d 雙位日、%H 24 制時、%M 分、%S 秒、%X 等效於 %H:%M:%S。
Win32 API GetLocalTime 填充 SYSTEMTIME 結構,提供毫秒級精度的各時間分量:
SYSTEMTIME st;
CString strDate, strTime;
GetLocalTime(&st); // 獲取本地時間
strDate.Format(_T("%04d-%02d-%02d"), st.wYear, st.wMonth, st.wDay);
strTime.Format(_T("%02d:%02d:%02d"), st.wHour, st.wMinute, st.wSecond);
// strDate 如 "2024-01-15",strTime 如 "14:30:05"
SYSTEMTIME 結構包含:wYear、wMonth、wDay、wHour、wMinute、wSecond、wMilliseconds、wDayOfWeek。
GetTickCount 返回系統啟動以來經過的毫秒數(DWORD,約 49.7 天溢出一次),適用於短時長測量。
DWORD t1 = GetTickCount(); // 開始前
Sleep(500); // 模擬耗時操作
DWORD t2 = GetTickCount(); // 結束後
CString str;
str.Format(_T("time: %d ms"), t2 - t1);
AfxMessageBox(str);
DWORD t = GetTickCount();
CString str, str1;
str1.Format(_T("系統已運行 %d 時"), t / 3600000);
str = str1;
t %= 3600000;
str1.Format(_T("%d 分"), t / 60000);
str += str1;
t %= 60000;
str1.Format(_T("%d 秒"), t / 1000);
str += str1;
AfxMessageBox(str);
注意: 系統長時間運行導致 GetTickCount 溢出時,時間計算會出錯。需高精度或長時長計時,建議使用 QueryPerformanceCounter / QueryPerformanceFrequency 或 GetTickCount64(Vista+)。