代码之家  ›  专栏  ›  技术社区  ›  Jake Petroules

如何以毫秒为单位获得两个QDateTimes之间的差异?

  •  6
  • Jake Petroules  · 技术社区  · 14 年前

    我希望QDateTime重写-operator并返回一个QTimeSpan,表示两个QDateTime之间的差异(就像.NET的TimeSpan一样)。因为这在Qt中不存在,所以我决定实现它。

    不幸的是,QDateTime没有 msecsTo

    3 回复  |  直到 7 年前
        1
  •  10
  •   jkerian    14 年前

    我可能会用 a.daysTo(b)*1000*60*60*24 + a.time().msecsTo(b.time()) . 请注意,您需要注意您的距离,因为您的数据类型很快就会溢出。

        2
  •  22
  •   Jake Petroules    9 年前

    从qt4.7开始,QDateTime有一个“msecsTo”方法。参见Qt 4.8文档 http://doc.qt.io/qt-4.8/qdatetime.html#msecsTo .

    QDateTime dateTime1 = QDateTime::currentDateTime();
    // let's say exactly 5 seconds pass here...
    QDateTime dateTime2 = QDateTime::currentDateTime();
    qint64 millisecondsDiff = dateTime1.msecsTo(dateTime2);
    // millisecondsDiff is equal to 5000
    
        3
  •  3
  •   jrharshath    14 年前

    这个怎么样:

    QDateTime a = QDateTime::currentDateTime();
    QDateTime b = a.addMSecs( 1000 );
    qDebug( "%d", a.time().msecsTo( b.time() ) );
    

    Source

        4
  •  2
  •   SayAz    5 年前

    所有的解决方案都是好的,但是如果您的时间戳是一种特定的格式,那么您可以在下面找到差异,并且您可以将其分配给QString。

    开始 时间是以某种形式存在于某个时刻的吗

    QString start = QDateTime().currentDateTime().toString("hh:mm:ss AP dd/MM/yyyy"); 
    

    结束 时间过得真快吗 开始

    QString end = QDateTime().currentDateTime().toString("hh:mm:ss AP dd/MM/yyyy");
    

    姆塞斯托 并将它们分配给QString(如果需要)。

    QString timeDiff= QString("%1").arg(QDateTime().fromString(start ,"hh:mm:ss AP dd/MM/yyyy").msecsTo(QDateTime().fromString(end ,"hh:mm:ss AP dd/MM/yyyy")));