C++中的Qt-Qdate函数与年份的问题



简单的问题:我想在文件中写入当前日期。以下是我的代码:

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

当我阅读该文件时,我发现一个字节表示日期(0x18表示24日(,一个字节代表月份(0x02表示2月((,还有一个错误的字节表示年份(0xe6表示2022(。我需要今年的最后两个数字(例如:2022->22(。我该怎么办?谢谢Paolo

2022在十六进制中是0x7E6,当您保存将其转换为uint8时,最高有效位将被截断,以获得您所指示的值。其想法是使用模块操作员将2022转换为22,然后保存:

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

最新更新