简体   繁体   English

Qt - 获取两个日期时间对象之间的时间跨度

[英]Qt - Get the time span between two datetime objects

I have two datetime objects, say, "2013-06-13 11:00:45", "2013-06-14 09:03:23". 我有两个日期时间对象,比如“2013-06-13 11:00:45”,“2013-06-14 09:03:23”。

How can I get the time span between these two datetimes(in the form of "X days, X hours, X minutes, X seconds")? 如何获得这两个日期之间的时间跨度(以“X天,X小时,X分钟,X秒”的形式)?

Currently, you must use QDateTime::secsTo and then do the math to figure out the days, hours, minutes and seconds. 目前,您必须使用QDateTime::secsTo ,然后进行数学计算以确定天,小时,分钟和秒。

However, there are plans to add a QTimeSpan class to Qt: 但是,有计划将QTimeSpan类添加到Qt:

https://qt.gitorious.org/qt/qt/merge_requests/1014 https://qt.gitorious.org/qt/qt/merge_requests/1014

It isn't clear when this will get added to Qt; 目前尚不清楚何时将其添加到Qt; the merge request is almost 2 years old already. 合并请求已经差不多2年了。 However, you can grab the code from the above merge request and compile it into your project if you'd like. 但是,如果您愿意,可以从上面的合并请求中获取代码并将其编译到您的项目中。

QTime may help to format the part of the result of QDateTime::secsTo method ( mentioned by @RA ) that is less than a day eg, t.toString("hh:mm:ss.zzz") or: QTime可以帮助格式化QDateTime::secsTo方法由@RA提到 )小于一天的部分结果,例如t.toString("hh:mm:ss.zzz")或:

#include <QString>
#include <QTime>

/// seconds as "X days, X hours, X minutes, X seconds" string
QString secondsToString(qint64 seconds)
{
  const qint64 DAY = 86400;
  qint64 days = seconds / DAY;
  QTime t = QTime(0,0).addSecs(seconds % DAY);
  return QString("%1 days, %2 hours, %3 minutes, %4 seconds")
    .arg(days).arg(t.hour()).arg(t.minute()).arg(t.second());
}

Example: 例:

#include <QDateTime>
#include <QDebug>   

int main()
{
  QString format = "yyyy-MM-dd HH:mm:ss";
  QDateTime a = QDateTime::fromString("2013-06-13 11:00:45", format);
  QDateTime b = QDateTime::fromString("2013-06-14 09:03:23", format);
  qDebug() << secondsToString(a.secsTo(b));
}

Output: 输出:

"0 days, 22 hours, 2 minutes, 38 seconds"

By default, the dates use your local timezone. 默认情况下,日期使用您的本地时区。 QDateTime::secsTo() converts the dates to "seconds since epoch" before finding the difference ie, if there is a DST transition between the dates or the UTC offset has changes for any other reason then it is taken into account (if the corresponding C mktime() supports it on a given platform). QDateTime::secsTo()在找到差异之前将日期转换为“自纪元以来的秒数”,即,如果日期之间存在DST转换,或者UTC偏移因任何其他原因而发生变化,则将其考虑在内(如果相应的话) C mktime()在给定平台上支持它。 POSIX time does not count leap seconds (you could use a "right" timezone, to count leaps seconds). POSIX时间不计算闰秒(您可以使用“正确”时区,计算跳跃秒数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM