How to get the difference between two QDateTimes in milliseconds?

I want QDateTime to override the statement - and return a QTimeSpan representing the difference between the two QDateTimes (like the .NET TimeSpan). Since this does not exist in Qt, I decided to implement it.

Unfortunately, QDateTime has no function msecsTo. What is the cleanest way to get the difference between two QDateTimes accurate to the millisecond?

+5
source share
3 answers

I would use a.daysTo(b)*1000*60*60*24 + a.time().msecsTo(b.time()). Note that you need to see how close you can be, as you are about to quickly overflow your data type.

+7
source

, 2010 , Qt 4.7 ( , - 21 2010 ), , :

Qt 4.7, QDateTime msecsTo. . Qt 4.8 http://doc.qt.io/qt-4.8/qdatetime.html#msecsTo.

QDateTime dateTime1 = QDateTime::currentDateTime();
// let say exactly 5 seconds pass here...
QDateTime dateTime2 = QDateTime::currentDateTime();
qint64 millisecondsDiff = dateTime1.msecsTo(dateTime2);
// millisecondsDiff is equal to 5000
+5

how about this:

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

Source

+1
source

All Articles