天天看點

VC++程式設計中擷取系統時間

<span style="white-space:pre">	</span>總結了在程式中如何獲得系統時間的方法
           
void CGetSystenTimeDlg::OnBnClickedGettimeButton()
{
	// TODO: 在此添加控件通知處理程式代碼
	//方法一  使用MFC的CTime類
	CString str; //擷取系統時間  
	CTime tm; tm=CTime::GetCurrentTime();   
	str=tm.Format("現在時間是%Y年%m月%d日 %X"); MessageBox(str,NULL,MB_OK); 

	方法二  使用win32定義得結構體
	SYSTEMTIME time;
	CString str1,str2;
	GetLocalTime(&time);  //Windows API 函數,用來擷取當地的目前系統日期和時間。
	str1.Format(L"%d-%d-%d",time.wYear,time.wMonth,time.wDay);
	str2.Format(L"%2d:%2d:%2d",time.wHour,time.wMinute,time.wSecond);
	MessageBox(str1,NULL,MB_OK);
	MessageBox(str2,NULL,MB_OK);

	//方法三:GetTickCount傳回(retrieve)從作業系統啟動所經過的毫秒數
	//,它的傳回值是DWORD。 可以用它來測量程式的運作時間
	CString str3;
	long t1=GetTickCount();//程式段開始前取得系統運作時間(ms)   
	Sleep(500); 
	long t2=GetTickCount();//程式段結束後取得系統運作時間(ms)   
	str3.Format(L"time:%dms",t2-t1);//前後之差即 程式運作時間   
	AfxMessageBox(str3);//擷取系統運作時間    即休眠的的時間 
	
	 
	 //從作業系統啟動所經過的時間
	 long t=GetTickCount();
	 CString str4;
	 CString str5;
	 str4.Format(L"系統已運作 %d時",t/3600000); 
	 str5=str5+str4;
	// MessageBox(str4,NULL,MB_OK);
	 t%=3600000;
	 
	 str4.Format(L"系統已經運作 %d分",t/60000);
	 str5=str5+str4;
	 t%=60000;
	 str4.Format(L"系統已經運作 %d秒",t/1000);
	 str5=str5+str4;
	 
	 MessageBox(str5,NULL,MB_OK);


}
           

方法一:

VC++程式設計中擷取系統時間

方法二:

VC++程式設計中擷取系統時間
VC++程式設計中擷取系統時間

方法三:

VC++程式設計中擷取系統時間