Skip to content

Instantly share code, notes, and snippets.

@FantasticJZI
Last active October 17, 2023 03:39
Show Gist options
  • Save FantasticJZI/6f2dcd11e7cad90768e86156cb1ec51b to your computer and use it in GitHub Desktop.
Save FantasticJZI/6f2dcd11e7cad90768e86156cb1ec51b to your computer and use it in GitHub Desktop.
how many days between two date?
#include <stdio.h>
#include <stdlib.h>
int leap(int input) //閏年判斷
{
if(input%400==0)
{
return 1;
}
else if(input%4==0 && input%100!=0)
{
return 1;
}
else
return 0;
}
int headMonth(int month, int date, int year) //測資給的當月(開頭年)
{
int re=0;
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
re+=31-date;
else if(month==2 && leap(year))
re+=29-date;
else if(month==2 && !leap(year))
re+=28-date;
else if(month==4 || month==6 || month==9 || month==11)
re+=30-date;
return re;
}
int monthCount1(int month, int year)//開頭年還沒經過的月份
{
int re=0;
while(month<12)
{
month++;
if(month==2 && leap(year))
re+=29;
else if(month==2 && !leap(year))
re+=28;
else if(month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
re+=31;
else if(month==4 || month==6 || month==9 || month==11)
re+=30;
}
return re;
}
int monthCount2(int month, int year)//結尾年已經過的月份
{
int re=0,month1=1;
while(month1<month)
{
if(month1==1 || month1==3 || month1==5 || month1==7 || month1==8 || month1==10 || month1==12)
re+=31;
else if(month1==2 && leap(year))
re+=29;
else if(month1==2 && !leap(year))
re+=28;
else if(month1==4 || month1==6 || month1==9 || month1==11)
re+=30;
month1++;
}
return re;
}
int yearCount(int year1, int year2)//計算跨過的年份
{
int re=0;
while(year2+1<year1)
{
year2++;
if(leap(year2))
re+=366;
else
re+=365;
}
return re;
}
int main()
{
int year1,year2,month1,month2,date1,date2;
while(scanf("%d %d %d",&year1,&month1,&date1)==3)
{
scanf("%d %d %d",&year2,&month2,&date2);
int tmp,total=0; //先處理測資讓第一個測資一定大於第二個
if((year1<year2) || ((year1==year2) && (month1<month2)) || ((year1==year2) && (month1==month2) && (date1<date2)))
{
tmp=year1;
year1=year2;
year2=tmp;
tmp=month1;
month1=month2;
month2=tmp;
tmp=date1;
date1=date2;
date2=tmp;
}
if(year1-year2>=2)
{
total+=date1;
total+=headMonth(month2,date2,year2)+monthCount1(month2,year2)+monthCount2(month1,year1)+yearCount(year1,year2);
}
else if(year1-year2==1) //年份相差1
{
total+=date1;
total+=headMonth(month2,date2,year2)+monthCount1(month2,year2)+monthCount2(month1,year1);
}
else //同年
{
if(month1!=month2)
{
total+=date1;
total+=headMonth(month2,date2,year2);
while(month1!=month2+1)
{
month2++;
if(month2==1 || month2==3 || month2==5|| month2==7 || month2==8 || month2==10 || month2==12)
total+=31;
else if(month2==2 && leap(year2))
total+=29;
else if(month2==2 && !leap(year2))
total+=28;
else if(month2==4 || month2==6 || month2==9 || month2==11)
total+=30;
}
}
else
total+=date1-date2;
}
printf("%d\n",total);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment