Reputation: 1788
As I said in title I need to convert seconds to hh:mm:ss
I tried this:
ui->label->setText(QDateTime::fromTime_t(10).toString("hh:mm:ss"));
But default value for hours is always 01 but I need it to be 00. As result I should get 00:00:10 but I get 01:00:10.
Upvotes: 19
Views: 27180
Reputation: 2114
Other answers work perfect when the number of seconds stays below 24 hours. For most usecases that is good enough. However for our usecase the timer went above 24 hours and reset to 00:00:00. Do note that the following code does not work for times of 100 hours or more. The number 2 in the arg method forces the string to be 2 characters.
int totalNumberOfSeconds = 90242; // nr of seconds more than 1 day.
int seconds = totalNumberOfSeconds % 60;
int minutes = (totalNumberOfSeconds / 60) % 60;
int hours = (totalNumberOfSeconds / 60 / 60);
QString timeString = QString("%1:%2:%3")
.arg(hours, 2, 10, QChar('0'))
.arg(minutes, 2, 10, QChar('0'))
.arg(seconds, 2, 10, QChar('0'));
Upvotes: 5
Reputation: 41
In Qt 5 you can use QTime::fromMSecsSinceStartOfDay(int msecs).
ui->label->setText(QTime::fromMSecsSinceStartOfDay(10 * 1000).toString("hh:mm:ss"));
Upvotes: 3
Reputation: 12931
Your timezone is included in it thats why. Try this:
QDateTime::fromTime_t(10).toUTC().toString("hh:mm:ss");
Upvotes: 19
Reputation: 157484
There is no QTime::fromTime_t
; possibly you're using QDateTime::fromTime_t
, which accounts for time zones and daylight savings.
Instead you can use QTime().addSecs(10).toString(...)
.
Upvotes: 6