CString str;
CTime tm = CTime::GetCurrentTime(); // 取得目前時間
str = tm.Format(_T("現在時間是 %Y年%m月%d日 %X"));
MessageBox(str, NULL, MB_OK);
Format 格式化字串支援 %Y 年、%m 月、%d 日、%X 完整時間等。
SYSTEMTIME st;
GetLocalTime(&st);
CString strDate, strTime;
strDate.Format(_T("%04d-%02d-%02d"), st.wYear, st.wMonth, st.wDay);
strTime.Format(_T("%02d:%02d:%02d"), st.wHour, st.wMinute, st.wSecond);
// st.wMilliseconds 可取得毫秒
適合需高精度或非 MFC 專案。
long t1 = GetTickCount();
Sleep(500); // 模擬耗時操作
long t2 = GetTickCount();
CString str;
str.Format(_T("time: %d ms"), t2 - t1);
AfxMessageBox(str);
long 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 回傳 DWORD,約 49.7 天溢位歸零,長期運行系統需改用 GetTickCount64 (Vista+) 或 QueryPerformanceCounter。
| 需求 | 推薦方法 | 備註 |
|---|---|---|
| 顯示人類可讀的日期時間 | CTime / GetLocalTime | CTime 依賴 MFC;GetLocalTime 純 API |
| 高精度效能計時 (微秒級) | QueryPerformanceCounter | 硬體計數器,精度最高 |
| 簡易程式區段計時 | GetTickCount | 毫秒精度,注意溢位 |
| 系統啟動時長 | GetTickCount64 | 解決 49 天溢位問題 |