0
点赞
收藏
分享

微信扫一扫

C++:时间日期类,增加若干秒

有态度的萌狮子 2022-01-17 阅读 42
c++

问题:

代码: 

#include<iostream>
using namespace std;
//自定义的日期类 
class DateType
{
	public:
		//年,月,日 
		int year,month,day;
		void PrintDate()
		{
			cout<<year<<"-"<<month<<"-"<<day;
		}
};
//自定义的时间类 
class TimeType
{
	public:
		//时,分,秒 
		int hour,minute,second;
};
//自定义的日期时间类 DateTimeType
class DateTimeType
 {  
 	//类 DateType 的类对象 date 作为其数据成员
	DateType date; 
	//类 TimeType 的类对象 time 作为其另一个数据成员
	TimeType time; 
	public:
		//构造函数,设定 DateTimeType 类对象的日期时间,并为各参数设置了默认值
		DateTimeType(int y0=1, int m0=1, int d0=1, int hr0=0, int mi0=0, int se0=0);
		//返回本类的私有数据对象 data
		DateType& GetDate()
		{ 
			return date; 
		} 
		//返回本类的私有数据对象 time
		TimeType& GetTime()
		{ 
			return time; 
		} 
		//增加若干秒,注意“进位”问题
		void IncrementSecond(int s);  
		//屏幕输出日期时间对象的有关数据
		void PrintDateTime(); 
};
//构造函数,设定DateTimeType类对象的日期时间 
DateTimeType::DateTimeType(int y0, int m0, int d0, int hr0, int mi0, int se0)
{
	date.year=y0;
	date.month=m0;
	date.day=d0;
	time.hour=hr0;
	time.minute=mi0;
	time.second=se0;
}

void DateTimeType::IncrementSecond(int s)
{
	int mon[13],temp,m=date.month;
	//每个月份的天数 
    mon[1]=mon[3]=mon[5]=mon[7]=mon[8]=mon[10]=mon[12]=31;
    mon[2]=28;
	mon[4]=mon[6]=mon[9]=mon[11]=30;
	//判断是否是闰年 
	if(date.year%100==0&&date.year%4==0||date.year%400==0)
		mon[2]=29;
	//增加若干秒 
    time.second+=s; 
    if(time.second>=60)
    {
    	temp=time.second/60;
    	time.minute+=temp;
    	time.second-=(60*temp);
    	if(time.minute>=60)
    	{
    		temp=time.minute/60;
    		time.hour+=temp;
    		time.minute-=(60*temp);
    		if(time.hour>=24)
    		{
    			temp=time.hour/24;
    			date.day+=temp;
				time.hour-=(24*temp);
				while(date.day>mon[date.month])
				{
					m++;
					temp=date.day/mon[date.month];
					date.day-=mon[date.month];
					if(date.month==12)
					   date.month=1;
					else date.month++;
				} 
				if(m>12)
				{
					temp=m/12;
					date.year+=temp;
				}
			}
		}
	}
}

void DateTimeType::PrintDateTime()
{
	cout<<date.year<<"-"<<date.month<<"-"<<date.day<<"  "<<time.hour<<":"<<time.minute<<":"<<time.second<<endl;
}

int main() 
{
	DateTimeType dttm1(1999,12,31,23,59,59), dttm2;
	//调用对象成员所属类的公有成员函数
	(dttm1.GetDate()).PrintDate(); 
	cout<<endl;
	//调用本派生类的成员函数 PrintDateTime
	dttm1.PrintDateTime(); 
	dttm2.PrintDateTime();
	 //调用本派生类成员函数
	dttm1.IncrementSecond(30) ;
	dttm1.PrintDateTime();
}

运行结果:

举报

相关推荐

0 条评论