summaryrefslogtreecommitdiffstats
path: root/src/corelib/time
diff options
context:
space:
mode:
Diffstat (limited to 'src/corelib/time')
-rw-r--r--src/corelib/time/qcalendar.cpp6
-rw-r--r--src/corelib/time/qdatetime.cpp415
-rw-r--r--src/corelib/time/qdatetimeparser.cpp49
-rw-r--r--src/corelib/time/qdatetimeparser_p.h2
-rw-r--r--src/corelib/time/qtimezone.cpp4
-rw-r--r--src/corelib/time/qtimezoneprivate.cpp19
-rw-r--r--src/corelib/time/qtimezoneprivate_android.cpp52
-rw-r--r--src/corelib/time/qtimezoneprivate_icu.cpp12
-rw-r--r--src/corelib/time/qtimezoneprivate_mac.mm47
-rw-r--r--src/corelib/time/qtimezoneprivate_tz.cpp2
10 files changed, 292 insertions, 316 deletions
diff --git a/src/corelib/time/qcalendar.cpp b/src/corelib/time/qcalendar.cpp
index d308aeba2b..9d485f181e 100644
--- a/src/corelib/time/qcalendar.cpp
+++ b/src/corelib/time/qcalendar.cpp
@@ -100,7 +100,7 @@ struct Registry {
if (id == QCalendar::System::User) {
byId.push_back(calendar);
} else {
- Q_ASSERT(byId.at(size_t(id)) == nullptr);
+ Q_ASSERT(byId[size_t(id)] == nullptr);
byId[size_t(id)] = calendar;
}
if (id == QCalendar::System::Gregorian) {
@@ -618,7 +618,7 @@ const QCalendarBackend *QCalendarBackend::fromEnum(QCalendar::System system)
if (calendarRegistry.isDestroyed() || system == QCalendar::System::User)
return nullptr;
Q_ASSERT(calendarRegistry->byId.size() >= size_t(system));
- if (auto *c = calendarRegistry->byId.at(size_t(system)))
+ if (auto *c = calendarRegistry->byId[size_t(system)])
return c;
switch (system) {
case QCalendar::System::Gregorian:
@@ -723,7 +723,7 @@ QCalendar::QCalendar(QLatin1String name)
QCalendar::QCalendar(QStringView name)
: d(QCalendarBackend::fromName(name)) {}
-/*
+/*!
\fn bool QCalendar::isValid() const
Returns true if this is a valid calendar object.
diff --git a/src/corelib/time/qdatetime.cpp b/src/corelib/time/qdatetime.cpp
index 95a7255a04..67d37f19d8 100644
--- a/src/corelib/time/qdatetime.cpp
+++ b/src/corelib/time/qdatetime.cpp
@@ -127,7 +127,7 @@ static const char qt_shortMonthNames[][4] = {
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
-static int qt_monthNumberFromShortName(QStringRef shortName)
+static int qt_monthNumberFromShortName(QStringView shortName)
{
for (unsigned int i = 0; i < sizeof(qt_shortMonthNames) / sizeof(qt_shortMonthNames[0]); ++i) {
if (shortName == QLatin1String(qt_shortMonthNames[i], 3))
@@ -136,9 +136,9 @@ static int qt_monthNumberFromShortName(QStringRef shortName)
return -1;
}
static int qt_monthNumberFromShortName(const QString &shortName)
-{ return qt_monthNumberFromShortName(QStringRef(&shortName)); }
+{ return qt_monthNumberFromShortName(QStringView(shortName)); }
-static int fromShortMonthName(const QStringRef &monthName, int year)
+static int fromShortMonthName(QStringView monthName, int year)
{
// Assume that English monthnames are the default
int month = qt_monthNumberFromShortName(monthName);
@@ -164,8 +164,8 @@ static ParsedRfcDateTime rfcDateImpl(const QString &s)
{
ParsedRfcDateTime result;
- // Matches "Wdy, dd Mon yyyy HH:mm:ss ±hhmm" (Wdy, being optional)
- QRegExp rex(QStringLiteral("^(?:[A-Z][a-z]+,)?[ \\t]*(\\d{1,2})[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d)(?::(\\d\\d))?)?[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
+ // Matches "[ddd,] dd MMM yyyy[ hh:mm[:ss]] [±hhmm]" - correct RFC 822, 2822, 5322 format
+ QRegExp rex(QStringLiteral("^[ \\t]*(?:[A-Z][a-z]+,)?[ \\t]*(\\d{1,2})[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d)(?::(\\d\\d))?)?[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
if (s.indexOf(rex) == 0) {
const QStringList cap = rex.capturedTexts();
result.date = QDate(cap[3].toInt(), qt_monthNumberFromShortName(cap[2]), cap[1].toInt());
@@ -176,8 +176,8 @@ static ParsedRfcDateTime rfcDateImpl(const QString &s)
const int minOffset = cap[9].toInt();
result.utcOffset = ((hourOffset * 60 + minOffset) * (positiveOffset ? 60 : -60));
} else {
- // Matches "Wdy Mon dd HH:mm:ss yyyy"
- QRegExp rex(QStringLiteral("^[A-Z][a-z]+[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d):(\\d\\d))?[ \\t]+(\\d\\d\\d\\d)[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
+ // Matches "ddd MMM dd[ hh:mm:ss] yyyy [±hhmm]" - permissive RFC 850, 1036 (read only)
+ QRegExp rex(QStringLiteral("^[ \\t]*[A-Z][a-z]+[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d):(\\d\\d))?[ \\t]+(\\d\\d\\d\\d)[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
if (s.indexOf(rex) == 0) {
const QStringList cap = rex.capturedTexts();
result.date = QDate(cap[6].toInt(), qt_monthNumberFromShortName(cap[1]), cap[2].toInt());
@@ -207,7 +207,7 @@ static QString toOffsetString(Qt::DateFormat format, int offset)
#if QT_CONFIG(datestring)
// Parse offset in [+-]HH[[:]mm] format
-static int fromOffsetString(const QStringRef &offsetString, bool *valid) noexcept
+static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
{
*valid = false;
@@ -228,22 +228,23 @@ static int fromOffsetString(const QStringRef &offsetString, bool *valid) noexcep
return 0;
// Split the hour and minute parts
- const QStringRef time = offsetString.mid(1);
- int hhLen = time.indexOf(QLatin1Char(':'));
- int mmIndex;
+ const QStringView time = offsetString.mid(1);
+ qsizetype hhLen = time.indexOf(QLatin1Char(':'));
+ qsizetype mmIndex;
if (hhLen == -1)
mmIndex = hhLen = 2; // [+-]HHmm or [+-]HH format
else
mmIndex = hhLen + 1;
- const QStringRef hhRef = time.left(hhLen);
+ const QLocale C = QLocale::c();
+ const QStringView hhRef = time.left(qMin(hhLen, time.size()));
bool ok = false;
- const int hour = hhRef.toInt(&ok);
+ const int hour = C.toInt(hhRef, &ok);
if (!ok)
return 0;
- const QStringRef mmRef = time.mid(mmIndex);
- const int minute = mmRef.isEmpty() ? 0 : mmRef.toInt(&ok);
+ const QStringView mmRef = time.mid(qMin(mmIndex, time.size()));
+ const int minute = mmRef.isEmpty() ? 0 : C.toInt(mmRef, &ok);
if (!ok || minute < 0 || minute > 59)
return 0;
@@ -1213,25 +1214,25 @@ QString QDate::toString(Qt::DateFormat format) const
\table
\header \li Expression \li Output
- \row \li d \li the day as number without a leading zero (1 to 31)
- \row \li dd \li the day as number with a leading zero (01 to 31)
+ \row \li d \li The day as a number without a leading zero (1 to 31)
+ \row \li dd \li The day as a number with a leading zero (01 to 31)
\row \li ddd
- \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
+ \li The abbreviated localized day name (e.g. 'Mon' to 'Sun').
Uses the system locale to localize the name, i.e. QLocale::system().
\row \li dddd
- \li the long localized day name (e.g. 'Monday' to 'Sunday').
+ \li The long localized day name (e.g. 'Monday' to 'Sunday').
Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li M \li the month as number without a leading zero (1 to 12)
- \row \li MM \li the month as number with a leading zero (01 to 12)
+ \row \li M \li The month as a number without a leading zero (1 to 12)
+ \row \li MM \li The month as a number with a leading zero (01 to 12)
\row \li MMM
- \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
+ \li The abbreviated localized month name (e.g. 'Jan' to 'Dec').
Uses the system locale to localize the name, i.e. QLocale::system().
\row \li MMMM
- \li the long localized month name (e.g. 'January' to 'December').
+ \li The long localized month name (e.g. 'January' to 'December').
Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li yy \li the year as two digit number (00 to 99)
- \row \li yyyy \li the year as four digit number. If the year is negative,
- a minus sign is prepended in addition.
+ \row \li yy \li The year as a two digit number (00 to 99)
+ \row \li yyyy \li The year as a four digit number. If the year is negative,
+ a minus sign is prepended, making five characters.
\endtable
Any sequence of characters enclosed in single quotes will be included
@@ -1625,6 +1626,29 @@ qint64 QDate::daysTo(const QDate &d) const
*/
#if QT_CONFIG(datestring)
+namespace {
+
+struct ParsedInt { int value = 0; bool ok = false; };
+
+/*
+ /internal
+
+ Read an int that must be the whole text. QStringRef::toInt() will ignore
+ spaces happily; but ISO date format should not.
+*/
+ParsedInt readInt(QStringView text)
+{
+ ParsedInt result;
+ for (const auto &ch : text) {
+ if (ch.isSpace())
+ return result;
+ }
+ result.value = QLocale::c().toInt(text, &result.ok);
+ return result;
+}
+
+}
+
/*!
Returns the QDate represented by the \a string, using the
\a format given, or an invalid date if the string cannot be
@@ -1676,17 +1700,18 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
return QDate(year, month, day);
}
#endif // textdate
- case Qt::ISODate: {
- // Semi-strict parsing, must be long enough and have non-numeric separators
- if (string.size() < 10 || string.at(4).isDigit() || string.at(7).isDigit()
- || (string.size() > 10 && string.at(10).isDigit())) {
- return QDate();
- }
- const int year = string.midRef(0, 4).toInt();
- if (year <= 0 || year > 9999)
- return QDate();
- return QDate(year, string.midRef(5, 2).toInt(), string.midRef(8, 2).toInt());
+ case Qt::ISODate:
+ // Semi-strict parsing, must be long enough and have punctuators as separators
+ if (string.size() >= 10 && string.at(4).isPunct() && string.at(7).isPunct()
+ && (string.size() == 10 || !string.at(10).isDigit())) {
+ QStringView view(string);
+ const ParsedInt year = readInt(view.mid(0, 4));
+ const ParsedInt month = readInt(view.mid(5, 2));
+ const ParsedInt day = readInt(view.mid(8, 2));
+ if (year.ok && year.value > 0 && year.value <= 9999 && month.ok && day.ok)
+ return QDate(year.value, month.value, day.value);
}
+ break;
}
return QDate();
}
@@ -1719,11 +1744,15 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
\row \li MMMM
\li The long localized month name (e.g. 'January' to 'December').
Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li yy \li The year as two digit number (00 to 99)
- \row \li yyyy \li The year as four digit number. If the year is negative,
- a minus sign is prepended in addition.
+ \row \li yy \li The year as a two digit number (00 to 99)
+ \row \li yyyy \li The year as a four digit number, possibly plus a leading
+ minus sign for negative years.
\endtable
+ \note Unlike the other version of this function, day and month names must
+ be given in the user's local language. It is only possible to use the English
+ names if the user's language is English.
+
All other input characters will be treated as text. Any sequence
of characters that are enclosed in single quotes will also be
treated as text and will not be used as an expression. For example:
@@ -1765,7 +1794,7 @@ QDate QDate::fromString(const QString &string, const QString &format, QCalendar
QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString, cal);
// dt.setDefaultLocale(QLocale::c()); ### Qt 6
if (dt.parseFormat(format))
- dt.fromString(string, &date, 0);
+ dt.fromString(string, &date, nullptr);
#else
Q_UNUSED(string);
Q_UNUSED(format);
@@ -2063,30 +2092,30 @@ QString QTime::toString(Qt::DateFormat format) const
\table
\header \li Expression \li Output
\row \li h
- \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
+ \li The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
\row \li hh
- \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
+ \li The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
\row \li H
- \li the hour without a leading zero (0 to 23, even with AM/PM display)
+ \li The hour without a leading zero (0 to 23, even with AM/PM display)
\row \li HH
- \li the hour with a leading zero (00 to 23, even with AM/PM display)
- \row \li m \li the minute without a leading zero (0 to 59)
- \row \li mm \li the minute with a leading zero (00 to 59)
- \row \li s \li the whole second, without any leading zero (0 to 59)
- \row \li ss \li the whole second, with a leading zero where applicable (00 to 59)
- \row \li z \li the fractional part of the second, to go after a decimal
+ \li The hour with a leading zero (00 to 23, even with AM/PM display)
+ \row \li m \li The minute without a leading zero (0 to 59)
+ \row \li mm \li The minute with a leading zero (00 to 59)
+ \row \li s \li The whole second, without any leading zero (0 to 59)
+ \row \li ss \li The whole second, with a leading zero where applicable (00 to 59)
+ \row \li z \li The fractional part of the second, to go after a decimal
point, without trailing zeroes (0 to 999). Thus "\c{s.z}"
reports the seconds to full available (millisecond) precision
without trailing zeroes.
- \row \li zzz \li the fractional part of the second, to millisecond
+ \row \li zzz \li The fractional part of the second, to millisecond
precision, including trailing zeroes where applicable (000 to 999).
\row \li AP or A
- \li use AM/PM display. \e A/AP will be replaced by either
- QLocale::amText() or QLocale::pmText().
+ \li Use AM/PM display. \e A/AP will be replaced by an upper-case
+ version of either QLocale::amText() or QLocale::pmText().
\row \li ap or a
- \li use am/pm display. \e a/ap will be replaced by a lower-case version of
- QLocale::amText() or QLocale::pmText().
- \row \li t \li the timezone (for example "CEST")
+ \li Use am/pm display. \e a/ap will be replaced by a lower-case version
+ of either QLocale::amText() or QLocale::pmText().
+ \row \li t \li The timezone (for example "CEST")
\endtable
Any sequence of characters enclosed in single quotes will be included
@@ -2320,22 +2349,21 @@ int QTime::msecsTo(const QTime &t) const
#if QT_CONFIG(datestring)
-static QTime fromIsoTimeString(const QStringRef &string, Qt::DateFormat format, bool *isMidnight24)
+static QTime fromIsoTimeString(QStringView string, Qt::DateFormat format, bool *isMidnight24)
{
if (isMidnight24)
*isMidnight24 = false;
const int size = string.size();
- if (size < 5)
+ if (size < 5 || string.at(2) != QLatin1Char(':'))
return QTime();
- bool ok = false;
- int hour = string.mid(0, 2).toInt(&ok);
- if (!ok)
- return QTime();
- const int minute = string.mid(3, 2).toInt(&ok);
- if (!ok)
+ ParsedInt hour = readInt(string.mid(0, 2));
+ ParsedInt minute = readInt(string.mid(3, 2));
+ if (!hour.ok || !minute.ok)
return QTime();
+ // FIXME: ISO 8601 allows [,.]\d+ after hour, just as it does after minute
+
int second = 0;
int msec = 0;
@@ -2354,40 +2382,57 @@ static QTime fromIsoTimeString(const QStringRef &string, Qt::DateFormat format,
// seconds is 4. E.g. 12:34,99999 will expand to 12:34:59.9994. The milliseconds
// will then be rounded up AND clamped to 999.
- const QStringRef minuteFractionStr = string.mid(6, 5);
- const long minuteFractionInt = minuteFractionStr.toLong(&ok);
- if (!ok)
+ const QStringView minuteFractionStr = string.mid(6, qMin(qsizetype(5), string.size() - 6));
+ const ParsedInt parsed = readInt(minuteFractionStr);
+ if (!parsed.ok)
return QTime();
- const float minuteFraction = double(minuteFractionInt) / (std::pow(double(10), minuteFractionStr.count()));
+ const float secondWithMs
+ = double(parsed.value) * 60 / (std::pow(double(10), minuteFractionStr.size()));
- const float secondWithMs = minuteFraction * 60;
- const float secondNoMs = std::floor(secondWithMs);
- const float secondFraction = secondWithMs - secondNoMs;
- second = secondNoMs;
+ second = std::floor(secondWithMs);
+ const float secondFraction = secondWithMs - second;
msec = qMin(qRound(secondFraction * 1000.0), 999);
- } else {
+ } else if (string.at(5) == QLatin1Char(':')) {
// HH:mm:ss or HH:mm:ss.zzz
- second = string.mid(6, 2).toInt(&ok);
- if (!ok)
+ const ParsedInt parsed = readInt(string.mid(6, qMin(qsizetype(2), string.size() - 6)));
+ if (!parsed.ok)
return QTime();
- if (size > 8 && (string.at(8) == QLatin1Char(',') || string.at(8) == QLatin1Char('.'))) {
- const QStringRef msecStr(string.mid(9, 4));
- int msecInt = msecStr.isEmpty() ? 0 : msecStr.toInt(&ok);
+ second = parsed.value;
+ if (size <= 8) {
+ // No fractional part to read
+ } else if (string.at(8) == QLatin1Char(',') || string.at(8) == QLatin1Char('.')) {
+ QStringView msecStr(string.mid(9, qMin(qsizetype(4), string.size() - 9)));
+ bool ok = true;
+ // Can't use readInt() here, as we *do* allow trailing space - but not leading:
+ if (!msecStr.isEmpty() && !msecStr.at(0).isDigit())
+ return QTime();
+ msecStr = msecStr.trimmed();
+ int msecInt = msecStr.isEmpty() ? 0 : QLocale::c().toInt(msecStr, &ok);
if (!ok)
return QTime();
- const double secondFraction(msecInt / (std::pow(double(10), msecStr.count())));
+ const double secondFraction(msecInt / (std::pow(double(10), msecStr.size())));
msec = qMin(qRound(secondFraction * 1000.0), 999);
+ } else {
+#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) // behavior change
+ // Stray cruft after date-time: tolerate trailing space, but nothing else.
+ for (const auto &ch : string.mid(8)) {
+ if (!ch.isSpace())
+ return QTime();
+ }
+#endif
}
+ } else {
+ return QTime();
}
const bool isISODate = format == Qt::ISODate || format == Qt::ISODateWithMs;
- if (isISODate && hour == 24 && minute == 0 && second == 0 && msec == 0) {
+ if (isISODate && hour.value == 24 && minute.value == 0 && second == 0 && msec == 0) {
if (isMidnight24)
*isMidnight24 = true;
- hour = 0;
+ hour.value = 0;
}
- return QTime(hour, minute, second, msec);
+ return QTime(hour.value, minute.value, second, msec);
}
/*!
@@ -2424,7 +2469,7 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
case Qt::ISODateWithMs:
case Qt::TextDate:
default:
- return fromIsoTimeString(QStringRef(&string), format, nullptr);
+ return fromIsoTimeString(QStringView(string), format, nullptr);
}
}
@@ -2437,23 +2482,30 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
\table
\header \li Expression \li Output
\row \li h
- \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
+ \li The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
\row \li hh
- \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
- \row \li m \li the minute without a leading zero (0 to 59)
- \row \li mm \li the minute with a leading zero (00 to 59)
- \row \li s \li the whole second, without any leading zero (0 to 59)
- \row \li ss \li the whole second, with a leading zero where applicable (00 to 59)
- \row \li z \li the fractional part of the second, to go after a decimal
+ \li The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
+ \row \li H
+ \li The hour without a leading zero (0 to 23, even with AM/PM display)
+ \row \li HH
+ \li The hour with a leading zero (00 to 23, even with AM/PM display)
+ \row \li m \li The minute without a leading zero (0 to 59)
+ \row \li mm \li The minute with a leading zero (00 to 59)
+ \row \li s \li The whole second, without any leading zero (0 to 59)
+ \row \li ss \li The whole second, with a leading zero where applicable (00 to 59)
+ \row \li z \li The fractional part of the second, to go after a decimal
point, without trailing zeroes (0 to 999). Thus "\c{s.z}"
reports the seconds to full available (millisecond) precision
without trailing zeroes.
- \row \li zzz \li the fractional part of the second, to millisecond
+ \row \li zzz \li The fractional part of the second, to millisecond
precision, including trailing zeroes where applicable (000 to 999).
- \row \li AP
- \li interpret as an AM/PM time. \e AP must be either "AM" or "PM".
- \row \li ap
- \li Interpret as an AM/PM time. \e ap must be either "am" or "pm".
+ \row \li AP or A
+ \li Interpret as an AM/PM time. \e A/AP will match an upper-case
+ version of either QLocale::amText() or QLocale::pmText().
+ \row \li ap or a
+ \li Interpret as an am/pm time. \e a/ap will match a lower-case version
+ of either QLocale::amText() or QLocale::pmText().
+ \row \li t \li the timezone (for example "CEST")
\endtable
All other input characters will be treated as text. Any sequence
@@ -2488,7 +2540,7 @@ QTime QTime::fromString(const QString &string, const QString &format)
QDateTimeParser dt(QVariant::Time, QDateTimeParser::FromString, QCalendar());
// dt.setDefaultLocale(QLocale::c()); ### Qt 6
if (dt.parseFormat(format))
- dt.fromString(string, 0, &time);
+ dt.fromString(string, nullptr, &time);
#else
Q_UNUSED(string);
Q_UNUSED(format);
@@ -3255,7 +3307,7 @@ inline QDateTime::Data::Data(Qt::TimeSpec spec)
// the structure is too small, we need to detach
d = new QDateTimePrivate;
d->ref.ref();
- d->m_status = mergeSpec(nullptr, spec);
+ d->m_status = mergeSpec({}, spec);
}
}
@@ -3399,6 +3451,7 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
DaylightStatus hint,
QDate *zoneDate, QTime *zoneTime)
{
+ Q_ASSERT(zone.isValid());
// Get the effective data from QTimeZone
QTimeZonePrivate::Data data = zone.d->dataForLocalTime(zoneMSecs, int(hint));
// Docs state any time before 1970-01-01 will *not* have any DST applied
@@ -3788,8 +3841,9 @@ QTimeZone QDateTime::timeZone() const
case Qt::OffsetFromUTC:
return QTimeZone(d->m_offsetFromUtc);
case Qt::TimeZone:
- Q_ASSERT(d->m_timeZone.isValid());
- return d->m_timeZone;
+ if (d->m_timeZone.isValid())
+ return d->m_timeZone;
+ break;
case Qt::LocalTime:
return QTimeZone::systemTimeZone();
}
@@ -3873,6 +3927,7 @@ QString QDateTime::timeZoneAbbreviation() const
#if !QT_CONFIG(timezone)
break;
#else
+ Q_ASSERT(d->m_timeZone.isValid());
return d->m_timeZone.d->abbreviation(toMSecsSinceEpoch());
#endif // timezone
case Qt::LocalTime: {
@@ -3909,6 +3964,7 @@ bool QDateTime::isDaylightTime() const
#if !QT_CONFIG(timezone)
break;
#else
+ Q_ASSERT(d->m_timeZone.isValid());
return d->m_timeZone.d->isDaylightTime(toMSecsSinceEpoch());
#endif // timezone
case Qt::LocalTime: {
@@ -4033,6 +4089,10 @@ void QDateTime::setTimeZone(const QTimeZone &toZone)
*/
qint64 QDateTime::toMSecsSinceEpoch() const
{
+ // Note: QDateTimeParser relies on this producing a useful result, even when
+ // !isValid(), at least when the invalidity is a time in a fall-back (that
+ // we'll have adjusted to lie outside it, but marked invalid because it's
+ // not what was asked for). Other things may be doing similar.
switch (getSpec(d)) {
case Qt::UTC:
return getMSecs(d);
@@ -4047,12 +4107,13 @@ qint64 QDateTime::toMSecsSinceEpoch() const
}
case Qt::TimeZone:
-#if !QT_CONFIG(timezone)
- return 0;
-#else
- return QDateTimePrivate::zoneMSecsToEpochMSecs(d->m_msecs, d->m_timeZone,
- extractDaylightStatus(getStatus(d)));
+#if QT_CONFIG(timezone)
+ if (d->m_timeZone.isValid()) {
+ return QDateTimePrivate::zoneMSecsToEpochMSecs(d->m_msecs, d->m_timeZone,
+ extractDaylightStatus(getStatus(d)));
+ }
#endif
+ return 0;
}
Q_UNREACHABLE();
return 0;
@@ -4147,9 +4208,11 @@ void QDateTime::setMSecsSinceEpoch(qint64 msecs)
case Qt::TimeZone:
Q_ASSERT(!d.isShort());
#if QT_CONFIG(timezone)
+ d.detach();
+ if (!d->m_timeZone.isValid())
+ break;
// Docs state any LocalTime before 1970-01-01 will *not* have any DST applied
// but all affected times afterwards will have DST applied.
- d.detach();
if (msecs >= 0) {
status = mergeDaylightStatus(status,
d->m_timeZone.d->isDaylightTime(msecs)
@@ -4358,61 +4421,9 @@ QString QDateTime::toString(Qt::DateFormat format) const
\fn QString QDateTime::toString(const QString &format) const
\fn QString QDateTime::toString(QStringView format) const
- Returns the datetime as a string. The \a format parameter
- determines the format of the result string.
-
- These expressions may be used for the date:
-
- \table
- \header \li Expression \li Output
- \row \li d \li the day as number without a leading zero (1 to 31)
- \row \li dd \li the day as number with a leading zero (01 to 31)
- \row \li ddd
- \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
- Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li dddd
- \li the long localized day name (e.g. 'Monday' to 'Sunday').
- Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li M \li the month as number without a leading zero (1-12)
- \row \li MM \li the month as number with a leading zero (01-12)
- \row \li MMM
- \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
- Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li MMMM
- \li the long localized month name (e.g. 'January' to 'December').
- Uses the system locale to localize the name, i.e. QLocale::system().
- \row \li yy \li the year as two digit number (00-99)
- \row \li yyyy \li the year as four digit number
- \endtable
-
- These expressions may be used for the time:
-
- \table
- \header \li Expression \li Output
- \row \li h
- \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
- \row \li hh
- \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
- \row \li H
- \li the hour without a leading zero (0 to 23, even with AM/PM display)
- \row \li HH
- \li the hour with a leading zero (00 to 23, even with AM/PM display)
- \row \li m \li the minute without a leading zero (0 to 59)
- \row \li mm \li the minute with a leading zero (00 to 59)
- \row \li s \li the whole second without a leading zero (0 to 59)
- \row \li ss \li the whole second with a leading zero where applicable (00 to 59)
- \row \li z \li the fractional part of the second, to go after a decimal
- point, without trailing zeroes (0 to 999). Thus "\c{s.z}"
- reports the seconds to full available (millisecond) precision
- without trailing zeroes.
- \row \li zzz \li the fractional part of the second, to millisecond
- precision, including trailing zeroes where applicable (000 to 999).
- \row \li AP or A
- \li use AM/PM display. \e A/AP will be replaced by either "AM" or "PM".
- \row \li ap or a
- \li use am/pm display. \e a/ap will be replaced by either "am" or "pm".
- \row \li t \li the timezone (for example "CEST")
- \endtable
+ Returns the datetime as a string. The \a format parameter determines the
+ format of the result string. See QTime::toString() and QDate::toString() for
+ the supported specifiers for time and date, respectively.
Any sequence of characters enclosed in single quotes will be included
verbatim in the output string (stripped of the quotes), even if it contains
@@ -4474,7 +4485,7 @@ static inline void massageAdjustedDateTime(const QDateTimeData &d, QDate *date,
QDateTimePrivate::DaylightStatus status = QDateTimePrivate::UnknownDaylightTime;
localMSecsToEpochMSecs(timeToMSecs(*date, *time), &status, date, time);
#if QT_CONFIG(timezone)
- } else if (spec == Qt::TimeZone) {
+ } else if (spec == Qt::TimeZone && d->m_timeZone.isValid()) {
QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(*date, *time),
d->m_timeZone,
QDateTimePrivate::UnknownDaylightTime,
@@ -5135,7 +5146,8 @@ QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, const QTimeZone &timeZone
{
QDateTime dt;
dt.setTimeZone(timeZone);
- dt.setMSecsSinceEpoch(msecs);
+ if (timeZone.isValid())
+ dt.setMSecsSinceEpoch(msecs);
return dt;
}
@@ -5238,16 +5250,17 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
if (!date.isValid())
return QDateTime();
if (size == 10)
- return QDateTime(date);
+ return date.startOfDay();
Qt::TimeSpec spec = Qt::LocalTime;
- QStringRef isoString(&string);
- isoString = isoString.mid(10); // trim "yyyy-MM-dd"
+ QStringView isoString = QStringView(string).mid(10); // trim "yyyy-MM-dd"
- // Must be left with T and at least one digit for the hour:
+ // Must be left with T (or space) and at least one digit for the hour:
if (isoString.size() < 2
- || !(isoString.startsWith(QLatin1Char('T'))
- // FIXME: QSql relies on QVariant::toDateTime() accepting a space here:
+ || !(isoString.startsWith(QLatin1Char('T'), Qt::CaseInsensitive)
+ // RFC 3339 (section 5.6) allows a space here. (It actually
+ // allows any separator one considers more readable, merely
+ // giving space as an example - but let's not go wild !)
|| isoString.startsWith(QLatin1Char(' ')))) {
return QDateTime();
}
@@ -5255,7 +5268,7 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
int offset = 0;
// Check end of string for Time Zone definition, either Z for UTC or [+-]HH:mm for Offset
- if (isoString.endsWith(QLatin1Char('Z'))) {
+ if (isoString.endsWith(QLatin1Char('Z'), Qt::CaseInsensitive)) {
spec = Qt::UTC;
isoString.chop(1); // trim 'Z'
} else {
@@ -5386,7 +5399,7 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
if (parts.count() == 5)
return QDateTime(date, time, Qt::LocalTime);
- QStringRef tz = parts.at(5);
+ QStringView tz = parts.at(5);
if (!tz.startsWith(QLatin1String("GMT"), Qt::CaseInsensitive))
return QDateTime();
tz = tz.mid(3);
@@ -5409,65 +5422,13 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
Returns the QDateTime represented by the \a string, using the \a
format given, or an invalid datetime if the string cannot be parsed.
- Uses the calendar \a cal if supplied, else Gregorian. The illustrative
- values and ranges below are given for the latter; other calendars may have
- different ranges or values.
-
- These expressions may be used for the date part of the format string:
+ Uses the calendar \a cal if supplied, else Gregorian.
- \table
- \header \li Expression \li Output
- \row \li d \li the day as number without a leading zero (1 to 31)
- \row \li dd \li the day as number with a leading zero (01 to 31)
- \row \li ddd
- \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
- \row \li dddd
- \li the long localized day name (e.g. 'Monday' to 'Sunday').
- \row \li M \li the month as number without a leading zero (1-12)
- \row \li MM \li the month as number with a leading zero (01-12)
- \row \li MMM
- \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
- \row \li MMMM
- \li the long localized month name (e.g. 'January' to 'December').
- \row \li yy \li the year as two digit number (00-99)
- \row \li yyyy \li the year as four digit number
- \endtable
-
- \note Unlike the other version of this function, day and month names must
- be given in the user's local language. It is only possible to use the English
- names if the user's language is English.
-
- These expressions may be used for the time part of the format string:
-
- \table
- \header \li Expression \li Output
- \row \li h
- \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
- \row \li hh
- \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
- \row \li H
- \li the hour without a leading zero (0 to 23, even with AM/PM display)
- \row \li HH
- \li the hour with a leading zero (00 to 23, even with AM/PM display)
- \row \li m \li the minute without a leading zero (0 to 59)
- \row \li mm \li the minute with a leading zero (00 to 59)
- \row \li s \li the whole second without a leading zero (0 to 59)
- \row \li ss \li the whole second with a leading zero where applicable (00 to 59)
- \row \li z \li the fractional part of the second, to go after a decimal
- point, without trailing zeroes (0 to 999). Thus "\c{s.z}"
- reports the seconds to full available (millisecond) precision
- without trailing zeroes.
- \row \li zzz \li the fractional part of the second, to millisecond
- precision, including trailing zeroes where applicable (000 to 999).
- \row \li AP or A
- \li interpret as an AM/PM time. \e AP must be either "AM" or "PM".
- \row \li ap or a
- \li Interpret as an AM/PM time. \e ap must be either "am" or "pm".
- \endtable
-
- All other input characters will be treated as text. Any sequence
- of characters that are enclosed in single quotes will also be
- treated as text and not be used as an expression.
+ See QDate::fromString() and QTime::fromString() for the expressions
+ recognized in the format string to represent parts of the date and time.
+ All other input characters will be treated as text. Any sequence of
+ characters that are enclosed in single quotes will also be treated as text
+ and not be used as an expression.
\snippet code/src_corelib_tools_qdatetime.cpp 12
diff --git a/src/corelib/time/qdatetimeparser.cpp b/src/corelib/time/qdatetimeparser.cpp
index 2c566e3584..31d8e6cc20 100644
--- a/src/corelib/time/qdatetimeparser.cpp
+++ b/src/corelib/time/qdatetimeparser.cpp
@@ -137,13 +137,12 @@ bool QDateTimeParser::setDigit(QDateTime &v, int index, int newVal) const
#endif
return false;
}
- const SectionNode &node = sectionNodes.at(index);
- const QDate date = v.date();
+ QCalendar::YearMonthDay date = calendar.partsFromDate(v.date());
+ if (!date.isValid())
+ return false;
+
const QTime time = v.time();
- int year = date.year(calendar);
- int month = date.month(calendar);
- int day = date.day(calendar);
int hour = time.hour();
int minute = time.minute();
int second = time.second();
@@ -152,14 +151,15 @@ bool QDateTimeParser::setDigit(QDateTime &v, int index, int newVal) const
// Only offset from UTC is amenable to setting an int value:
int offset = tspec == Qt::OffsetFromUTC ? v.offsetFromUtc() : 0;
+ const SectionNode &node = sectionNodes.at(index);
switch (node.type) {
case Hour24Section: case Hour12Section: hour = newVal; break;
case MinuteSection: minute = newVal; break;
case SecondSection: second = newVal; break;
case MSecSection: msec = newVal; break;
case YearSection2Digits:
- case YearSection: year = newVal; break;
- case MonthSection: month = newVal; break;
+ case YearSection: date.year = newVal; break;
+ case MonthSection: date.month = newVal; break;
case DaySection:
case DayOfWeekSectionShort:
case DayOfWeekSectionLong:
@@ -169,7 +169,7 @@ bool QDateTimeParser::setDigit(QDateTime &v, int index, int newVal) const
// to 31 for february should return true
return false;
}
- day = newVal;
+ date.day = newVal;
break;
case TimeZoneSection:
if (newVal < absoluteMin(index) || newVal > absoluteMax(index))
@@ -185,15 +185,14 @@ bool QDateTimeParser::setDigit(QDateTime &v, int index, int newVal) const
}
if (!(node.type & DaySectionMask)) {
- if (day < cachedDay)
- day = cachedDay;
- const int max = calendar.daysInMonth(month, year);
- if (day > max) {
- day = max;
- }
+ if (date.day < cachedDay)
+ date.day = cachedDay;
+ const int max = calendar.daysInMonth(date.month, date.year);
+ if (date.day > max)
+ date.day = max;
}
- const QDate newDate(year, month, day, calendar);
+ const QDate newDate = calendar.dateFromParts(date);
const QTime newTime(hour, minute, second, msec);
if (!newDate.isValid() || !newTime.isValid())
return false;
@@ -369,13 +368,6 @@ static QString unquote(const QStringRef &str)
}
return ret;
}
-/*!
- \internal
-
- Parses the format \a newFormat. If successful, returns \c true and
- sets up the format. Else keeps the old format and returns \c false.
-
-*/
static inline int countRepeat(const QString &str, int index, int maxCount)
{
@@ -394,7 +386,12 @@ static inline void appendSeparator(QStringList *list, const QString &string, int
list->append(lastQuote >= from ? unquote(separator) : separator.toString());
}
+/*!
+ \internal
+ Parses the format \a newFormat. If successful, returns \c true and sets up
+ the format. Else keeps the old format and returns \c false.
+*/
bool QDateTimeParser::parseFormat(const QString &newFormat)
{
const QLatin1Char quote('\'');
@@ -407,7 +404,7 @@ bool QDateTimeParser::parseFormat(const QString &newFormat)
QDTPDEBUGN("parseFormat: %s", newFormat.toLatin1().constData());
QVector<SectionNode> newSectionNodes;
- Sections newDisplay = 0;
+ Sections newDisplay;
QStringList newSeparators;
int i, index = 0;
int add = 0;
@@ -1154,7 +1151,7 @@ QDateTimeParser::scanString(const QDateTime &defaultValue,
}
pos += separator.size();
sectionNodes[index].pos = pos;
- int *current = 0;
+ int *current = nullptr;
const SectionNode sn = sectionNodes.at(index);
ParsedSection sect;
@@ -1365,7 +1362,7 @@ QDateTimeParser::scanString(const QDateTime &defaultValue,
// given date (which might be a spring-forward, skipping an hour).
if (parserType == QVariant::DateTime && !(isSet & HourSectionMask) && !when.isValid()) {
qint64 msecs = when.toMSecsSinceEpoch();
- // Fortunately, that gets a useful answer ...
+ // Fortunately, that gets a useful answer, even though when is invalid ...
const QDateTime replace =
#if QT_CONFIG(timezone)
tspec == Qt::TimeZone
@@ -1799,7 +1796,7 @@ int QDateTimeParser::SectionNode::maxChange() const
QDateTimeParser::FieldInfo QDateTimeParser::fieldInfo(int index) const
{
- FieldInfo ret = 0;
+ FieldInfo ret;
const SectionNode &sn = sectionNode(index);
switch (sn.type) {
case MSecSection:
diff --git a/src/corelib/time/qdatetimeparser_p.h b/src/corelib/time/qdatetimeparser_p.h
index d128e35ddc..ff8da956f0 100644
--- a/src/corelib/time/qdatetimeparser_p.h
+++ b/src/corelib/time/qdatetimeparser_p.h
@@ -83,7 +83,7 @@ public:
DateTimeEdit
};
QDateTimeParser(QVariant::Type t, Context ctx, const QCalendar &cal = QCalendar())
- : currentSectionIndex(-1), display(nullptr), cachedDay(-1), parserType(t),
+ : currentSectionIndex(-1), cachedDay(-1), parserType(t),
fixday(false), spec(Qt::LocalTime), context(ctx), calendar(cal)
{
defaultLocale = QLocale::system();
diff --git a/src/corelib/time/qtimezone.cpp b/src/corelib/time/qtimezone.cpp
index 410a16e3c5..87d8ea75f1 100644
--- a/src/corelib/time/qtimezone.cpp
+++ b/src/corelib/time/qtimezone.cpp
@@ -217,7 +217,7 @@ Q_GLOBAL_STATIC(QTimeZoneSingleton, global_tz);
This class includes data obtained from the CLDR data files under the terms
of the Unicode Data Files and Software License. See
- \l{Unicode Common Locale Data Repository (CLDR)} for details.
+ \l{unicode-cldr}{Unicode Common Locale Data Repository (CLDR)} for details.
\sa QDateTime
*/
@@ -318,7 +318,7 @@ Q_GLOBAL_STATIC(QTimeZoneSingleton, global_tz);
*/
QTimeZone::QTimeZone() noexcept
- : d(0)
+ : d(nullptr)
{
}
diff --git a/src/corelib/time/qtimezoneprivate.cpp b/src/corelib/time/qtimezoneprivate.cpp
index 72a0e3c24e..facdf6661d 100644
--- a/src/corelib/time/qtimezoneprivate.cpp
+++ b/src/corelib/time/qtimezoneprivate.cpp
@@ -381,18 +381,15 @@ QTimeZonePrivate::Data QTimeZonePrivate::dataForLocalTime(qint64 forLocalMSecs,
On the first pass, the case we consider is what hint told us to expect
(except when hint was -1 and didn't actually tell us what to expect),
so it's likely right. We only get a second pass if the first failed,
- by which time the second case, that we're trying, is likely right. If
- an overwhelming majority of calls have hint == -1, the Q_LIKELY here
- shall be wrong half the time; otherwise, its errors shall be rarer
- than that.
+ by which time the second case, that we're trying, is likely right.
*/
if (nextFirst ? i == 0 : i) {
Q_ASSERT(nextStart != invalidMSecs());
- if (Q_LIKELY(nextStart <= nextTran.atMSecsSinceEpoch))
+ if (nextStart <= nextTran.atMSecsSinceEpoch)
return nextTran;
} else {
// If next is invalid, nextFirst is false, to route us here first:
- if (nextStart == invalidMSecs() || Q_LIKELY(nextStart > tran.atMSecsSinceEpoch))
+ if (nextStart == invalidMSecs() || nextStart > tran.atMSecsSinceEpoch)
return tran;
}
}
@@ -421,7 +418,7 @@ QTimeZonePrivate::Data QTimeZonePrivate::dataForLocalTime(qint64 forLocalMSecs,
int early = offsetFromUtc(recent);
int late = offsetFromUtc(imminent);
- if (Q_LIKELY(early == late)) { // > 99% of the time
+ if (early == late) { // > 99% of the time
utcEpochMSecs = forLocalMSecs - early * 1000;
} else {
// Close to a DST transition: early > late is near a fall-back,
@@ -433,7 +430,7 @@ QTimeZonePrivate::Data QTimeZonePrivate::dataForLocalTime(qint64 forLocalMSecs,
const qint64 forStd = forLocalMSecs - offsetInStd * 1000;
// Best guess at the answer:
const qint64 hinted = hint > 0 ? forDst : forStd;
- if (Q_LIKELY(offsetFromUtc(hinted) == (hint > 0 ? offsetInDst : offsetInStd))) {
+ if (offsetFromUtc(hinted) == (hint > 0 ? offsetInDst : offsetInStd)) {
utcEpochMSecs = hinted;
} else if (hint <= 0 && offsetFromUtc(forDst) == offsetInDst) {
utcEpochMSecs = forDst;
@@ -633,7 +630,13 @@ bool QTimeZonePrivate::isValidId(const QByteArray &ianaId)
// Somewhat slack hand-rolled version:
const int MinSectionLength = 1;
+#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)
+ // Android has its own naming of zones.
+ // "Canada/East-Saskatchewan" has a 17-character second component.
+ const int MaxSectionLength = 17;
+#else
const int MaxSectionLength = 14;
+#endif
int sectionLength = 0;
for (const char *it = ianaId.begin(), * const end = ianaId.end(); it != end; ++it, ++sectionLength) {
const char ch = *it;
diff --git a/src/corelib/time/qtimezoneprivate_android.cpp b/src/corelib/time/qtimezoneprivate_android.cpp
index be4f374fdd..5cb8155dcc 100644
--- a/src/corelib/time/qtimezoneprivate_android.cpp
+++ b/src/corelib/time/qtimezoneprivate_android.cpp
@@ -1,5 +1,6 @@
/****************************************************************************
**
+** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2014 Drew Parsons <dparsons@emerall.com>
** Contact: https://www.qt.io/licensing/
**
@@ -53,9 +54,10 @@ QT_BEGIN_NAMESPACE
QAndroidTimeZonePrivate::QAndroidTimeZonePrivate()
: QTimeZonePrivate()
{
- // start with system time zone
- androidTimeZone = QJNIObjectPrivate::callStaticObjectMethod("java.util.TimeZone", "getDefault", "()Ljava/util/TimeZone;");
- init("UTC");
+ // Keep in sync with systemTimeZoneId():
+ androidTimeZone = QJNIObjectPrivate::callStaticObjectMethod(
+ "java.util.TimeZone", "getDefault", "()Ljava/util/TimeZone;");
+ m_id = androidTimeZone.callObjectMethod("getID", "()Ljava/lang/String;").toString().toUtf8();
}
// Create a named time zone
@@ -76,32 +78,33 @@ QAndroidTimeZonePrivate::~QAndroidTimeZonePrivate()
{
}
-
void QAndroidTimeZonePrivate::init(const QByteArray &ianaId)
{
- QJNIObjectPrivate jo_ianaId = QJNIObjectPrivate::fromString( QString::fromUtf8(ianaId) );
- androidTimeZone = QJNIObjectPrivate::callStaticObjectMethod( "java.util.TimeZone", "getTimeZone", "(Ljava/lang/String;)Ljava/util/TimeZone;", static_cast<jstring>(jo_ianaId.object()) );
+ const QString iana = QString::fromUtf8(ianaId);
+ androidTimeZone = QJNIObjectPrivate::callStaticObjectMethod(
+ "java.util.TimeZone", "getTimeZone", "(Ljava/lang/String;)Ljava/util/TimeZone;",
+ static_cast<jstring>(QJNIObjectPrivate::fromString(iana).object()));
+
+ // The ID or display name of the zone we've got, if it looks like what we asked for:
+ const auto match = [iana](const QJNIObjectPrivate &jname) -> QByteArray {
+ const QString name = jname.toString();
+ if (iana.compare(name, Qt::CaseInsensitive))
+ return name.toUtf8();
+
+ return QByteArray();
+ };
// Painfully, JNI gives us back a default zone object if it doesn't
// recognize the name; so check for whether ianaId is a recognized name of
// the zone object we got and ignore the zone if not.
// Try checking ianaId against getID(), getDisplayName():
- QJNIObjectPrivate jname = androidTimeZone.callObjectMethod("getID", "()Ljava/lang/String;");
- bool found = (jname.toString().toUtf8() == ianaId);
- for (int style = 1; !found && style-- > 0;) {
- for (int dst = 1; !found && dst-- > 0;) {
- jname = androidTimeZone.callObjectMethod("getDisplayName", "(ZI;)Ljava/lang/String;",
- bool(dst), style);
- found = (jname.toString().toUtf8() == ianaId);
+ m_id = match(androidTimeZone.callObjectMethod("getID", "()Ljava/lang/String;"));
+ for (int style = 1; m_id.isEmpty() && style-- > 0;) {
+ for (int dst = 1; m_id.isEmpty() && dst-- > 0;) {
+ m_id = match(androidTimeZone.callObjectMethod(
+ "getDisplayName", "(ZI;)Ljava/lang/String;", bool(dst), style));
}
}
-
- if (!found)
- m_id.clear();
- else if (ianaId.isEmpty())
- m_id = systemTimeZoneId();
- else
- m_id = ianaId;
}
QAndroidTimeZonePrivate *QAndroidTimeZonePrivate::clone() const
@@ -225,11 +228,10 @@ QTimeZonePrivate::Data QAndroidTimeZonePrivate::previousTransition(qint64 before
QByteArray QAndroidTimeZonePrivate::systemTimeZoneId() const
{
- QJNIObjectPrivate androidSystemTimeZone = QJNIObjectPrivate::callStaticObjectMethod("java.util.TimeZone", "getDefault", "()Ljava/util/TimeZone;");
- QJNIObjectPrivate systemTZIdAndroid = androidSystemTimeZone.callObjectMethod<jstring>("getID");
- QByteArray systemTZid = systemTZIdAndroid.toString().toUtf8();
-
- return systemTZid;
+ // Keep in sync with default constructor:
+ QJNIObjectPrivate androidSystemTimeZone = QJNIObjectPrivate::callStaticObjectMethod(
+ "java.util.TimeZone", "getDefault", "()Ljava/util/TimeZone;");
+ return androidSystemTimeZone.callObjectMethod<jstring>("getID").toString().toUtf8();
}
QList<QByteArray> QAndroidTimeZonePrivate::availableTimeZoneIds() const
diff --git a/src/corelib/time/qtimezoneprivate_icu.cpp b/src/corelib/time/qtimezoneprivate_icu.cpp
index 5570ce7571..8a92bbb387 100644
--- a/src/corelib/time/qtimezoneprivate_icu.cpp
+++ b/src/corelib/time/qtimezoneprivate_icu.cpp
@@ -273,7 +273,7 @@ static int ucalDaylightOffset(const QByteArray &id)
// Create the system default time zone
QIcuTimeZonePrivate::QIcuTimeZonePrivate()
- : m_ucal(0)
+ : m_ucal(nullptr)
{
// TODO No ICU C API to obtain sysem tz, assume default hasn't been changed
init(ucalDefaultTimeZoneId());
@@ -281,7 +281,7 @@ QIcuTimeZonePrivate::QIcuTimeZonePrivate()
// Create a named time zone
QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QByteArray &ianaId)
- : m_ucal(0)
+ : m_ucal(nullptr)
{
// Need to check validity here as ICu will create a GMT tz if name is invalid
if (availableTimeZoneIds().contains(ianaId))
@@ -289,14 +289,14 @@ QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QByteArray &ianaId)
}
QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QIcuTimeZonePrivate &other)
- : QTimeZonePrivate(other), m_ucal(0)
+ : QTimeZonePrivate(other), m_ucal(nullptr)
{
// Clone the ucal so we don't close the shared object
UErrorCode status = U_ZERO_ERROR;
m_ucal = ucal_clone(other.m_ucal, &status);
if (!U_SUCCESS(status)) {
m_id.clear();
- m_ucal = 0;
+ m_ucal = nullptr;
}
}
@@ -322,7 +322,7 @@ void QIcuTimeZonePrivate::init(const QByteArray &ianaId)
if (!U_SUCCESS(status)) {
m_id.clear();
- m_ucal = 0;
+ m_ucal = nullptr;
}
}
@@ -493,7 +493,7 @@ QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds(int offsetFromUtc) c
// TODO Available directly in C++ api but not C api, from 4.8 onwards new filter method works
#if U_ICU_VERSION_MAJOR_NUM >= 49 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM == 8)
UErrorCode status = U_ZERO_ERROR;
- UEnumeration *uenum = ucal_openTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, 0,
+ UEnumeration *uenum = ucal_openTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, nullptr,
&offsetFromUtc, &status);
QList<QByteArray> result;
if (U_SUCCESS(status))
diff --git a/src/corelib/time/qtimezoneprivate_mac.mm b/src/corelib/time/qtimezoneprivate_mac.mm
index d3c4fbe5da..1fb48a31d3 100644
--- a/src/corelib/time/qtimezoneprivate_mac.mm
+++ b/src/corelib/time/qtimezoneprivate_mac.mm
@@ -1,5 +1,6 @@
/****************************************************************************
**
+** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2013 John Layt <jlayt@kde.org>
** Contact: https://www.qt.io/licensing/
**
@@ -59,22 +60,24 @@ QT_BEGIN_NAMESPACE
// Create the system default time zone
QMacTimeZonePrivate::QMacTimeZonePrivate()
- : m_nstz(0)
{
- init(systemTimeZoneId());
+ // Reset the cached system tz then instantiate it:
+ [NSTimeZone resetSystemTimeZone];
+ m_nstz = [NSTimeZone.systemTimeZone retain];
+ Q_ASSERT(m_nstz);
+ m_id = QString::fromNSString(m_nstz.name).toUtf8();
}
// Create a named time zone
QMacTimeZonePrivate::QMacTimeZonePrivate(const QByteArray &ianaId)
- : m_nstz(0)
+ : m_nstz(nil)
{
init(ianaId);
}
QMacTimeZonePrivate::QMacTimeZonePrivate(const QMacTimeZonePrivate &other)
- : QTimeZonePrivate(other), m_nstz(0)
+ : QTimeZonePrivate(other), m_nstz([other.m_nstz copy])
{
- m_nstz = [other.m_nstz copy];
}
QMacTimeZonePrivate::~QMacTimeZonePrivate()
@@ -94,11 +97,21 @@ void QMacTimeZonePrivate::init(const QByteArray &ianaId)
if (m_nstz)
m_id = ianaId;
}
+ if (!m_nstz) {
+ // macOS has been seen returning a systemTimeZone which reports its name
+ // as Asia/Kolkata, which doesn't appear in knownTimeZoneNames (which
+ // calls the zone Asia/Calcutta). So explicitly check for the name
+ // systemTimeZoneId() returns, and use systemTimeZone if we get it:
+ m_nstz = [NSTimeZone.systemTimeZone retain];
+ Q_ASSERT(m_nstz);
+ if (QString::fromNSString(m_nstz.name).toUtf8() == ianaId)
+ m_id = ianaId;
+ }
}
QString QMacTimeZonePrivate::comment() const
{
- return QString::fromNSString([m_nstz description]);
+ return QString::fromNSString(m_nstz.description);
}
QString QMacTimeZonePrivate::displayName(QTimeZone::TimeType timeType,
@@ -201,7 +214,7 @@ bool QMacTimeZonePrivate::hasTransitions() const
// TODO Not sure what is returned in event of no transitions, assume will be before requested date
NSDate *epoch = [NSDate dateWithTimeIntervalSince1970:0];
const NSDate *date = [m_nstz nextDaylightSavingTimeTransitionAfterDate:epoch];
- const bool result = ([date timeIntervalSince1970] > [epoch timeIntervalSince1970]);
+ const bool result = (date.timeIntervalSince1970 > epoch.timeIntervalSince1970);
return result;
}
@@ -211,7 +224,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::nextTransition(qint64 afterMSecsSinc
const NSTimeInterval seconds = afterMSecsSinceEpoch / 1000.0;
NSDate *nextDate = [NSDate dateWithTimeIntervalSince1970:seconds];
nextDate = [m_nstz nextDaylightSavingTimeTransitionAfterDate:nextDate];
- const NSTimeInterval nextSecs = [nextDate timeIntervalSince1970];
+ const NSTimeInterval nextSecs = nextDate.timeIntervalSince1970;
if (nextDate == nil || nextSecs <= seconds) {
[nextDate release];
return invalidData();
@@ -237,7 +250,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::previousTransition(qint64 beforeMSec
NSDate *nextDate = [NSDate dateWithTimeIntervalSince1970:nextSecs];
nextDate = [m_nstz nextDaylightSavingTimeTransitionAfterDate:nextDate];
if (nextDate != nil
- && (tranSecs = [nextDate timeIntervalSince1970]) < endSecs) {
+ && (tranSecs = nextDate.timeIntervalSince1970) < endSecs) {
// There's a transition within the last year before endSecs:
nextSecs = tranSecs;
} else {
@@ -246,7 +259,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::previousTransition(qint64 beforeMSec
nextDate = [m_nstz nextDaylightSavingTimeTransitionAfterDate:nextDate];
if (nextDate != nil) {
NSTimeInterval lateSecs = nextSecs;
- nextSecs = [nextDate timeIntervalSince1970];
+ nextSecs = nextDate.timeIntervalSince1970;
Q_ASSERT(nextSecs <= endSecs - year || nextSecs == tranSecs);
/*
We're looking at the first ever transition for our zone, at
@@ -272,8 +285,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::previousTransition(qint64 beforeMSec
NSTimeInterval middle = nextSecs / 2 + lateSecs / 2;
NSDate *split = [NSDate dateWithTimeIntervalSince1970:middle];
split = [m_nstz nextDaylightSavingTimeTransitionAfterDate:split];
- if (split != nil
- && (tranSecs = [split timeIntervalSince1970]) < endSecs) {
+ if (split != nil && (tranSecs = split.timeIntervalSince1970) < endSecs) {
nextDate = split;
nextSecs = tranSecs;
} else {
@@ -290,7 +302,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::previousTransition(qint64 beforeMSec
while (nextDate != nil && nextSecs < endSecs) {
prevSecs = nextSecs;
nextDate = [m_nstz nextDaylightSavingTimeTransitionAfterDate:nextDate];
- nextSecs = [nextDate timeIntervalSince1970];
+ nextSecs = nextDate.timeIntervalSince1970;
if (nextSecs <= prevSecs) // presumably no later data available
break;
}
@@ -305,18 +317,19 @@ QByteArray QMacTimeZonePrivate::systemTimeZoneId() const
{
// Reset the cached system tz then return the name
[NSTimeZone resetSystemTimeZone];
- return QString::fromNSString([[NSTimeZone systemTimeZone] name]).toUtf8();
+ Q_ASSERT(NSTimeZone.systemTimeZone);
+ return QString::fromNSString(NSTimeZone.systemTimeZone.name).toUtf8();
}
QList<QByteArray> QMacTimeZonePrivate::availableTimeZoneIds() const
{
- NSEnumerator *enumerator = [[NSTimeZone knownTimeZoneNames] objectEnumerator];
- QByteArray tzid = QString::fromNSString([enumerator nextObject]).toUtf8();
+ NSEnumerator *enumerator = NSTimeZone.knownTimeZoneNames.objectEnumerator;
+ QByteArray tzid = QString::fromNSString(enumerator.nextObject).toUtf8();
QList<QByteArray> list;
while (!tzid.isEmpty()) {
list << tzid;
- tzid = QString::fromNSString([enumerator nextObject]).toUtf8();
+ tzid = QString::fromNSString(enumerator.nextObject).toUtf8();
}
std::sort(list.begin(), list.end());
diff --git a/src/corelib/time/qtimezoneprivate_tz.cpp b/src/corelib/time/qtimezoneprivate_tz.cpp
index 3c2695a789..5e55c6897d 100644
--- a/src/corelib/time/qtimezoneprivate_tz.cpp
+++ b/src/corelib/time/qtimezoneprivate_tz.cpp
@@ -512,7 +512,7 @@ PosixZone PosixZone::parse(const char *&pos, const char *end)
if (zoneEnd < end && (zoneEnd[0] == '+' || zoneEnd[0] == '-'))
++zoneEnd;
while (zoneEnd < end) {
- if (strchr(offsetChars, char(*zoneEnd)) == NULL)
+ if (strchr(offsetChars, char(*zoneEnd)) == nullptr)
break;
++zoneEnd;
}