[SOLVED] Qt Qdate function in C++ problem with year


Simple question: I’d like to write current date in a file. The following is my code:

void fileWR::write()
QFile myfile("date.dat");
if (myfile.exists("date.dat"))

QDataStream out(&myfile);
out << (quint8) QDate::currentDate().day();     // OK!!
out << (quint8) QDate::currentDate().month();   // OK!!
out << (quint8) QDate::currentDate().year();    // NOT OK !!!


When I read the file, I found a byte for the day number(0x18 for 24th), a byte for month(0x02 for February)) and one wrong byte for year (0xe6 for 2022). I need the last two numbers for year (eg: 2022 -> 22).
How can I do?


2022 in hexadecimal is 0x7E6 and as you save converting it to uint8 then the most significant bits will be truncated obtaining what you indicate. The idea is to convert 2022 to 22 using the module operator and then save it:

QDataStream out(&myfile);
QDate now = QDate::currentDate();
out << (quint8) now.day();
out << (quint8) now.month();
out << (quint8) (now.year() % 100);

Answered By – eyllanesc

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *