4

The QTime Class offers me a bit of a pickle insofar as it does not allow me to set milliseconds above certain values, thus making an entry like this invalid.:

    QTime time;
    time.setHMS(0,0,0,42010958); // I normally use a variable

Considering that the range of milliseconds I'm dealing with is between about 1000 and 1000000000, I'm not terribly keen on writing a tremendous amount of of integer conversion code to sanitise each entry, but I will do what I have to do.

What is the cleanest way to convert 42010958 Milliseconds into Hours:Minutes:Seconds in Qt?

Anon
  • 2,267
  • 3
  • 34
  • 51

3 Answers3

6

"Cleanest" is a matter of taste, but here's how I would do it:

int milliseconds = 42010958;
int seconds      = milliseconds / 1000;
milliseconds     = milliseconds % 1000;
int minutes      = seconds / 60; 
seconds          = seconds % 60;
int hours        = minutes / 60;
minutes          = minutes % 60;

QTime time;
time.setHMS(hours, minutes, seconds, milliseconds);
Anon
  • 2,267
  • 3
  • 34
  • 51
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • Apart from that colon in there, this is a very clean and working solution. I'll give it a few minutes in case anyone knows of a function that makes this even cleaner. Otherwise I thank you. – Anon Dec 02 '16 at 23:05
4

You can use QTime::fromMSecsSinceStartOfDay.

#include <QtCore>

int main(int argc, char *argv[])
{
    QTime time = QTime::fromMSecsSinceStartOfDay(42010958);
    qDebug() << time.toString("hh:mm:ss:zzz");
    return EXIT_SUCCESS;
}
thuga
  • 12,601
  • 42
  • 52
3

You could use the STL.

using namespace std::chrono_literals;
auto milliseconds = 42010958ms;
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(milliseconds);
milliseconds -= seconds;
auto minutes = std::chrono::duration_cast<std::chrono::minutes>(seconds);
seconds -= minutes;
auto hours = std::chrono::duration_cast<std::chrono::hours>(minutes);
minutes -= hours;
Chris Ray
  • 31
  • 2
  • +1 And add `#include "chrono_io.h" (https://howardhinnant.github.io/date/chrono_io.html)` if you want rock-solid debugging of your durations such as `std::cout << hours << '\n';` That will confirm that not only is the run-time value of `hours` is correct, but the *compile-time* type of `hours` is _also_ correct. :-) – Howard Hinnant Dec 03 '16 at 02:18
  • 2
    And people wonder why everyone looks outside of the standard library first. This kind of verboseness is rather sad in the design of a library meant for widespread reuse. – Kuba hasn't forgotten Monica Dec 05 '16 at 14:46