Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two QDateTimes in milliseconds?

Tags:

qt

qt4

I wish QDateTime overrode the - operator and returned a QTimeSpan representing the difference between two QDateTimes (just like .NET's TimeSpan). Since this doesn't exist in Qt, I decided to implement it.

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

like image 450
Jake Petroules Avatar asked Sep 13 '10 20:09

Jake Petroules


3 Answers

how about this:

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

Source

like image 199
jrharshath Avatar answered Oct 17 '22 07:10

jrharshath


I realize that this question is from 2010, and that Qt 4.7 didn't exist back then (it actually came out about a week after this question was originally asked--September 21 2010), but for people who are looking for how to do this now:

As of Qt 4.7, QDateTime has a "msecsTo" method. See Qt 4.8 documentation at 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
like image 38
nathan_m Avatar answered Oct 17 '22 07:10

nathan_m


I would probably use a.daysTo(b)*1000*60*60*24 + a.time().msecsTo(b.time()). Note that you need to watch how close you can be, since you're going to overflow your data type rather quickly.

like image 10
jkerian Avatar answered Oct 17 '22 07:10

jkerian