Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert QString to QDate in specific format?

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 ?

like image 276
McLan Avatar asked Dec 20 '15 15:12

McLan


People also ask

How do you convert QString to QDate?

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.

How do you use QDate?

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 .

What is QDate?

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.


1 Answers

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");
like image 86
Daniel Kamil Kozar Avatar answered Sep 28 '22 08:09

Daniel Kamil Kozar