【46】MFC入门到精通——MFC显示实时时间,获取系统当前时间GetCurrentTime()、获取本地时间GetLocalTime()

文章目录

1 MFC获取时间方法

方法一:获取系统当前时间GetCurrentTime()

cpp 复制代码
//方法一,获取系统当前时间
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()

cpp 复制代码
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()获取程序运行时间

cpp 复制代码
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 获取时间

cpp 复制代码
//方法一,获取系统当前时间
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();中添加代码

cpp 复制代码
	//显示当前时间
	Current_Time();
	//1秒触发一次的定时器 
	SetTimer(1, 1000, NULL);

2.4 定时器函数 调用 获取时间函数

cpp 复制代码
void CSerialPortDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	if (nIDEvent == 1) {
		Current_Time();
	}
	CDialogEx::OnTimer(nIDEvent);
}

2.5 效果演示

参考链接 :

MFC--在窗口状态栏设置时间显示

MFC中设置静态文本框的时间

MFC获取时间的几种方法

相关推荐
星火开发设计2 小时前
C++ queue 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识·队列
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——力扣 394 题:字符串解码
数据结构·c++·结构与算法
txinyu的博客2 小时前
结合游戏场景理解,互斥锁,读写锁,自旋锁,CAS / 原子变量,分段锁
开发语言·c++·游戏
hugerat2 小时前
在AI的帮助下,用C++构造微型http server
linux·c++·人工智能·http·嵌入式·嵌入式linux
-森屿安年-3 小时前
unordered_map 和 unordered_set 的实现
数据结构·c++·散列表
九久。3 小时前
手动实现std:iterator/std:string/std::vector/std::list/std::map/std:set
c++·stl
小羊羊Python3 小时前
Sound Maze - 基于 SFML+C++14 的音效迷宫开源游戏 | MIT 协议
c++·游戏·开源
txinyu的博客3 小时前
HTTP服务实现用户级窗口限流
开发语言·c++·分布式·网络协议·http
代码村新手3 小时前
C++-类和对象(上)
开发语言·c++
txinyu的博客3 小时前
map和unordered_map的性能对比
开发语言·数据结构·c++·算法·哈希算法·散列表