Qt seconds to DD HH SS

2019-05-30 19:26发布

问题:

using Qt 4.8 how can I print the time in the format DD HH SS? I have the seconds and I want to get back a string in that format.

回答1:

QDateTime::fromTime_t(seconds).toString("ss hh DD");

see http://qt-project.org/doc/qt-5.0/qdatetime.html#toString

If you want a duration ( your question was really unclear) try something like :

QString seconds_to_DHMS(quint32 duration)
{
  QString res;
  int seconds = (int) (duration % 60);
  duration /= 60;
  int minutes = (int) (duration % 60);
  duration /= 60;
  int hours = (int) (duration % 24);
  int days = (int) (duration / 24);
  if((hours == 0)&&(days == 0))
      return res.sprintf("%02d:%02d", minutes, seconds);
  if (days == 0)
      return res.sprintf("%02d:%02d:%02d", hours, minutes, seconds);
  return res.sprintf("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}


回答2:

Since you have the server uptime as seconds, you can use the QDateTime class.

QDateTime::fromTime_t(duration).toUTC().toString("dd hh ss");

Notice the toUTC, that's to set the beginning hour to 0. Since you will only be taking the date, hour and seconds, it doesn't really matter if the seconds are not since that date since the year won't be displayed.



回答3:

You can use QDateTime::fromTime_t :

Returns a datetime whose date and time are the number of seconds that have passed since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).



回答4:

What you want to print is a duration of time...not a "moment" in clock time. QDateTime doesn't do much with durations except computing secsTo (and daysTo), and you pretty much have to roll your own printing.

Good news is the math isn't that hard:

Convert seconds to Days, Minutes and Seconds

Although your internationalization of words like seconds / days / years might be a nuisance. :(



回答5:

The math is incredibly hard. Days are not 24 hours, they are usually 24 hours but sometimes 23 or 25 (daylight savings time changes) or 24 hours and a second or two (leap seconds). The same problem goes for months (obviously, since differently-sized months are common) years (leap day) and really anything that inherits day's problem by being defined in terms of days (weeks).