regexqtqdatetimeqdate

Problems to convert a QString to QDateTime


i have a problem to convert a QString to a QDataTime-Object.

The String looks like: "2008:09:23 14:18:03 and have a length of 20. The Problem is, if i remove the first character the output looks like: "008:09:23 14:18:03.

That's wrong with it? Can i delete all characters without the numbers?

The code:

        QDateTime date;
        QString d=QString::fromStdString(result.val_string);
        date.fromString(d,"yyyy:MM:dd hh:mm:ss");
        qDebug()<<d;
        qDebug()<<d.length()<<date.toString();

And the output:

 "008:09:23 14:18:03
 19 "" 

Greetings


Solution

  • The double quotes are printed by the qDebug, they are not included in the QString itself. However, it seems that you have some non-printable character at the end of the original string which deletes the closing " sign. Try to copy only first 19 characters into the QString:

        QString d = QString::fromStdString(result.val_string.substr(0, 19));
        date.fromString(d,"yyyy:MM:dd hh:mm:ss");
        qDebug()<<d;
        qDebug()<<d.length()<<date.toString();
    

    EDIT QDateTime.fromString is the static method returning the QDateTime object - it will not modify the object itself!

    QDateTime date;
    std::string val_string = "2008:09:23 14:18:03";
    QString d = QString::fromStdString(val_string.substr(0, 19));
    date = QDateTime::fromString(d,"yyyy:MM:dd HH:mm:ss");
    qDebug()<<d;
    qDebug()<<d.length()<<date.toString();