Search code examples
c++qtqtime

QTime how to add/substract time QT/C++


I'm trying to add/substract time in a QTime object.

QString time = "10:00:00";
QTime tobj = QTime::fromString(currentTime,"hh:mm:ss");
tobj.addSecs(3600);
qDebugs() << "time:" << tobj;

I would expect the debugger to output "11:00:00", but it just stays "10:00:00", why is this and what am i over looking?


Solution

  • Your problem is addSecs() is a const function: https://doc.qt.io/qt-5/qtime.html#addSecs It does not modify the object but returns a new QTime object.

    One way to solve this is to do the following:

    QString time = "10:00:00";
    QTime tobj = QTime::fromString(time,"hh:mm:ss").addSecs(3600);
    qDebugs() << "time:" << tobj;
    

    Here I chained the output of QTime::fromString(time,"hh:mm:ss") with your call to addSecs(3600) the value set to tobj will be 1 hour ahead of the time.