Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"))
myfile.remove();

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

myfile.close();
}

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?
Thanks
Paolo

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 modulo 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading