简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM