Search This Blog

Monday, June 27, 2011

Days of difference Calculation

How to calculate the total days between 2 dates without using programming language specific features? At the moment I was given the question, I have no idea, because I don’t know how to get a precise day number for each year. After like 20 minutes (I react slowly sometimes), I realized that there is a solution.
I recalled in Chinese calendar there is a leap year for around every 4 years. The exact rule for leap year is a bit complex, I checked google and found some adequate to use answers. Suppose we already have a function leapyear(y) which returns 1 to indicate a year is leap year or 0 for not a leap year, we then have a solution. I put the pseudo code below,
Int function getDaysOfYear(var year)
{
Case(leapyear(year)){
Case 0: daysOfYear = 365; break;
Case 1: daysOfYear = 366; break; // leap year has 366 days
}
Return daysOfYear;
}

int function getDaysOfMonth(var month, var year)
{
If (leapyear(year) and month==2)
{
month = 0;
}
case(month) {
1, 3, 5, 7, 8, 10, 12: daysOfMonth = 31; break;
0: daysOfMonth = 29; break; // leap year’s February month only have 29 days
2: daysOfMonth = 28; break; // normal year’s February month only have 28 days
 4, 6, 9, 11: daysOfMonth = 30; break;
Other: break;
}
Return daysOfMonth;
}

Int daysOfDifference(var d1, var d2)
{
If (d1 > d2) swap(d1, d2);
// get days of all the years in between
For (int i=d1.y; i<d2.y; i++)
{
Days  += getDaysOfYear(i);
}
If (d1.m <= d2.m)
{
For (int j=d1.m; j<d2.m; j++)
{
Days += getDaysOfMonth(j);
}
} else
{
For (int j=d2.m; j<d1.m; j++)
{
Days -= getDaysOfMonth(j);
}
}
Days += d2.d – d1.d;
Return days;
}
Now we will handle the function leapyear(var year)
I’m giving a Gregorian calendar leapyear calculation method below, It is still not 100% accurate for very big years (much larger than 172800).

There are 3 rules for judging a leap year,
1.       Year can be devided by 4, but not by 100
2.       Year can be devided by 400, but not by 3200
3.       Year can be devided by both 3200 and 172800
int leapyear(int year)
{
if (((year%3200)&&(year% 172800))||((year%400==0)&&(year%3200!=0)) || (year%100!=0) && (year%4==0))
 return 1;
else
return 0;
}
Any genius answers to the days of difference question is more than welcome to add.

No comments:

Post a Comment