C语言版的
/*
给定两个日期,计算中间的天数
思路:
1、同年同月的时候,直接计算天数的差值
2、同年不同月,计算月份和天数的差值(小月到月底+大月月初到指定日期的天数+中间隔的月的天数)
3、不同年,计算小年到年尾的天数+大年年初到指定日期的天数+中间隔的年的天数
以下各函数的意义:
isLeap()判断是否为润年
swap()交换两个变量的值,始终把小的日期放在前面
daysInSameMonth(),对应于1
daysInSameYear(),对应于2
daysInDiffYear(),对应于3
数据可以用时间计算器来计算
*/
#include <stdio.h>
#include <math.h>
int allDays[12]={31,59,90,120,151,181,212,243,273,304,334,365};
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int isLeap(int year)
{
if(( year%4==0 && year%100!=0)||(year %400==0))
{
return 1;
}
return 0;
}
void swap(int *a,int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int daysInSameMonth(int d1,int d2)
{
int temp = d1-d2;
return abs(temp);
}
int daysInSameYear(int m1,int m2,int d1,int d2,int isleap)
{
int d=0,i;
if(isleap)
{
for(i=1;i<12;i++)
allDays[i]++;
days[1]++;
}
if(m1>m2)
{
swap(&m1,&m2);
swap(&d1,&d2);
}
d+=(days[m1-1]-d1);
d+=d2;
d+=(allDays[m2-2]-allDays[m1-1]);
if(isleap)
{
for(i=1;i<12;i++)
allDays[i]--;
days[1]--;
}
return d;
}
void daysInDiffYear(int y1,int y2,int m1,int m2,int d1,int d2)
{
int d=0,i,isY1leap,isY2leap;
isY1leap=isLeap(y1);
isY2leap=isLeap(y2);
if(y1>y2)
{
swap(&y1,&y2);
swap(&m1,&m2);
swap(&d1,&d2);
}
d+=daysInSameYear(m1,12,d1,31,isY1leap);
d+=daysInSameYear(1,m2,1,d2,isY2leap)+1;//这里加1,是因为1月1号在这里面
for(i=1;i<y2-y1;i++)
{
if(isLeap(y1+i))
d+=366;
else
d+=365;
}
printf("%d\n",d);
}
int main()
{
int year1,year2,month1,month2,day1,day2;
int isleap;
printf("请输入两个日期,格式为:2001-10-02 2001-12-30\n");
scanf("%d-%d-%d",&year1,&month1,&day1);
scanf("%d-%d-%d",&year2,&month2,&day2);
if(year1==year2 && month1==month2)
{
printf("%d\n",daysInSameMonth(day1,day2));
}else if(year1 ==year2)
{
isleap = isLeap(year1);
printf("%d\n",daysInSameYear(month1,month2,day1,day2,isleap));
}else
{
daysInDiffYear(year1,year2,month1,month2,day1,day2);
}
return 0;
}
下面来Java版的
private static void getDays(Date date1,Date date2) {
long diff=0;
diff = date2.getTime() - date1.getTime();
diff = diff / 1000 / 60 / 60 / 24;
System.out.println(diff);
}