I'm trying to parse a QString containing a custom datetime format as follows "ddd MMM d yy HH:mm".
I have the following code which produces an invalid datetime object:
QString format = "ddd MMM d yy HH:mm";
QString date = "Tue May 2 23 00:01";
QDateTime datetime = QDateTime::fromString(date, format);
if (!datetime.isValid()) {
qDebug() << "Error parsing input string:" << date;
qDebug() << "datetime:" << datetime;
return;
}
Output:
Error parsing input string: "Tue May 2 23 00:01"
datetime: QDateTime(Invalid)
What is wrong with either my format or my input string?
To answer your question:
molbdnilo said:
Which is an excellent observation, and it points out the cause of your problem.
Based on that I found this thread in which Edward Welbourne said:
Also, QDateTime::isValid() documention says:
You can confirm these findings by testing on your own example as follows:
This outputs nothing because it's a valid date.
This also outputs nothing, because it's also a valid date, the remaining 2 digits of the year (left
yy) are by dafault19.There is a solution, in which you have to add 100 years to your
datetime, I have tested it and it seems that it does not work for you case, and my best guess is that it has to do with your date format (double digit plus triple digit?).So at the moment, you might have only one solution, and that is to avoid using double digit year format.
Additional sources: