最近无聊,写了一个日期比较的C程序,发上来供大家拍砖!
#include <stdio.h>
bool isRun(int year);
int year(int year1,int year2);
int month(struct day day1,struct day day2);
int day(int day1,int day2);
struct day{
int year;
int month;
int day;
};
int main(){
int def;
struct day day1={2009,3,9},day2={1986,8,26};
if(day1.year<day2.year){
printf("输入有误,请将大数放在前面!");
}else if((day1.year==day2.year)&&(day1.month<day2.month)){
printf("输入有误,请将大数放在前面!");
}else if((day1.year==day2.year)&&(day1.month==day2.month)&&(day1.day<day2.day)){
printf("输入有误,请将大数放在前面!");
}else{
def=year(day1.year,day2.year)+month(day1,day2)+day(day1.day,day2.day);
printf("两个时间的差值为:%d",def);
}
}
//bool isRun(int year);
//返回年差数
int year(int year1,int year2){
int def = year1-year2;
int i;
int result=0;//年值
for(i=0;i<def;i++){
if(isRun(year1+i)){
//为闰年
result=result+366;
}else{
//为平年
result=result+365;
}
}
return result;
}
int monthToJanaray(int year,int month);
//返回月差数
int month(struct day day1,struct day day2){
int num1=monthToJanaray(day1.year,day1.month);
int num2=monthToJanaray(day2.year,day2.month);
return num1-num2;
}
//返回日差数
int day(int day1,int day2){
return day1-day2;
}
int yearMonthToDay(int year,int month);
//返回一年中某月到一月的天数
int monthToJanaray(int year,int month){
int i;
int day=0;
for(i=month-1;i>0;i--){
day=day+yearMonthToDay(year,i);
}
return day;
}
//bool isRun(int year);
//返回一年中一个月的天数
int yearMonthToDay(int year,int month){
int i;//一年中的某个月的天数
int leap;
int days[2][12]={
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}
};
if(isRun(year)){
//为闰年
leap=1;
}else{
//为平年
leap=0;
}
i=days[leap][month-1];
return i;
}
//判断是否闰年
bool isRun(int year){
int i =year;
if((i%4==0&&i%100== 0)||i%400==0){
//为闰年
return true;
}else{
//为平年
return false;
}
}