Łukasz Przeniosło
Łukasz Przeniosło

Reputation: 2949

How to convert seconds (double) to QDateTime in Qt?

I have a number of seconds stored in a double format (but they are integer values if that's to be concerned). I would like to convert them to a hh:mm:ss format string. How to do that?

For example double secs = 120; would be 00:02:00.

Upvotes: 2

Views: 8606

Answers (4)

Juan
Juan

Reputation: 830

I had the same problem and wanted to store the result in QString so I did that

int nbSecond = 145678;
QTime time(0,0,0);
time = time.addSecs(int(nbSecond));

// The expected format in the question asked
QString stringA = QString("%1:%2:%3").arg(time.hour()).arg(time.minute()).arg(time.second());
qDebug() << stringA;  // Display : 16:27:58

// Another Format for example
QString stringB = QString("%1 hours, %2 minutes, %3 seconds").arg(time.hour()).arg(time.minute()).arg(time.second());
qDebug() << stringB;  // Display : 16 hours, 27 minutes, 58 seconds

Hope this can help someone

Upvotes: 0

Bowdzone
Bowdzone

Reputation: 3854

You can create a QTime object by using its default constructor and then add your seconds to it:

double secs = 120;

QTime a(0,0,0);
a = a.addSecs(int(secs));

Upvotes: 9

synacker
synacker

Reputation: 1782

QTime time;
time = time.addSecs((int)secs);
qDebug() << time.toString("hh:mm:ss");

Upvotes: 0

vahancho
vahancho

Reputation: 21220

Why can't you convert seconds into hours, mins and seconds?

double secsDouble = 3666.0; // 1 hour, 1 min, 6 seconds.
int secs = (int)secsDouble;

int h = secs / 3600;
int m = ( secs % 3600 ) / 60;
int s = ( secs % 3600 ) % 60;

QTime t(h, m, s);
qDebug() << time.toString("hh:mm:ss");

Upvotes: 1

Related Questions