Wednesday, October 30, 2013

Qt conversion from date to qstring and from qstring to date


Qt provides very nice library to handle Date and Time. We can use them and convert from Date and Time to Qstring and vice-versa. Below is the sample code snippets providing for both conversion from date to string and string to date in Qt.

Conversion from QDateTime to QString: Below is the sample code for converting datetime to string in Qt. Qt has many string formats to retrieve day, month, year in different formats. for more info check here.

QString dateToString(QDateTime d)
{
    //these three statements just for info.
    QString day = d.toString("dd");
    QString month = d.toString("MM");
    QString year = d.toString("yyyy");

    return d.toString("dd")+"/"+d.toString("MM")+"/"+d.toString("yyyy");
}


Conversion from QString to QDateTime: Below is the sample code to convert from string to date and if the date format string is "dd/mm/yyyy". if the format is different, you need to add corresponding order to get the proper date as the code first converts the string to list using convertQDatetoList  and from list to date as below.

QVariantList convertQDatetoList(QString dateTime)
{
    QStringList tempList = dateTime.split("/");
    QVariantList dateList;
    QListIterator i(tempList);
    while(i.hasNext()) {
     dateList.append(i.next());
    }
    return dateList;
}

QDateTime setDateFromString(QString dateString)
{
 QDateTime dt;
    QVariantList dateAsList = convertQDatetoList(dateString);
    if(dateAsList.size()==3) {
     QDate t(dateAsList.at(2).toInt(),
                dateAsList.at(1).toInt(),
                dateAsList.at(0).toInt());
     dt.setDate(t);
    }
    else {
     //date format is not valid,so setting the current date
     dt = QDateTime::currentDateTime();
    }
 return dt;
}


No comments:

Popular Posts