PDA

View Full Version : Sorting a list containing QDates



Stanfillirenfro
1st May 2014, 09:17
Hello!

I want to sort a list containing QDates. After trying two ways, I could not overcome the probem. Could anyone help?
Here are my codes:

First, I used the function: qSort() as folowed:


qSort(list.benin(), list.end())

Form this code, the output is a list in which only day names are sorted. For example, if I have Mo (for monday), Fr (for friday) and Sat (for saturday), the output order is: Fr 22 2014, Mo 12 2014 and Sat 25 2014.

Second, with the following code, nothing is solved, the order for the imput is the same for the output.


for(int g = 0; g<list.size()-1; g++)
{
Date1 = list[g];

for(int l = g+1; l<list.size(); l++)
{
Date2 = list[l];

days = date1.daysTo(date2);


if(days < 0)
{

temp = date1;
date1 = date2;
date2 = temp;
}


Date2.clear();

}

Date1.clear();
}



I would appreciate any help.

Many thanks in advance!

ChrisW67
1st May 2014, 09:27
That sounds awfully like your list is a list of strings that represent dates and not QDates at all. QDate sorts correctly.


#include <QtCore>

int main(int argc, char **argv) {
QCoreApplication app(argc, argv);

QList<QDate> dates;
dates << QDate(2014, 5, 2) // Friday
<< QDate(2014, 4, 28) // Monday
<< QDate(2014, 4, 26); // Saturday

qDebug() << "Before" << dates;
qSort(dates.begin(), dates.end());
qDebug() << "After " << dates;

return 0;
}

// Before (QDate("Fri May 2 2014") , QDate("Mon Apr 28 2014") , QDate("Sat Apr 26 2014") )
// After (QDate("Sat Apr 26 2014") , QDate("Mon Apr 28 2014") , QDate("Fri May 2 2014") )

Stanfillirenfro
1st May 2014, 10:36
Thanks ChrisW67 for your reply.

It would be really good if my dates were in the format from your code, but my problem is that my dates are represented in the format:
Sa Feb 22 2014:

Assuming that I have a list of strings, I have converted these to dates as followed:


dateConverted = QDate::fromString(Date, "dd MMM dd yyyy");.

Is there any way to tranform the format of my dates to yours?

Many thanks in advance!.

Added after 1 1:

Hi, it was a bit stupid from me.

The problem is solved. I was always using QString in my list and not QDate.

Many thanks ChrisW67 for your help.

The problem is solved.