Important: Please read the Qt Code of Conduct -

QDate::fromString not working correctly?

  • As you can see from the screenshot the dates for days 1 & 2 do not get build, any ideeas as to why?0_1503751588399_datefromstring.png

  • Hi! This behavior of QDate::fromString is indeed unsatisfying but it's documented as such, see QDate Class:

    The expressions that don't expect leading zeroes (d, M) will be greedy. This means that they will use two digits even if this will put them outside the accepted range of values and leaves too few digits for other sections. For example, the following format string could have meant January 30 but the M will grab two digits, resulting in an invalid date:
    QDate date = QDate::fromString("130", "Md"); // invalid

    Anyway, there is no need to construct a string in the first place, just use this constructor.

  • Used fromString method as I used it previously in other places where I received the date in a specific format and didn't thought to look into the constructors.

    Thanks a lot mate, it works correctly now.

  • @adutzu89 Don't forget to check for errors:

    #include <QCoreApplication>
    #include <QJsonObject>
    #include <QJsonValue>
    #include <QDate>
    #include <QString>
    #include <QDebug>
    int getInteger(QJsonObject const &jsonObject, QString const &name)
        auto const jsonValue = jsonObject.value(name);
        if (jsonValue.isDouble()) {
            auto const s = QString::number(jsonValue.toDouble());
            auto ok = false;
            auto const v = s.toInt(&ok);
            if (ok)
                return v;
        throw 666;
    QDate getDate(QJsonObject const &jsonObject)
        QDate const date(getInteger(jsonObject, "year"),
                         getInteger(jsonObject, "month"),
                         getInteger(jsonObject, "day") );
        if (date.isValid())
            return date;
        throw 666;
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        QJsonObject const jsonObject{
            {"year", 2017},
            {"month", 9},
            {"day", 1} };
        qDebug() << getDate(jsonObject);
        return 0;

  • @Wieland

    Thanks for the tip.

Log in to reply