Esocoder
Esocoder

Reputation: 1061

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 overlooking?

Upvotes: 1

Views: 1554

Answers (2)

Rouhollah Ahmadi
Rouhollah Ahmadi

Reputation: 17

For subtraction, use a minus sign with the addSecs method, such as:

QTime time(15, 0, 0);             // time == 15:00:00
QTime newTime;
newTime = time.addSecs(3600);     // time == 16:00:00
newTime = time.addSecs(-3600);    // time == 14:00:00

Upvotes: -2

drescherjm
drescherjm

Reputation: 10847

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.

Upvotes: 4

Related Questions