# QDate comparison

• Hi,

I'm trying to compare dates. One provide by user, QDateEdit, against what's in the database. I searched online and found daysTo(), but there is one issue using this function.

qint64 QDate::daysTo(const QDate &d) const
Returns the number of days from this date to d (which is negative if d is earlier than this date).
Returns 0 if either date is invalid.

it returns 0 if either date is invalid, which I didn't run into yet but if the dates are the same, it also returns 0. Is there any other function to use to bypass this?

• @WhatIf

Did you see the relational operators are provided for QDate?

• This post is deleted!

• @WhatIf

Both comparing dates MUST in the same format. check here. Use `fromString` .
If both dates are same then it gives the 0. If you want even to calculate the hours, minutes and seconds if the date is same then you have to use QDateTime along with some mathematical calculation.

``````QDateTime currentTime = QDateTime::currentDateTime();
QDateTime userTime = QDateTime::fromString(timefromuser, "yyyy-M-d h:m:s"); //both must be in same format.
long seconds = currentTime.secsTo(userTime);
int secondss = (int)(seconds) % 60;
int minutes = (int)((seconds / (60)) % 60);
int hours = (int)((seconds / (60 * 60)) % 24);
int days = (int)((seconds) / (60 * 60 * 24));``````

• @WhatIf said:

it returns 0 if either date is invalid, which I didn't run into yet but if the dates are the same, it also returns 0.

To different between those two scenarios, I would first check that the dates are valid, like:

``````if ((!date1.isValid()) || (!date2.isValid())) {
// do some error handling.
} else {
const qint64 days = date1.daysTo(date2);
}
``````

Cheers.