# Blog

## Calculating the difference between two QDates

I wanted to calculate the difference between two QDates. Not only the days, but also the years, months, and weeks (for use in KPhotoAlbum).

I ended up using the following algorithm:

```struct DateDifference {
int years;
int months;
int days;
};

DateDifference Utilities::dateDifference(const QDate &date, const QDate &reference)
{
if (date > reference) {
return dateDifference(reference, date);
}

int years = reference.year() - date.year();
int months = reference.month() - date.month();
if (reference.month() < date.month()
|| ((reference.month() == date.month()) && (reference.day() < date.day()))) {
years--;
months += 12;
}
if (reference.day() < date.day()) {
months--;
}

int remainderMonth = reference.month() - (reference.day() < date.day());
int remainderYear = reference.year();
if (remainderMonth == 0) {
remainderMonth = 12;
remainderYear--;
}
int days = QDate(remainderYear, remainderMonth, date.day()).daysTo(reference);

return DateDifference { years, months, days };
}
```

Perhaps, this will help somebody.

I also filed a Feature request about adding such a function to Qt directly. Hopefully, it will be added in Qt 5.14 (to the new QCalendar class) :-)