在日常开发时,经常会遇到计算剩余进度或者剩余时间的问题,比如计算剩余下载时间等等。本篇文章旨在提供几个常用的转换方式供各位参考。
1、秒转时分秒(方法壹)
QString FormatHHMMSS(qint32 total)
{
int hh = total / (60 * 60);
int mm = (total- (hh * 60 * 60)) / 60;
int ss = (total - (hh * 60 * 60)) - mm * 60;
QString hour = QString::number(hh, 10);
QString min = QString::number(mm, 10);
QString sec = QString::number(ss, 10);
if (hour.length() == 1)
hour = "0" + hour;
if (min.length() == 1)
min = "0" + min;
if (sec.length() == 1)
sec = "0" + sec;
QString strTime = hour + ":" + min + ":" + sec;
return strTime;
}
2、秒转时分秒(方法贰)
借助进制转换与补零,可参考文章:https://hellokandy.blog.csdn.net/article/details/123003917
QString FormatHHMMSS2(qint32 total)
{
int hh = total / (60 * 60);
int mm = (total- (hh * 60 * 60)) / 60;
int ss = (total - (hh * 60 * 60)) - mm * 60;
QString strTime = QString("%1:%2:%3")
.arg(hh, 2, 10, QLatin1Char('0'))
.arg(mm, 2, 10, QLatin1Char('0'))
.arg(ss, 2, 10, QLatin1Char('0'));
return strTime;
}
3、毫秒转时分秒(修正版)
注意:需要把“天”计算到“时”里面才是正确的答案!
QString FormatHHMMSS3(qint64 ms)
{
int ss = 1000;//ms
int mm = ss * 60;
int hh = mm * 60;
int dd = hh * 24;
qint64 day = ms / dd;
qint64 hour = (ms - day * dd) / hh;
qint64 minute = (ms - day * dd - hour * hh) / mm;
qint64 second = (ms - day * dd - hour * hh - minute * mm) / ss;
qint64 milliSecond = ms - day * dd - hour * hh - minute * mm - second * ss;
QString strTime = QString("%1:%2:%3")
.arg(hour + day * 24, 2, 10, QLatin1Char('0'))
.arg(minute, 2, 10, QLatin1Char('0'))
.arg(second, 2, 10, QLatin1Char('0'));
return strTime;
}
测试代码
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qint64 s = 123456;
qDebug() << "hhmmss=" << FormatHHMMSS(s);
qDebug() << "hhmmss2=" << FormatHHMMSS2(s);
qDebug() << "hhmmss3=" << FormatHHMMSS3(s * 1000);
return a.exec();
}
QTime时间格式转换
注意:这种方式对于超过一天的计算是不准确的,需要自己单独先计算是否超过了一天
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qint64 s = 123456;//一天的总秒数:86400=24*60*60
QString tm = QTime(0, 0, 0).addSecs(int(s)).toString(QString::fromLatin1("HH:mm:ss"));
qDebug() << tm;
return a.exec();
}