v78*_*v78 0 c++ user-interface qt datetime
我需要QDateTime从格式中获取一个对象"hh:mm:ss".哪个年,月,日应该从当前日期开始?
除了预先yyyy-mm-dd输入字符串之外,是否有人建议任何更清洁的解决方案.
您可以使用获取当前日期/时间QDateTime::currentDateTime(),然后使用setTime()设置所需的时间:
QDateTime dateTime= QDateTime::currentDateTime();
dateTime.setTime(QTime::fromString("11:11:11", "hh:mm:ss"));
为了QDateTime在输入字符串的格式为时获取对象"MM/dd hh:mm:ss",在将年份设置为当前年份时,我会执行以下操作:
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,直到它被分配到最后一行中的当前年份.