在 Qt 中将 42010958 毫秒转换为 Hours:Minutes:Seconds 的最干净的方法是什么?

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

QTime Class 给了我一点麻烦,因为它不允许我将毫秒设置为高于特定值,因此使这样的条目无效。:

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

考虑到我处理的毫秒范围大约在 10001000000000 之间,我不太热衷于编写大量的整数转换代码来清理每个进入,但我会做我必须做的。

在 Qt 中将 42010958 毫秒转换为 Hours:Minutes:Seconds 最简洁的方法是什么?

"Cleanest" 是个人喜好问题,但我会这样做:

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);

你可以使用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;

您可以使用 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;
}