From be7f671ac99c7d02d82a5f05822642bd39e30923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Fri, 30 Sep 2016 11:50:49 +0200 Subject: [PATCH] Round to nearest millisecond in QDateTime::fromCFDate() CFAbsoluteTime is measured in seconds, represented by a double, so when converting milliseconds to CFAbsoluteTime we may get a slight error due to missing precision in double to represent the milliseconds exactly. By rounding to the closest millisecond when converting back, we avoid truncating and being one ms off. Change-Id: If1e99f97b000fb8cb893ddfc5d7ba81096c0ea88 Reviewed-by: Thiago Macieira Reviewed-by: Jake Petroules --- src/corelib/kernel/qcore_foundation.mm | 6 +++--- .../auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm | 11 +++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/corelib/kernel/qcore_foundation.mm b/src/corelib/kernel/qcore_foundation.mm index 2291017a5d..f5ccd1c1f2 100644 --- a/src/corelib/kernel/qcore_foundation.mm +++ b/src/corelib/kernel/qcore_foundation.mm @@ -375,8 +375,8 @@ QDateTime QDateTime::fromCFDate(CFDateRef date) { if (!date) return QDateTime(); - return QDateTime::fromMSecsSinceEpoch(static_cast((CFDateGetAbsoluteTime(date) - + kCFAbsoluteTimeIntervalSince1970) * 1000)); + CFAbsoluteTime sSinceEpoch = kCFAbsoluteTimeIntervalSince1970 + CFDateGetAbsoluteTime(date); + return QDateTime::fromMSecsSinceEpoch(qRound64(sSinceEpoch * 1000)); } /*! @@ -404,7 +404,7 @@ QDateTime QDateTime::fromNSDate(const NSDate *date) { if (!date) return QDateTime(); - return QDateTime::fromMSecsSinceEpoch(static_cast([date timeIntervalSince1970] * 1000)); + return QDateTime::fromMSecsSinceEpoch(qRound64([date timeIntervalSince1970] * 1000)); } /*! diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm b/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm index fb49b8952e..f73c7b9d5d 100644 --- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm +++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime_mac.mm @@ -36,8 +36,11 @@ void tst_QDateTime_macTypes() { // QDateTime <-> CFDate - { - QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(0); + + static const int kMsPerSecond = 1000; + + for (int i = 0; i < kMsPerSecond; ++i) { + QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(i); const CFDateRef cfDate = qtDateTime.toCFDate(); QCOMPARE(QDateTime::fromCFDate(cfDate), qtDateTime); CFRelease(cfDate); @@ -50,9 +53,9 @@ void tst_QDateTime_macTypes() QCOMPARE(QDateTime::fromCFDate(cfDate), qtDateTimeCopy); } // QDateTime <-> NSDate - { + for (int i = 0; i < kMsPerSecond; ++i) { QMacAutoReleasePool pool; - QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(0); + QDateTime qtDateTime = QDateTime::fromMSecsSinceEpoch(i); const NSDate *nsDate = qtDateTime.toNSDate(); QCOMPARE(QDateTime::fromNSDate(nsDate), qtDateTime); }