//file:date.h
#include<iostream.h>
class date
{
public:
date(){year=month=day=leapyear=pastdays=week=-1;};
date(int y,int m,int d);
int getweek(){return week;};
friend bool operator<(date& dt1,date& dt2);
friend long leapyearsbetween(date dt1,date dt2);
friend ostream& operator<<(ostream& out,date& dt);
friend long operator-(date dt1,date dt2);
date& operator+=(int days);
protected:
int year,month,day;
int leapyear,pastdays,week;
};
//file:date.cpp
#include<iomanip.h>
#include "date.h"
date::date(int y,int m,int d)
{
static int
r1[13]={0,31,28,31,30,31,30,31,31,30,31,30,31},
r2[13]={0,0,3,3,6,1,4,6,2,5,0,3,5},
r3[13]={0,0,31,59,90,120,151,181,212,243,273,304,334};
int c;
if(y<0||m<1||m>12||d<1)
{
cerr<<"Wrong Date!"<<endl;
year=month=day=leapyear=pastdays=week=-1;
return;
}
if(y%4==0&&y%100!=0||y%400==0)leapyear=1;
else leapyear=0;
if(d>r1[m]+(m==2?leapyear:0))
{
cerr<<"Wrong Date!"<<endl;
year=month=day=leapyear=pastdays=week=-1;
return;
}
year=y;month=m;day=d;//日期数据约束条件
y%=400;
if(leapyear&&m<3)c=5;
else c=6;
week=(y+y/4-y/100+r2[m]+d+c)%7;
pastdays=r3[m]+d;
if(leapyear&&m>2)++pastdays;
}
ostream& operator<<(ostream& out,date& dt)
{
out<<setw(4)<<dt.year<<"/"
<<setw(2)<<setfill('0')<<dt.month<<"/"
<<setw(2)<<setfill('0')<<dt.day;
return out;
}
bool operator<(date& dt1,date& dt2)
{
if(dt1.year<dt2.year)return true;
if(dt1.year>dt2.year)return false;
if(dt1.month<dt2.month)return true;
if(dt1.month>dt2.month)return false;
if(dt1.day<dt2.day)return true;
return false;
}
long leapyearsbetween(date dt1,date dt2)//dt1<dt2
{
long y1=dt1.year,y2=dt2.year-1;
long lys;
for(;!(y1%4==0&&y1%100!=0||y1%400==0);++y1);
if(y1>y2)return 0;
for(lys=0;y1<=y2;y1+=4)
if(y1%100!=0||y1%400==0)++lys;
return lys;
}
long operator-(date dt1,date dt2)
{
long sign=1;
if(dt1<dt2)
{date temp=dt1;dt1=dt2;dt2=temp;sign=-1;}
long lys=leapyearsbetween(dt2,dt1);
return sign*((dt1.year-dt2.year)*365+lys+dt1.pastdays-dt2.pastdays);
}
date& date::operator+=(int days)//后数天数
{
static int r[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int t;
if(days>=(t=366+leapyear-pastdays))
{
days-=t;
++year;month=day=1;
}
while(days>(t=365+leapyear))
{
days-=t;
++year;
}
while(days>=r[month]+(month==2&&leapyear?1:0))
{
days-=r[month]+(month==2&&leapyear?1:0);
++month;
}
day+=days;
if(day>r[month]+(month==2&&leapyear?1:0)){day-=r[month]+(month==2&&leapyear?1:0);++month;}
if(month>12){month=1;++year;}
return *this;
}
//file:test.cpp
#include "date.h"
void main()
{
int y,m,d;
date d1,d2;
cout<<"输入第一个日期:年月日"<<endl;
cin>>y>>m>>d;
d1=date(y,m,d);
while(1)
{
cout<<"输入后数天数:"<<endl;
cin>>d;if(d==-1)break;
d1+=d;
cout<<"到"<<d1<<endl;
}
}
正文
公历日期类2005-06-15 16:43:00
【评论】 【打印】 【字体:大 中 小】 本文链接:http://blog.pfan.cn/rickone/1852.html
阅读(5154) | 评论(2)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论