MFC获取系统当前时间

1.使用CTime类   

CString str; //获取系统时间   

CTime tm;

tm=CTime::GetCurrentTime();   

str=tm.Format("现在时间是%Y年%m月%d日 %X");

//CString strTime = t.Format(_T( "%Y-%m-%d %H:%M:%S"));

MessageBox(str,NULL,MB_OK);

2: 得到系统时间日期(使用GetLocalTime)  

 

SYSTEMTIME st;   

CString strDate,strTime;   

GetLocalTime(&st);   

strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);   

strTime.Format("%2d:%2d:%2d",st.wHour,st.wMinute,st.wSecond);

3.使用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);


  1. 在定时器中添加代码,定时器设置成一秒一次。

    CTime t = CTime::GetCurrentTime(); 

    CString strTime = t.Format(_T( "%Y-%m-%d %H:%M:%S"));

  2. 在界面上加一个编辑控件或者静态文本控件,再添加代码将 strTime 显示到控件中。

    SetDlgItemText(IDD_YOURCTRL, strTime);


新建一个基于对话框的MFC程序,设置都取默认值。

一、在“OnInitDialog()”函数的“return TRUE;”前加上以下代码:

SetTimer(1, 1000, NULL);

二、添加 WM_TIMER 消息映射(不要告诉我你不会-_-||),然后在OnTimer函数里添加以下代码:

CTime tm = CTime::GetCurrentTime();
CString str = tm.Format("%H:%M:%S");
SetWindowText(str); // 设置对话框的标题为当前时间

另:
OnTimer函数是使用类向导添加的。添加方法如下:
按“Ctrl+W”打开“MFC ClassWizard”对话框,
在“Message Maps”页,“Project”下拉框应该就一个工程,
“Class Name”下拉框选名称为“C***Dlg”的,
“Object IDs”列表框也选名称为“C***Dlg”的,
“Messages”列表框里选择“WM_TIMER”,
然后点右边的按钮“Add Function”,再点“Edit Code”,
就会自动添加OnTimer函数并定位到OnTimer函数里。


其实很简单 就是建立一个 dialog 工程

然后 添加 WM_TIMER函数 一次性搞定

我可以给你源码 MFC的东西 不看整个工程很难搞清楚的

至于说的在OnInitDialog中 添加SetTimer(100,1000,NULL);

其实意思是在程序运行时调用 SetTimer(100,1000,NULL);函数

原文地址:https://www.cnblogs.com/wxl845235800/p/7426183.html