From 7d929f13d50a0392bf6e24561304ed11e1407480 Mon Sep 17 00:00:00 2001 From: Edward Welbourne Date: Fri, 3 Nov 2023 15:00:42 +0100 Subject: [PATCH] QDTP: consolidate defaultValue computation and clip to range Previously setting a range on the QDTP that excluded 1900 would have lead to using a default value outside the QDTP's valid range. This did not arise in practice (QDTE supplies its own defaultValue, which is in range, and QDT/QLocale's use of QDTP don't set a range). However, I now want to give callers some control over the century used in two-digit years, which shall mean they can select the defaultValue's year; and we'll still need to ensure this is in range. Task-number: QTBUG-46843 Change-Id: I3884853dc1d2775e1049c25f208d90b8a363d0a7 Reviewed-by: Isak Fyksen Reviewed-by: Thiago Macieira --- src/corelib/time/qdatetimeparser.cpp | 21 +++++++++++++++++---- src/corelib/time/qdatetimeparser_p.h | 1 + 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/corelib/time/qdatetimeparser.cpp b/src/corelib/time/qdatetimeparser.cpp index 6277244901..9da0d1094a 100644 --- a/src/corelib/time/qdatetimeparser.cpp +++ b/src/corelib/time/qdatetimeparser.cpp @@ -2224,11 +2224,25 @@ QString QDateTimeParser::stateName(State s) const } } + +/*! + \internal + Compute a defaultValue to pass to parse(). +*/ +QDateTime QDateTimeParser::baseDate(const QTimeZone &zone) const +{ + QDateTime when = QDate(1900, 1, 1).startOfDay(zone); + if (const QDateTime start = getMinimum(); when < start) + return start; + if (const QDateTime end = getMaximum(); when > end) + return end; + return when; +} + // Only called when we want only one of date or time; use UTC to avoid bogus DST issues. bool QDateTimeParser::fromString(const QString &t, QDate *date, QTime *time) const { - QDateTime val(QDate(1900, 1, 1).startOfDay(QTimeZone::UTC)); - const StateNode tmp = parse(t, -1, val, false); + const StateNode tmp = parse(t, -1, baseDate(QTimeZone::UTC), false); if (tmp.state != Acceptable || tmp.conflicts) return false; @@ -2253,8 +2267,7 @@ bool QDateTimeParser::fromString(const QString &t, QDate *date, QTime *time) con // Only called when we want both date and time; default to local time. bool QDateTimeParser::fromString(const QString &t, QDateTime *datetime) const { - static const QDateTime defaultLocalTime = QDate(1900, 1, 1).startOfDay(); - const StateNode tmp = parse(t, -1, defaultLocalTime, false); + const StateNode tmp = parse(t, -1, baseDate(QTimeZone::LocalTime), false); if (datetime) *datetime = tmp.value; return tmp.state >= Intermediate && !tmp.conflicts && tmp.value.isValid(); diff --git a/src/corelib/time/qdatetimeparser_p.h b/src/corelib/time/qdatetimeparser_p.h index 64ced268c9..55bd517865 100644 --- a/src/corelib/time/qdatetimeparser_p.h +++ b/src/corelib/time/qdatetimeparser_p.h @@ -203,6 +203,7 @@ private: }; QString getAmPmText(AmPm ap, Case cs) const; + QDateTime baseDate(const QTimeZone &zone) const; friend class QDTPUnitTestParser;