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 <thiago.macieira@intel.com>
Reviewed-by: Jake Petroules <jake.petroules@qt.io>
This commit is contained in:
Tor Arne Vestbø 2016-09-30 11:50:49 +02:00 committed by Tor Arne Vestbø
parent c6fa0222e2
commit be7f671ac9
2 changed files with 10 additions and 7 deletions

View File

@ -375,8 +375,8 @@ QDateTime QDateTime::fromCFDate(CFDateRef date)
{
if (!date)
return QDateTime();
return QDateTime::fromMSecsSinceEpoch(static_cast<qint64>((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<qint64>([date timeIntervalSince1970] * 1000));
return QDateTime::fromMSecsSinceEpoch(qRound64([date timeIntervalSince1970] * 1000));
}
/*!

View File

@ -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);
}