gpt4 book ai didi

c++ - QDateTime : add current year automatically

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:25 25 4
gpt4 key购买 nike

我需要从 "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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com