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?
What is wrong with either my format or my input string?
To answer your question:
molbdnilo said:
May 2nd, 1923 was a Wednesday, not a Tuesday. (You're assuming the wrong century.)
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:
We currently fail to round-trip dates via such formats because 1900 is used as default year when no year is specified and (thus) 19 is used as default century number when only the later digits are (understood to be) specified. As we get further into the twenty-hundreds (as it were), this shall grow to be an increasing jarring flaw in date format handling.
Also, QDateTime::isValid() documention says:
Returns true if this datetime represents a definite moment, otherwise false.
You can confirm these findings by testing on your own example as follows:
QString format = "ddd MMM d yyyy HH:mm";
QString date = "Tue May 2 2023 00:01";
This outputs nothing because it's a valid date.
QString format = "ddd MMM d yy HH:mm";
QString date = "Wed May 2 23 00:01";
This also outputs nothing, because it's also a valid date, the remaining 2 digits of the year (left yy
) are by dafault 19
.
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: