1

When im running the following code the qdatetime is invalid:

QString dateString = QString(__DATE__).simplified();
QDateTime date =  QDateTime::fromString(dateString, "MMM d yyyy");
qDebug() << "Build date " << date.toMSecsSinceEpoch();

The content of dateString = Jul 14 2020 so there are no extra spaces. Why is it not working. The following code works fine:

qDebug() << "Build date 2" << QDateTime(QLocale("en_US").toDate(QString(__DATE__).simplified(), "MMM d yyyy")).toMSecsSinceEpoch();

It has the same date format and is also based on __DATE__.

The output is:

Build date  -3600000
Build date 2 1594677600000

My Complete code:

#include <QCoreApplication>
#include <QDate>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString dateString = QString(__DATE__).simplified();
    QDateTime date =  QDateTime::fromString(dateString, "MMM d yyyy");
    qDebug() << "Build date " << date.toMSecsSinceEpoch();    
    qDebug() << "Build date 2" << QDateTime(QLocale("en_US").toDate(QString(__DATE__).simplified(), "MMM d yyyy")).toMSecsSinceEpoch();

    return a.exec();
}

I am running on ubuntu 18.04.

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

1 Answers1

2

From QDateTime::fromString() (Qt 5.12) documentation:

Note: Unlike the other version of this function, day and month names must be given in the user's local language. It is only possible to use the English names if the user's language is English.

Your system locale must be something other than English, so that's why it fails to work.

Waqar
  • 8,558
  • 4
  • 35
  • 43