hi everybody, i would like to know how to computes and returns d2 – d1
d2 is passed to the function by reference and d1 is the implied calling object; date d1 is earlier than date d2
the function returns the difference between two date objects in terms of number of days, a positive integer

#include <iostream>
using namespace std;

class date {
public:
	date();
	date(int, int, int);
	void showDate();
	date addDays(int);
    int diff(date &d2);
private:
	int year;
	int month;
	int day;
};
date::date()
{}
date::date(int mm, int dd, int yy)
{
	year = yy;
	month = mm;
	day = dd;
}
void date::showDate()
{
	cout << month << '/' << day << '/' << year % 100;
}
date date::addDays(int n)
{
	date hold = *this;	// hold must initialized to the date of the calling object
	hold.day = day + n;	// which is pointed to by the "this" pointer
	if (hold.day > 30) {
		hold.day -= 30;
		hold.month++;
	}
	if (hold.month > 12) {
		hold.month -= 12;
		hold.year++;
	}
	return hold;
}
int diff(date &d2) // this is the function that i need help with
 {
	

}
int main()
{
	date dObj(3, 10, 2010),d2,newDay;
	
	dObj.showDate();
	cout << endl;
	
	newDay = dObj.addDays(30);
	newDay.showDate();

	newDay = dObj.diff(4, 10, 2010);
	newDay.showDate();
	cout << endl;
	return 0;
}

This sort of thing is not trivial because the different months have different numbers of days and February has different numbers of days in it depending on the year. The are, at least, 2 approaches

  1. Convert the dates to the number of days past a given epoch date, 1 Jan 1970 is popular. Then you can just take the highest from the lowest. In fact many structures like this store there internal data in this form rather than as separate day/month/year. It also make comparisons and other arithmetic easy.

  2. Write an algorithm that works out the number of days left in the month of the earlier date, adds all the days in the months of the months in between the 2 dates and then adds the number of days into the month of the later date. There are all sorts of corner cases, dates in the same month for instance and short cuts, dates with whole years between them you can calculate days in the year rather than having to calculate individual months.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.