问题描述:给出两个日期计算两者的天数距离;给出一个日期确定之周几;打印出给出年月的日历
参考:
http://blog.youkuaiyun.com/johnnyhu90/article/details/43052601
#include <iostream>
#include <cassert>
using namespace std;
//有效月份1-12
const int DAYS_EVERYMONTH[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
typedef struct
{
int year;
int month;
int day;
}date;
int which_days(date d)//该日期是本年的那一天
{
int sum_day=0;
int month_2=28;
if(d.year % 400 == 0 || ( d.year % 100 != 0 && d.year % 4 == 0) && d.month>2)
sum_day+=1;
for(int i=1;i<d.month;i++)
{
sum_day+=DAYS_EVERYMONTH[i];
}
sum_day+=d.day;
return sum_day;
}
int cmp(date d1,date d2)//是否d2的日期更靠后
{
if(d1.year==d2.year)
if(d1.month==d2.month)
return d1.day<d2.day;
else
return d1.month<d2.month;
return d1.year<d2.year;
}
int cal_day(date d1,date d2)
{
int flag=1;
if(!cmp(d1,d2))//为了防止在计算过程中出现日期为负的,所以需要处理
{
date temp=d1;
d1=d2;
d2=temp;
flag=-1;
}
int res_day=0;
if(d1.year==d2.year)
return (which_days(d2)-which_days(d1))*flag;
for(int i=d1.year;i<d2.year;i++)
{
if( i % 400 == 0 || ( i % 100 != 0 && i % 4 == 0))
res_day+=366;
else
res_day+=365;
}
res_day+=which_days(d2)-which_days(d1);
return res_day*flag;
}
int get_day_of_week(date d)
{
const date coordinate={2017,7,24};
int Week=1;
int days=cal_day(coordinate,d);
int week=(days+Week)%7;//以周日(0)开始计算
return week>=0? week:(7-abs(week));
}
void Print_calendar(date d)
{
int month_days=0;
if(d.month==2)
if(d.year%400==0 || (d.year%100!=0&&d.year%4==0))
month_days=29;
else
month_days=28;
else
month_days=DAYS_EVERYMONTH[d.month];
printf("%d-%d日历\n",d.year,d.month);
printf("Sun\tMon\tTues\tWed\tThur\tFri\tSat\n");
d.day=1;
int week=get_day_of_week(d);//本月1号周几
int i=0;
for(i=0;i<week;i++)
printf("\t");
int day=1;
while(day<=month_days)
{
printf("%d",day++);
i++;
if(i%7==0)
printf("\n");
else
printf("\t");
}
printf("\n");
}
int main()
{
date d1={2011,3,20};
date d2={2017,7,24};
cout<<"两个日期的间隔:"<<cal_day(d1,d2)<<endl;
date d3={2016,7,23};//
cout<<"2017-7-21是星期 "<<get_day_of_week(d3)<<endl;
Print_calendar(d2);
system("pause");
return 0;
}