c++ - QDateTime : add current year automatically

标签 c++ qt user-interface datetime

我需要从 "hh:mm:ss" 格式中获取一个 QDateTime 对象。从当前日期算起年、月、日应该从哪里开始?

除了在输入字符串前添加 yyyy-mm-dd 之外,有人会建议任何更简洁的解决方案吗?

最佳答案

您可以使用 QDateTime::currentDateTime() 获取当前日期/时间, 然后使用 setTime()设置你想要的时间:

QDateTime dateTime= QDateTime::currentDateTime();
dateTime.setTime(QTime::fromString("11:11:11", "hh:mm:ss"));

编辑:

当输入字符串的格式为"MM/dd hh:mm:ss"时,为了得到一个QDateTime对象,同时设置年份为当前年,我会做这样的事情:

QDateTime dateTime= QDateTime::fromString("12/17 11:11:11", "MM/dd hh:mm:ss");
//get current date
QDate currentDate= QDate::currentDate();
//get read date
QDate readDate= dateTime.date();
//assign new date by taking year from currentDate, month and days from readDate
dateTime.setDate(QDate(currentDate.year(), readDate.month(), readDate.day()));

请注意,当输入格式中不存在字段时,QDateTime::fromString()使用一些默认值。在本例中,年份设置为 1900,直到在最后一行将其指定为当前年份。

关于c++ - QDateTime : add current year automatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188043/

相关文章:

c++ - const string 丢弃限定符

c++ - Qt 和 Windows 可执行版本信息

c++ - Qt - 需要递归重绘,怎么样?

c# - 修改控件模板时保留控件的主题风格

android - 从另一个线程更新 UI 时 View.GONE 与 View.INVISIBLE

c++ - 将Rust项目链接到与其他cmake项目链接的cmake项目

c++ - 尝试使用 uint*& 作为 const 单元 *& 失败 : invalid initialization of reference of type ‘const uint8_t*&’ from expression of type ‘uint8_t*

c++ - Unchecked 和 Checked 的作用是什么?

c++ - 如何设置QXmlStreamReader atStart?

python - 在 Python 中逐行打印输出到 GUI