| 40 | } |
| 41 | |
| 42 | QString Time::humanReadableDuration(double duration, int precision) |
| 43 | { |
| 44 | using days = std::chrono::duration<int, std::ratio<86400>>; |
| 45 | |
| 46 | QString outStr; |
| 47 | QTextStream os(&outStr); |
| 48 | |
| 49 | bool neg = false; |
| 50 | if (duration < 0) { |
| 51 | neg = true; // flag |
| 52 | duration *= -1; // invert |
| 53 | } |
| 54 | |
| 55 | auto std_duration = std::chrono::duration<double>(duration); |
| 56 | auto d = std::chrono::duration_cast<days>(std_duration); |
| 57 | std_duration -= d; |
| 58 | auto h = std::chrono::duration_cast<std::chrono::hours>(std_duration); |
| 59 | std_duration -= h; |
| 60 | auto m = std::chrono::duration_cast<std::chrono::minutes>(std_duration); |
| 61 | std_duration -= m; |
| 62 | auto s = std::chrono::duration_cast<std::chrono::seconds>(std_duration); |
| 63 | std_duration -= s; |
| 64 | auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std_duration); |
| 65 | |
| 66 | auto dc = d.count(); |
| 67 | auto hc = h.count(); |
| 68 | auto mc = m.count(); |
| 69 | auto sc = s.count(); |
| 70 | auto msc = ms.count(); |
| 71 | |
| 72 | if (neg) { |
| 73 | os << '-'; |
| 74 | } |
| 75 | if (dc) { |
| 76 | os << dc << QObject::tr("days"); |
| 77 | } |
| 78 | if (hc) { |
| 79 | if (dc) |
| 80 | os << " "; |
| 81 | os << qSetFieldWidth(2) << hc << QObject::tr("h"); // hours |
| 82 | } |
| 83 | if (mc) { |
| 84 | if (dc || hc) |
| 85 | os << " "; |
| 86 | os << qSetFieldWidth(2) << mc << QObject::tr("m"); // minutes |
| 87 | } |
| 88 | if (dc || hc || mc || sc) { |
| 89 | if (dc || hc || mc) |
| 90 | os << " "; |
| 91 | os << qSetFieldWidth(2) << sc << QObject::tr("s"); // seconds |
| 92 | } |
| 93 | if ((msc && (precision > 0)) || !(dc || hc || mc || sc)) { |
| 94 | if (dc || hc || mc || sc) |
| 95 | os << " "; |
| 96 | os << qSetFieldWidth(0) << qSetRealNumberPrecision(precision) << msc << QObject::tr("ms"); // miliseconds |
| 97 | } |
| 98 | |
| 99 | os.flush(); |