开发者

How to get the difference between two QDateTimes in milliseconds?

开发者 https://www.devze.com 2023-01-15 19:48 出处:网络
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 impleme

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 th开发者_如何学编程e millisecond?


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


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.


how about this:

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

Source


All the solutions are good, but if your timestamp is in a particular format then you can find the difference by below, and also you can assign that to QString.

let start is time on some moment in some format

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

let end is time on some moment after start in some format

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

So, you can find the difference by providing the format and using msecsto and assign them to QString(if required).

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")));
0

精彩评论

暂无评论...
验证码 换一张
取 消