Counting Days Between two dates

I'm trying to count the days between two dates. So far I am using an overloaded operator function so when it subracts it performs a series of calculations as well.
The first operator is a Date Class with the year,month,day. Basically, I make the second Date_time a constant so I cannot change the variables, and then increment the number of months and years in the first operator util it is equivalent to that of the constant. While incrementing the months, I also take a counter and add the total number of days from that month to a temporary counter. Once I actually get to the month and year.

Right now it's take really long to perform these calculations and its giving me weird numbers like -3224252233. Any thoughts?


int Date_Time::operator -(const Date_Time &right)
{
     int days_amount = 0, days_temp = 0 , max_day = 0, t_month = month, t_year = year;
 
	 if (year < right.year)
	 {
	 	while(t_year != right.year && t_month != right.month)
	 	{
			t_month = t_month + 1;
			if (t_month < 13)
			{ 
				if(t_month == 1 || t_month == 3 || t_month == 5 ||
	   			t_month == 7 || t_month == 8 || t_month == 10 ||
	   			t_month == 12)
				{
					max_day = 31;
				}	
				if (t_month == 4 || t_month == 6 || t_month == 9 || t_month == 11)
				{
					max_day = 30;
				}
				if (leap_year && t_month == 2)
				{
					max_day = 29;
				}
				else
					max_day = 28;
			
			   days_temp += max_day;
			}
			
			if (t_month == 13)
			{
				t_month = 1;
				t_year = t_year + 1;
			}	 	 
		} 
		
		if (day < right.day)
			days_amount = days_temp + abs(day - right.day);
		else 
			days_amount = days_temp - (day - right.day);	
		
		return days_amount;		
	 }
	 
	 else
	 {
		while(t_year != right.year && t_month != right.month)
	 	{
			t_month = t_month + 1;
			if (t_month > 0)
			{ 
				if(t_month == 1 || t_month == 3 || t_month == 5 ||
	   			t_month == 7 || t_month == 8 || t_month == 10 ||
	   			t_month == 12)
				{
					max_day = 31;
				}	
				if (t_month == 4 || t_month == 6 || t_month == 9 || t_month == 11)
				{
					max_day = 30;
				}
				if (leap_year && t_month == 2)
				{
					max_day = 29;
				}
				else
					max_day = 28;
			
			   days_temp += max_day;
			}
			
			if (t_month == 0)
			{
				t_month = 12;
				t_year = t_year - 1;
			}	 	 
		} 
		
		if (day > right.day)
			days_amount = (days_temp + day)- right.day;
		else 
			days_amount = (days_temp + day) + abs(day - right.day);	
		
		return days_amount;	
	}
}
There is also the method of the julian day number. Convert your two dates in julian day numbers then substract them. A 32bit julian day number should cover a wider range of time than a 32 bit time_t obtained by mktime i think

Wikipedia :
http://en.wikipedia.org/wiki/Julian_day
Topic archived. No new replies allowed.