I have a QDateEdit
in my GUI from which I convert the QDate
to QString
and add it to my database. The QString
date is saved in the database in this format: 20/12/2015.
In case a user want to edit the date, then I need to show the date on the QDateEdit
field on the GUI again. Hence, I need to fetch the database, bring back the date (which is in QString
format) and convert it to QDate
back again in order to put it on the QDateEdit
field on the GUI.
However, I cannot manage to convert that QString
format (i.e.: 20/12/2015) to QDate
using the following:
QString date_string_on_db = "20/12/2015";
QDate Date;
Date.fromString(date_string_on_db,"dd/MM/YYYY");
The Date
is always returning invalid
.
what should I do ?
The following piece of code will demonstrate this point. QString date_string_on_db = "20/12/2015"; QDate Date = QDate::fromString(date_string_on_db,"dd/MM/yyyy"); By examining a variety of different samples, we were able to resolve the issue with the Qdate From String Example directive that was included.
QDate::QDate(int y, int m, int d) Constructs a date with year y, month m and day d. The date is understood in terms of the Gregorian calendar. If the specified date is invalid, the date is not set and isValid() returns false .
The system date (QDATE) system value indicates the year, the month, and the day on the system. This value is made up of the QYEAR, QMONTH, and QDAY system values. The format in which QDATE appears is specified by the QDATFMT system value. You can change the system date.
First of all, the format string should be dd/MM/yyyy
. Qt documentation for the QDate
class says that yyyy
is recognized as a four digit year number.
Second of all, fromString
is a static
function that returns a new QDate
. Currently, the return value of that function is discarded : it is not written back into the Date
variable, as you might think. The complete correct code should therefore look like this :
QString date_string_on_db = "20/12/2015";
QDate Date = QDate::fromString(date_string_on_db,"dd/MM/yyyy");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With