Windows程序设计——Win32下获取当前系统时间和计算两个时间差的方法

注意:

控制台需要加 #include “atltime.h” 头文件

#include "stdafx.h"
 
#include "atltime.h"
#include <iostream>
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
	CString strTime;		//用于将CTime对象格式化为字符串
	//获取当前的系统时间
	CTime curTime = CTime::GetCurrentTime();
 
	int nYear = curTime.GetYear();
	int nMonth = curTime.GetMonth();
	int nDay = curTime.GetDay();
	int nHour = curTime.GetHour();
	int nMin = curTime.GetMinute();
	int nSec = curTime.GetSecond();
 
	/* 方法一 */
	//输出当前时间
	cout << "当前时间:" << endl;
	cout << nYear << "年" << nMonth << "月" << nDay << "日" << nHour << "时" << nMin << "分" << nSec << "秒" << endl;
 
	/* 方法二 */
	//将当前时间curTime格式化为字符串
	strTime = curTime.Format(_T("%Y-%m-%d %H:%M:%S %A"));
	//出书格式化字符串,由于字符串使用Unicode字符,所以要使用wcout输出
	wcout << (LPCTSTR)strTime << endl;
 
	//为计算时间差,需要设定一个起始时间并输出
	CTime startTime = CTime(2017,10,1,10,20,10);
	cout << "起始时间" << endl;
	cout << startTime.GetYear() << "-" << startTime.GetMonth() << "-" << startTime.GetDay() << " " 
		<< startTime.GetHour() << ":" << startTime.GetMinute() << ":" << startTime.GetSecond() << endl;
 
	//计算时间差
	CTimeSpan timeSpan;
	timeSpan = curTime - startTime;
	cout << "两个时间相差:" << endl;
	cout << timeSpan.GetDays() << "天" << timeSpan.GetHours() << "小时" 
		<< timeSpan.GetMinutes() << "分" << timeSpan.GetSeconds() << "秒"<< endl;
 
	cout << "总小时数:" << timeSpan.GetTotalHours() << "小时" << endl;
	cout << "总分钟数:" << timeSpan.GetTotalMinutes() << "分钟" << endl;
	cout << "总秒数:" << timeSpan.GetTotalSeconds() << "秒" << endl;
 
	getchar();
	return 0;
}

效果图:

在这里插入图片描述

发布了71 篇原创文章 · 获赞 66 · 访问量 9410

猜你喜欢

转载自blog.csdn.net/weixin_45525272/article/details/105048463