Reputation: 391
I have a program that uses two functions I have defined inside a class. My class works fine, but my program always returns an amount that is some amount of days off. There is more error when the dates are farther apart. My code is designed to in one function calculate the total amount of days since 1582, and another function subtracts the higher amount from the lesser. Where am I getting the error from? I know it may not be the most efficient way to do things (cpu wise) but can someone find where my logic is messed up? This accounts for leap years as well. I have been checking my program against a website http://www.timeanddate.com/date/durationresult.html
int Date::totalDays()
{
int totalDays = 0;
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
totalDays += day;
for (int i = month-1; i > 0; i--)
{
totalDays += daysInMonth[i];
}
for (int i = year-1; i > 1582; i--)
{
if(year % 100 == 0)
{
if(year % 400 == 0)
totalDays += 366;
else
totalDays += 365;
}
else
{
if(year % 4 == 0)
totalDays += 366;
else
totalDays += 365;
}
}
return totalDays;
}
int Date::daysBetween(Date other)
{
if (this->totalDays() > other.totalDays())
return this->totalDays() - other.totalDays();
else
return other.totalDays() - this->totalDays();
}
Thank you.
Upvotes: 0
Views: 4003
Reputation: 8695
Problem 1:
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
should be
int daysInMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
// ^^
Problem 2:
if the current year
is a leap-year, and month
is greater than 2, you'll also need to add one day to account for February 29th of the current year.
Upvotes: 3