文章目錄
- 1 MFC獲取時間方法
- 方法一:獲取系統當前時間GetCurrentTime()
- 方法二:獲取本地時間GetLocalTime()
- 使用GetTickCount()獲取程序運行時間
- 2 MFC顯示實時時間 使用方法
- 2.1 獲取時間
- 2.2 類向導 添加定時器函數 OnTimer
- 2.3 初始化 設置定時器
- 2.4 定時器函數 調用 獲取時間函數
- 2.5 效果演示
1 MFC獲取時間方法
方法一:獲取系統當前時間GetCurrentTime()
//方法一,獲取系統當前時間
int CSerialPortDlg::Current_Time()
{//方法一,獲取系統當前時間CTime time;//實例一個時間對象CString strTime;//顯示時間time = CTime::GetCurrentTime();//獲取系統當前時間//strTime = time.Format(_T("%Y - %m - %d %H: %M : %S"));//將time對象中的時間信息(年,月,日,時,分,秒)存儲到CString變量中進行顯示strTime = time.Format(_T("當前時間 %H:%M:%S"));//顯示SetDlgItemText(IDC_STATIC_CurrentTime, strTime);return 0;
}
方法二:獲取本地時間GetLocalTime()
int CSerialPortDlg::Current_Time()
{//方法二,獲取本地時間精確到毫秒 CString strTime;SYSTEMTIME lpsystime;GetLocalTime(&lpsystime);//strTime.Format(L"%d-%d-%d %d:%d:%d:%d", lpsystime.wYear, lpsystime.wMonth, lpsystime.wDay, lpsystime.wHour,lpsystime.wMinute, lpsystime.wSecond, lpsystime.wMilliseconds);strTime.Format(L"當前時間 %d:%d:%d", lpsystime.wHour,lpsystime.wMinute, lpsystime.wSecond);//顯示SetDlgItemText(IDC_STATIC_CurrentTime, strTime);return 0;
}
使用GetTickCount()獲取程序運行時間
long t1=GetTickCount();//程序段開始前取得系統運行時間(ms)
Sleep(500); long t2=GetTickCount();//程序段結束后取得系統運行時間(ms)
str.Format("time:%dms",t2-t1);//前后之差即 程序運行時間
AfxMessageBox(str);//獲取系統運行時間
long t=GetTickCount();
CString str,str1;
str1.Format("系統已運行 %d時",t/3600000);
str=str1; t%=3600000;
str1.Format("%d分",t/60000);
str+=str1; t%=60000;
str1.Format("%d秒",t/1000);
str+=str1;
AfxMessageBox(str);
2 MFC顯示實時時間 使用方法
2.1 獲取時間
//方法一,獲取系統當前時間
int CSerialPortDlg::Current_Time()
{//方法一,獲取系統當前時間CTime time;//實例一個時間對象CString strTime;//顯示時間time = CTime::GetCurrentTime();//獲取系統當前時間//strTime = time.Format(_T("%Y - %m - %d %H: %M : %S"));//將time對象中的時間信息(年,月,日,時,分,秒)存儲到CString變量中進行顯示strTime = time.Format(_T("當前時間 %H:%M:%S"));//顯示SetDlgItemText(IDC_STATIC_CurrentTime, strTime);return 0;
}
2.2 類向導 添加定時器函數 OnTimer
2.3 初始化 設置定時器
在OnInitDialog();
中添加代碼
//顯示當前時間Current_Time();//1秒觸發一次的定時器 SetTimer(1, 1000, NULL);
2.4 定時器函數 調用 獲取時間函數
void CSerialPortDlg::OnTimer(UINT_PTR nIDEvent)
{// TODO: 在此添加消息處理程序代碼和/或調用默認值if (nIDEvent == 1) {Current_Time();}CDialogEx::OnTimer(nIDEvent);
}
2.5 效果演示
參考鏈接 :
MFC–在窗口狀態欄設置時間顯示
MFC中設置靜態文本框的時間
MFC獲取時間的幾種方法