Date Comparison
-
Im simply trying to compare two dates...and its not working properly. Here is what im trying, but no luck. Ive tried a number of different ways, but its still failing. Regardless of which date is earlier, it always hits my "do this" logic. Im assuming the code below is failing because of the string? But Ive tried comparing them as dates too...but no luck.
What am I missing?
QString myTargetDate = QDate::currentDate().addDays(-3).toString("yyyy-MM-dd");
QString myShipDate = ui->shipDateEdit->date().toString("yyyy-MM-dd");if (myShipDate < myTargetDate);
{
do this
} -
@Scott-Krise said in Date Comparison:
Im assuming the code below is failing because of the string?
Not because of it but you should really, really keep it a
QDate
as it's infinitely more efficientit always hits my "do this" logic
As it should. The block does not depend on the
if
To solve remove the
;
at the end ofif (myShipDate < myTargetDate);
Going forward increasing the level of compiler warnings should be enough to spot these kind of problems
-
@Scott-Krise why are converting dates to string? Why not to use the less than operator directly? See here for an example...
-
Hi @Scott-Krise
As said by @Pablo-J-Rogina use the
QDate
directly. Below is the sample code.QDate date1, date2; auto result1 = (date1.currentDate() == date2.currentDate()); date1 = date1.currentDate().addDays(5); auto result2 = (date1 > date2.currentDate()); qDebug() << "result1 : " << result1 << "\nresult2 : " << result2 << endl;
Output:
result1 : true result2 : true
All the best.
-
OMG. A mis-placed semicolon. How embarassing! Ya, it makes perfect sense why it was doing what it was now that I noticed that! Thanks everyone.
Paradeep, to answer your question, I started with QDate...then when that didn't work I started trying things based on internet searches and led me to trying the string option.
The interesting when you google how to compare dates in C++ how many abstract solutions you find. It really shouldn't be that difficult!! Thanks again!
-
@Scott-Krise said in Date Comparison:
how to compare dates in C++
Well, that's the magic of Qt framework: you have a level of abstraction that also provide multi-platform solutions...
PS: please don't forget to mark your post as solved!
-
One other question. Id like to take vronin's suggestion and increase my warning level...but not sure where to do that....or what warning level you suggest?
Thanks again.