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
CodePudding user response:
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);