PDA

View Full Version : Problem with comparing two QDateTime objects



NoRulez
15th May 2008, 11:17
Hey @all,

i've found a misterious problem, or is this thing a bug, or i have something miss unterstood.

I created an example where a function/slot is called on a specified date and time, but the time (QTime) doesn't equal at any time.
Here is the output:

Timer started
Date is equal
QTime("11:38:00") > QTime("11:37:57")
Date is equal
QTime("11:38:00") > QTime("11:37:58")
Date is equal
QTime("11:38:00") > QTime("11:37:59")
Date is equal
QTime("11:38:00") < QTime("11:38:00") =====> Here the time must also be equal, but why not?
Date is equal
QTime("11:38:00") < QTime("11:38:01")
Date is equal
QTime("11:38:00") < QTime("11:38:02")
Date is equal
QTime("11:38:00") < QTime("11:38:03")

And here is the source where i check these things:


Example::Example(QObject *parent) : QObject(parent) {
dt.setDate(QDate(2008, 5, 15));
dt.setTime(QTime(11, 38));
int secs = 1;
int msecs = secs * 1000;
timer_check = new QTimer(this);
connect(timer_check, SIGNAL(timeout()), SLOT(doSomething()));
timer_check->start(msecs);
cout << "Timer started" << endl;
}

Example::~Example() {

}

void Example::doSomething() {
emit checkTime();
}

void Example::checkTime() {
QDateTime dt_cur = QDateTime::currentDateTime();
QTime t = dt_cur.time();
QDate d = dt_cur.date();
if(dt_cur == dt)
cout << "Time reached ;-)" << endl;
if(dt.date() == d) {
cout << "Date is equal" << endl;
}
if(dt.time() == t) {
cout << "Time is equal" << endl;
}
else {
if(dt.time() > t)
qDebug() << dt.time() << " > " << t;
else if(dt.time() >= t)
qDebug() << dt.time() << " >= " << t;
else if(dt.time() < t)
qDebug() << dt.time() << " < " << t;
else if(dt.time() <= t)
qDebug() << dt.time() << " <= " << t;
else if(dt.time() == t)
qDebug() << dt.time() << " == " << t;
else
qDebug() << dt.time() << " ?? " << t;
}
}


Why does the time/datetime doesn't match? Do I something wrong within the comparison?

Regards
NoRulez

wysota
15th May 2008, 11:27
According to me you are facing the same problem as comparing real numbers. QTime considers also miliseconds and you'll have a tough time trying to match them as well ;)

You can overcome the problem by:

QTime t1;
QTime t2;
if(t2.secsTo(t1)==0){
qDebug() << "Equal";
}