QDateTime from string (__DATE__) invalid

匆匆过客 提交于 2020-08-09 08:15:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/62894735/qdatetime-from-string-date-invalid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!