QDate - wrong year

2.6k Views Asked by At

I have the following situation:

   QDate fixDate = QDate::fromString(QString("270912"), "ddMMyy");

the year returned is 1912. I do not understand why and how get the correct year.

Thanks in advance

3

There are 3 best solutions below

2
On BEST ANSWER

Qt always interprets a two-digit year as 19yy. So it's best to modify the input string to look like YYYY.

Note: parsing it as YY and adding 100 years fails on Feb 29, 2000. '22900' is seen as February 29, 1900, but - surprise! - in the Gregorian calendar 1900 is not a leap year. So you get an invalid QDate, which remains invalid after adding 100 years to it.

2
On

As described in the docs:

For any field that is not represented in the format the following defaults are used:
Year 1900
Month 1
Day 1

// For example:
QDate::fromString("1.30", "M.d");           // January 30 1900
QDate::fromString("20000110", "yyyyMMdd");  // January 10, 2000

(Excuse the formatting, it's in a table in the docs). So you are going to have to pass the full year into the method until Qt decide 2012 is far enough into the century to change the default...

0
On

Could you use ddMMyyyy instead of ddMMyy? Or you need date in this format?

Look here for more information about fromString method