问题描述:
已知日期,格式为mm-dd-yyyy(月-日-年,如2003年9月10日为:9-10-2003),给定一个天数(如100天),计算:从该日期算起,经过给定天数之后的日期。
主要思想:
1、当给定的天数days大于或等于365(或366)时,计算目标年份
2、当给定的天数days小于365(或366)时,计算目标年份中的月份
3、当剩余天数不足一月时,计算目标年、月份中的天数
输入:起始日期:mm-dd-yyyy 与给定天数 days
输出:目标日期:mm-dd-yyyy
要点:(1)闰年的计算;(2)当月份或天数 "溢出"时的处理(如天数增加超过该月天数时应向月份进位,或月份增加超过一年所含月数(1年12个月)时则应向年份进位)。
编程实现:
#include <stdio.h>
struct Date
{
int year;
int month;
int day;
};
int normalMonthDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leapYear(int year)
{//leap year judgement
if(year %4 ==0 && year%100 !=0 || year %400 ==0)
return true;
return false;
}
Date getNewDate(Date initDate, int diffDays)
{
Date reDate = initDate;
//1.get years (days >=366 or 365)
int daysAyear = 365;
if(leapYear(reDate.year))
{//if leap year
daysAyear = 366;
}
while(diffDays/daysAyear)
{
diffDays = diffDays - daysAyear;
reDate.year ++;
if(leapYear(reDate.year))
{
daysAyear = 366;
}
}
//2.get months (days < 366 or 365)
if(leapYear(reDate.year))
{
normalMonthDays[2]=29;
}
while(diffDays/normalMonthDays[reDate.month])
{
diffDays = diffDays - normalMonthDays[reDate.month];
reDate.month++;
if(reDate.month >= 13)
{
reDate.year++;
if(leapYear(reDate.year))
{
normalMonthDays[2]=29;
}
reDate.month = reDate.month%12;
}
}
//3.get days
if(leapYear(reDate.year))
{
normalMonthDays[2]=29;
}
if(diffDays + reDate.day <= normalMonthDays[reDate.month])
reDate.day = diffDays + reDate.day;
else
{
reDate.day = diffDays + reDate.day - normalMonthDays[reDate.month];
reDate.month++;
if(reDate.month > 12)
{
reDate.year++;
reDate.month = reDate.month%12;
}
}
return reDate;
}
int main(void)
{
Date initDate;
int diffDays=0;
scanf("%d-%d-%d",&initDate.month, &initDate.day, &initDate.year);
scanf("%d", &diffDays);
Date reDate = getNewDate(initDate, diffDays);
printf("%d-%d-%d\n",reDate.month, reDate.day, reDate.year);
return 0;
}