c++qtqdatetime

Can not convert QString to QDateTime


I have to convert QString to QDateTime by QDateTime::fromString method. I have QString object which contains "Wed, 13 Jun 2018 12:52". But when I use it QDateTime::fromString returns invalid object and I don't knew why. I use "ddd, MM-MMM-yyyy HH:MM" format. Could anyone tell me what I doing wrong?

My code:

QString tempDate; //Wed, 13 Jun 2018 12:52
QDateTime::fromString(tempDate, "ddd, MM-MMM-yyyy HH:MM"); //returns invalid obj

Solution

  • Your QDateTime format does not correspond to your input string.

    Wed, 13 Jun 2018 12:52 should be matched with ddd, dd MMM yyyy HH:mm.

    See QDateTime::fromString.

    Also, make sure you're using the correct locale when doing the conversion, as ddd and MMM are localized. Either change the local with QLocale::setDefault, or with QLocale::toDateTime:

    QLocale(QLocale::English).toDateTime(tempDate, "ddd, dd MMM yyyy HH:mm");