summaryrefslogtreecommitdiffstats
path: root/src/corelib/time/qdatetime.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/corelib/time/qdatetime.cpp')
-rw-r--r--src/corelib/time/qdatetime.cpp4392
1 files changed, 2688 insertions, 1704 deletions
diff --git a/src/corelib/time/qdatetime.cpp b/src/corelib/time/qdatetime.cpp
index 1263353ee1..687f174c07 100644
--- a/src/corelib/time/qdatetime.cpp
+++ b/src/corelib/time/qdatetime.cpp
@@ -1,99 +1,56 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qplatformdefs.h"
+// Copyright (C) 2022 The Qt Company Ltd.
+// Copyright (C) 2021 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qdatetime.h"
+
+#include "qcalendar.h"
+#include "qdatastream.h"
+#include "qdebug.h"
+#include "qlocale.h"
+#include "qset.h"
+
+#include "private/qcalendarmath_p.h"
#include "private/qdatetime_p.h"
#if QT_CONFIG(datetimeparser)
#include "private/qdatetimeparser_p.h"
#endif
-
-#include "qdatastream.h"
-#include "qset.h"
-#include "qlocale.h"
-#include "qdatetime.h"
-#if QT_CONFIG(timezone)
-#include "qtimezoneprivate_p.h"
+#ifdef Q_OS_DARWIN
+#include "private/qcore_mac_p.h"
#endif
-#include "qdebug.h"
-#ifndef Q_OS_WIN
-#include <locale.h>
+#include "private/qgregoriancalendar_p.h"
+#include "private/qlocale_tools_p.h"
+#include "private/qlocaltime_p.h"
+#include "private/qnumeric_p.h"
+#include "private/qstringconverter_p.h"
+#include "private/qstringiterator_p.h"
+#if QT_CONFIG(timezone)
+#include "private/qtimezoneprivate_p.h"
#endif
#include <cmath>
-#ifdef Q_CC_MINGW
-# include <unistd.h> // Define _POSIX_THREAD_SAFE_FUNCTIONS to obtain localtime_r()
-#endif
-#include <time.h>
#ifdef Q_OS_WIN
# include <qt_windows.h>
#endif
-#if defined(Q_OS_MAC)
-#include <private/qcore_mac_p.h>
-#endif
-
-#include "qcalendar.h"
-#include "qgregoriancalendar_p.h"
+#include <private/qtools_p.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+using namespace QtPrivate::DateTimeConstants;
+using namespace QtMiscUtils;
+
/*****************************************************************************
Date/Time Constants
*****************************************************************************/
-enum {
- SECS_PER_DAY = 86400,
- MSECS_PER_DAY = 86400000,
- SECS_PER_HOUR = 3600,
- MSECS_PER_HOUR = 3600000,
- SECS_PER_MIN = 60,
- MSECS_PER_MIN = 60000,
- TIME_T_MAX = 2145916799, // int maximum 2037-12-31T23:59:59 UTC
- JULIAN_DAY_FOR_EPOCH = 2440588 // result of julianDayFromDate(1970, 1, 1)
-};
-
/*****************************************************************************
QDate static helper functions
*****************************************************************************/
+static_assert(std::is_trivially_copyable_v<QCalendar::YearMonthDay>);
-static inline QDate fixedDate(QCalendar::YearMonthDay &&parts, QCalendar cal)
+static inline QDate fixedDate(QCalendar::YearMonthDay parts, QCalendar cal)
{
if ((parts.year < 0 && !cal.isProleptic()) || (parts.year == 0 && !cal.hasYearZero()))
return QDate();
@@ -102,13 +59,13 @@ static inline QDate fixedDate(QCalendar::YearMonthDay &&parts, QCalendar cal)
return cal.dateFromParts(parts);
}
-static inline QDate fixedDate(QCalendar::YearMonthDay &&parts)
+static inline QDate fixedDate(QCalendar::YearMonthDay parts)
{
if (parts.year) {
parts.day = qMin(parts.day, QGregorianCalendar::monthLength(parts.month, parts.year));
- qint64 jd;
- if (QGregorianCalendar::julianFromParts(parts.year, parts.month, parts.day, &jd))
- return QDate::fromJulianDay(jd);
+ const auto jd = QGregorianCalendar::julianFromParts(parts.year, parts.month, parts.day);
+ if (jd)
+ return QDate::fromJulianDay(*jd);
}
return QDate();
}
@@ -126,7 +83,7 @@ static const char qt_shortMonthNames[][4] = {
static int fromShortMonthName(QStringView monthName)
{
for (unsigned int i = 0; i < sizeof(qt_shortMonthNames) / sizeof(qt_shortMonthNames[0]); ++i) {
- if (monthName == QLatin1String(qt_shortMonthNames[i], 3))
+ if (monthName == QLatin1StringView(qt_shortMonthNames[i], 3))
return i + 1;
}
return -1;
@@ -134,10 +91,46 @@ static int fromShortMonthName(QStringView monthName)
#endif // textdate
#if QT_CONFIG(datestring) // depends on, so implies, textdate
+namespace {
+using ParsedInt = QSimpleParsedNumber<qulonglong>;
+
+/*
+ Reads a whole number that must be the whole text.
+*/
+ParsedInt readInt(QLatin1StringView text)
+{
+ // Various date formats' fields (e.g. all in ISO) should not accept spaces
+ // or signs, so check that the string starts with a digit and that qstrntoull()
+ // converted the whole string.
+
+ if (text.isEmpty() || !isAsciiDigit(text.front().toLatin1()))
+ return {};
+
+ QSimpleParsedNumber res = qstrntoull(text.data(), text.size(), 10);
+ return res.used == text.size() ? res : ParsedInt{};
+}
+
+ParsedInt readInt(QStringView text)
+{
+ if (text.isEmpty())
+ return {};
+
+ // Converting to Latin-1 because QStringView::toULongLong() works with
+ // US-ASCII only by design anyway.
+ // Also QStringView::toULongLong() can't be used here as it will happily ignore
+ // spaces and accept signs; but various date formats' fields (e.g. all in ISO)
+ // should not.
+ QVarLengthArray<char> latin1(text.size());
+ QLatin1::convertFromUnicode(latin1.data(), text);
+ return readInt(QLatin1StringView{latin1.data(), latin1.size()});
+}
+
+} // namespace
+
struct ParsedRfcDateTime {
QDate date;
QTime time;
- int utcOffset;
+ int utcOffset = 0;
};
static int shortDayFromName(QStringView name)
@@ -150,23 +143,28 @@ static int shortDayFromName(QStringView name)
return 0;
}
-static ParsedRfcDateTime rfcDateImpl(const QString &s)
+static ParsedRfcDateTime rfcDateImpl(QStringView s)
{
// Matches "[ddd,] dd MMM yyyy[ hh:mm[:ss]] [±hhmm]" - correct RFC 822, 2822, 5322 format -
// or "ddd MMM dd[ hh:mm:ss] yyyy [±hhmm]" - permissive RFC 850, 1036 (read only)
ParsedRfcDateTime result;
- auto words = QStringView{s}.split(QLatin1Char(' '), Qt::SkipEmptyParts);
- if (words.size() < 3 || words.size() > 6)
+ QVarLengthArray<QStringView, 6> words;
+
+ auto tokens = s.tokenize(u' ', Qt::SkipEmptyParts);
+ auto it = tokens.begin();
+ for (int i = 0; i < 6 && it != tokens.end(); ++i, ++it)
+ words.emplace_back(*it);
+
+ if (words.size() < 3 || it != tokens.end())
return result;
- const QChar colon(QLatin1Char(':'));
- const QLocale C = QLocale::c();
+ const QChar colon(u':');
bool ok = true;
QDate date;
const auto isShortName = [](QStringView name) {
- return (name.length() == 3 && name.at(0).isUpper()
- && name.at(1).isLower() && name.at(2).isLower());
+ return (name.size() == 3 && name[0].isUpper()
+ && name[1].isLower() && name[2].isLower());
};
/* Reject entirely (return) if the string is malformed; however, if the date
@@ -176,10 +174,13 @@ static ParsedRfcDateTime rfcDateImpl(const QString &s)
do { // "loop" so that we can use break on merely invalid, but "right shape" date.
QStringView dayName;
bool rfcX22 = true;
- if (words.at(0).endsWith(QLatin1Char(','))) {
- dayName = words.takeFirst().chopped(1);
- } else if (!words.at(0).at(0).isDigit()) {
- dayName = words.takeFirst();
+ const QStringView maybeDayName = words.front();
+ if (maybeDayName.endsWith(u',')) {
+ dayName = maybeDayName.chopped(1);
+ words.erase(words.begin());
+ } else if (!maybeDayName.front().isDigit()) {
+ dayName = maybeDayName;
+ words.erase(words.begin());
rfcX22 = false;
} // else: dayName is not specified (so we can only be RFC *22)
if (words.size() < 3 || words.size() > 5)
@@ -231,36 +232,40 @@ static ParsedRfcDateTime rfcDateImpl(const QString &s)
// Time: [hh:mm[:ss]]
QTime time;
if (words.size() && words.at(0).contains(colon)) {
- const QStringView when = words.takeFirst();
- if (when.at(2) != colon || (when.size() == 8 ? when.at(5) != colon : when.size() > 5))
+ const QStringView when = words.front();
+ words.erase(words.begin());
+ if (when.size() < 5 || when[2] != colon
+ || (when.size() == 8 ? when[5] != colon : when.size() > 5)) {
return result;
- const int hour = C.toInt(when.left(2), &ok);
+ }
+ const int hour = when.first(2).toInt(&ok);
if (!ok)
return result;
- const int minute = C.toInt(when.mid(3, 2), &ok);
+ const int minute = when.sliced(3, 2).toInt(&ok);
if (!ok)
return result;
- const auto secs = when.size() == 8 ? C.toInt(when.right(2), &ok) : 0;
+ const auto secs = when.size() == 8 ? when.last(2).toInt(&ok) : 0;
if (!ok)
return result;
time = QTime(hour, minute, secs);
}
- // Offset: [±hhmm]
+ // Offset: [±hh[mm]]
int offset = 0;
if (words.size()) {
- const QStringView zone = words.takeFirst();
+ const QStringView zone = words.front();
+ words.erase(words.begin());
if (words.size() || !(zone.size() == 3 || zone.size() == 5))
return result;
bool negate = false;
- if (zone.at(0) == QLatin1Char('-'))
+ if (zone[0] == u'-')
negate = true;
- else if (zone.at(0) != QLatin1Char('+'))
+ else if (zone[0] != u'+')
return result;
- const int hour = C.toInt(zone.mid(1, 2), &ok);
+ const int hour = zone.sliced(1, 2).toInt(&ok);
if (!ok)
return result;
- const auto minute = zone.size() > 3 ? C.toInt(zone.mid(3, 2), &ok) : 0;
+ const auto minute = zone.size() == 5 ? zone.last(2).toInt(&ok) : 0;
if (!ok)
return result;
offset = (hour * 60 + minute) * 60;
@@ -275,24 +280,24 @@ static ParsedRfcDateTime rfcDateImpl(const QString &s)
}
#endif // datestring
-// Return offset in [+-]HH:mm format
+// Return offset in ±HH:mm format
static QString toOffsetString(Qt::DateFormat format, int offset)
{
return QString::asprintf("%c%02d%s%02d",
offset >= 0 ? '+' : '-',
- qAbs(offset) / SECS_PER_HOUR,
+ qAbs(offset) / int(SECS_PER_HOUR),
// Qt::ISODate puts : between the hours and minutes, but Qt:TextDate does not:
format == Qt::TextDate ? "" : ":",
(qAbs(offset) / 60) % 60);
}
#if QT_CONFIG(datestring)
-// Parse offset in [+-]HH[[:]mm] format
+// Parse offset in ±HH[[:]mm] format
static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
{
*valid = false;
- const int size = offsetString.size();
+ const qsizetype size = offsetString.size();
if (size < 2 || size > 6)
return 0;
@@ -300,32 +305,31 @@ static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
int sign;
// First char must be + or -
- const QChar signChar = offsetString.at(0);
- if (signChar == QLatin1Char('+'))
+ const QChar signChar = offsetString[0];
+ if (signChar == u'+')
sign = 1;
- else if (signChar == QLatin1Char('-'))
+ else if (signChar == u'-')
sign = -1;
else
return 0;
// Split the hour and minute parts
- const QStringView time = offsetString.mid(1);
- qsizetype hhLen = time.indexOf(QLatin1Char(':'));
+ const QStringView time = offsetString.sliced(1);
+ qsizetype hhLen = time.indexOf(u':');
qsizetype mmIndex;
if (hhLen == -1)
- mmIndex = hhLen = 2; // [+-]HHmm or [+-]HH format
+ mmIndex = hhLen = 2; // ±HHmm or ±HH format
else
mmIndex = hhLen + 1;
- const QLocale C = QLocale::c();
- const QStringView hhRef = time.left(qMin(hhLen, time.size()));
+ const QStringView hhRef = time.first(qMin(hhLen, time.size()));
bool ok = false;
- const int hour = C.toInt(hhRef, &ok);
- if (!ok)
+ const int hour = hhRef.toInt(&ok);
+ if (!ok || hour > 23) // More generous than QTimeZone::MaxUtcOffsetSecs
return 0;
- const QStringView mmRef = time.mid(qMin(mmIndex, time.size()));
- const int minute = mmRef.isEmpty() ? 0 : C.toInt(mmRef, &ok);
+ const QStringView mmRef = time.sliced(qMin(mmIndex, time.size()));
+ const int minute = mmRef.isEmpty() ? 0 : mmRef.toInt(&ok);
if (!ok || minute < 0 || minute > 59)
return 0;
@@ -344,6 +348,12 @@ static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
\reentrant
\brief The QDate class provides date functions.
+ \compares strong
+ \compareswith strong std::chrono::year_month_day std::chrono::year_month_day_last \
+ std::chrono::year_month_weekday std::chrono::year_month_weekday_last
+ These comparison operators are only available when using C++20.
+ \endcompareswith
+
A QDate object represents a particular day, regardless of calendar, locale
or other settings used when creating it or supplied by the system. It can
report the year, month and day of the month that represent the day with
@@ -431,8 +441,9 @@ static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
QDate::QDate(int y, int m, int d)
{
- if (!QGregorianCalendar::julianFromParts(y, m, d, &jd))
- jd = nullJd();
+ static_assert(maxJd() == JulianDayMax);
+ static_assert(minJd() == JulianDayMin);
+ jd = QGregorianCalendar::julianFromParts(y, m, d).value_or(nullJd());
}
QDate::QDate(int y, int m, int d, QCalendar cal)
@@ -441,6 +452,54 @@ QDate::QDate(int y, int m, int d, QCalendar cal)
}
/*!
+ \fn QDate::QDate(std::chrono::year_month_day date)
+ \fn QDate::QDate(std::chrono::year_month_day_last date)
+ \fn QDate::QDate(std::chrono::year_month_weekday date)
+ \fn QDate::QDate(std::chrono::year_month_weekday_last date)
+
+ \since 6.4
+
+ Constructs a QDate representing the same date as \a date. This allows for
+ easy interoperability between the Standard Library calendaring classes and
+ Qt datetime classes.
+
+ For example:
+
+ \snippet code/src_corelib_time_qdatetime.cpp 22
+
+ \note Unlike QDate, std::chrono::year and the related classes feature the
+ year zero. This means that if \a date is in the year zero or before, the
+ resulting QDate object will have an year one less than the one specified by
+ \a date.
+
+ \note This function requires C++20.
+*/
+
+/*!
+ \fn QDate QDate::fromStdSysDays(const std::chrono::sys_days &days)
+ \since 6.4
+
+ Returns a QDate \a days days after January 1st, 1970 (the UNIX epoch). If
+ \a days is negative, the returned date will be before the epoch.
+
+ \note This function requires C++20.
+
+ \sa toStdSysDays()
+*/
+
+/*!
+ \fn std::chrono::sys_days QDate::toStdSysDays() const
+
+ Returns the number of days between January 1st, 1970 (the UNIX epoch) and
+ this date, represented as a \c{std::chrono::sys_days} object. If this date
+ is before the epoch, the number of days will be negative.
+
+ \note This function requires C++20.
+
+ \sa fromStdSysDays(), daysTo()
+*/
+
+/*!
\fn bool QDate::isNull() const
Returns \c true if the date is null; otherwise returns \c false. A null
@@ -643,9 +702,8 @@ int QDate::dayOfYear(QCalendar cal) const
int QDate::dayOfYear() const
{
if (isValid()) {
- qint64 first;
- if (QGregorianCalendar::julianFromParts(year(), 1, 1, &first))
- return jd - first + 1;
+ if (const auto first = QGregorianCalendar::julianFromParts(year(), 1, 1))
+ return jd - *first + 1;
}
return 0;
}
@@ -736,17 +794,49 @@ int QDate::weekNumber(int *yearNumber) const
// This could be replaced by use of QIso8601Calendar, once we implement it.
// The Thursday of the same week determines our answer:
- QDate thursday(addDays(4 - dayOfWeek()));
- int year = thursday.year();
+ const QDate thursday(addDays(4 - dayOfWeek()));
+ if (yearNumber)
+ *yearNumber = thursday.year();
+
// Week n's Thurs's DOY has 1 <= DOY - 7*(n-1) < 8, so 0 <= DOY + 6 - 7*n < 7:
- int week = (thursday.dayOfYear() + 6) / 7;
+ return (thursday.dayOfYear() + 6) / 7;
+}
- if (yearNumber)
- *yearNumber = year;
- return week;
+#if QT_DEPRECATED_SINCE(6, 9)
+// Only called by deprecated methods (so bootstrap builds warn unused without this #if).
+static QTimeZone asTimeZone(Qt::TimeSpec spec, int offset, const char *warner)
+{
+ if (warner) {
+ switch (spec) {
+ case Qt::TimeZone:
+ qWarning("%s: Pass a QTimeZone instead of Qt::TimeZone.", warner);
+ break;
+ case Qt::LocalTime:
+ if (offset) {
+ qWarning("%s: Ignoring offset (%d seconds) passed with Qt::LocalTime",
+ warner, offset);
+ }
+ break;
+ case Qt::UTC:
+ if (offset) {
+ qWarning("%s: Ignoring offset (%d seconds) passed with Qt::UTC",
+ warner, offset);
+ offset = 0;
+ }
+ break;
+ case Qt::OffsetFromUTC:
+ break;
+ }
+ }
+ return QTimeZone::isUtcOrFixedOffset(spec)
+ ? QTimeZone::fromSecondsAheadOfUtc(offset)
+ : QTimeZone(QTimeZone::LocalTime);
}
+#endif // Helper for 6.9 deprecation
-static bool inDateTimeRange(qint64 jd, bool start)
+enum class DaySide { Start, End };
+
+static bool inDateTimeRange(qint64 jd, DaySide side)
{
using Bounds = std::numeric_limits<qint64>;
if (jd < Bounds::min() + JULIAN_DAY_FOR_EPOCH)
@@ -754,30 +844,24 @@ static bool inDateTimeRange(qint64 jd, bool start)
jd -= JULIAN_DAY_FOR_EPOCH;
const qint64 maxDay = Bounds::max() / MSECS_PER_DAY;
const qint64 minDay = Bounds::min() / MSECS_PER_DAY - 1;
- // (Divisions rounded towards zero, as MSECS_PER_DAY has factors other than two.)
+ // (Divisions rounded towards zero, as MSECS_PER_DAY is even - so doesn't
+ // divide max() - and has factors other than two, so doesn't divide min().)
// Range includes start of last day and end of first:
- if (start)
+ switch (side) {
+ case DaySide::Start:
return jd > minDay && jd <= maxDay;
- return jd >= minDay && jd < maxDay;
+ case DaySide::End:
+ return jd >= minDay && jd < maxDay;
+ }
+ Q_UNREACHABLE_RETURN(false);
}
-static QDateTime toEarliest(QDate day, const QDateTime &form)
+static QDateTime toEarliest(QDate day, const QTimeZone &zone)
{
- const Qt::TimeSpec spec = form.timeSpec();
- const int offset = (spec == Qt::OffsetFromUTC) ? form.offsetFromUtc() : 0;
-#if QT_CONFIG(timezone)
- QTimeZone zone;
- if (spec == Qt::TimeZone)
- zone = form.timeZone();
-#endif
- auto moment = [=](QTime time) {
- switch (spec) {
- case Qt::OffsetFromUTC: return QDateTime(day, time, spec, offset);
-#if QT_CONFIG(timezone)
- case Qt::TimeZone: return QDateTime(day, time, zone);
-#endif
- default: return QDateTime(day, time, spec);
- }
+ Q_ASSERT(!zone.isUtcOrFixedOffset());
+ // And the day starts in a gap. First find a moment not in that gap.
+ const auto moment = [=](QTime time) {
+ return QDateTime(day, time, zone, QDateTime::TransitionResolution::Reject);
};
// Longest routine time-zone transition is 2 hours:
QDateTime when = moment(QTime(2, 0));
@@ -795,8 +879,9 @@ static QDateTime toEarliest(QDate day, const QDateTime &form)
int low = 0;
// Binary chop to the right minute
while (high > low + 1) {
- int mid = (high + low) / 2;
- QDateTime probe = moment(QTime(mid / 60, mid % 60));
+ const int mid = (high + low) / 2;
+ const QDateTime probe = QDateTime(day, QTime(mid / 60, mid % 60), zone,
+ QDateTime::TransitionResolution::PreferBefore);
if (probe.isValid() && probe.date() == day) {
high = mid;
when = probe;
@@ -804,104 +889,134 @@ static QDateTime toEarliest(QDate day, const QDateTime &form)
low = mid;
}
}
- return when;
+ // Transitions out of local solar mean time, and the few international
+ // date-line crossings before that (Alaska, Philippines), may have happened
+ // between minute boundaries. Don't try to fix milliseconds.
+ if (QDateTime p = moment(when.time().addSecs(-1)); Q_UNLIKELY(p.isValid() && p.date() == day)) {
+ high *= 60;
+ low *= 60;
+ while (high > low + 1) {
+ const int mid = (high + low) / 2;
+ const int min = mid / 60;
+ const QDateTime probe = moment(QTime(min / 60, min % 60, mid % 60));
+ if (probe.isValid() && probe.date() == day) {
+ high = mid;
+ when = probe;
+ } else {
+ low = mid;
+ }
+ }
+ }
+ return when.isValid() ? when : QDateTime();
}
/*!
\since 5.14
- \fn QDateTime QDate::startOfDay(Qt::TimeSpec spec, int offsetSeconds) const
- \fn QDateTime QDate::startOfDay(const QTimeZone &zone) const
- Returns the start-moment of the day. Usually, this shall be midnight at the
- start of the day: however, if a time-zone transition causes the given date
- to skip over that midnight (e.g. a DST spring-forward skipping from the end
- of the previous day to 01:00 of the new day), the actual earliest time in
- the day is returned. This can only arise when the start-moment is specified
- in terms of a time-zone (by passing its QTimeZone as \a zone) or in terms of
- local time (by passing Qt::LocalTime as \a spec; this is its default).
+ Returns the start-moment of the day.
+
+ When a day starts depends on a how time is described: each day starts and
+ ends earlier for those in time-zones further west and later for those in
+ time-zones further east. The time representation to use can be specified by
+ an optional time \a zone. The default time representation is the system's
+ local time.
- The \a offsetSeconds is ignored unless \a spec is Qt::OffsetFromUTC, when it
- gives the implied zone's offset from UTC. As UTC and such zones have no
- transitions, the start of the day is QTime(0, 0) in these cases.
+ Usually, the start of the day is midnight, 00:00: however, if a time-zone
+ transition causes the given date to skip over that midnight (e.g. a DST
+ spring-forward skipping over the first hour of the day day), the actual
+ earliest time in the day is returned. This can only arise when the time
+ representation is a time-zone or local time.
+
+ When \a zone has a timeSpec() of is Qt::OffsetFromUTC or Qt::UTC, the time
+ representation has no transitions so the start of the day is QTime(0, 0).
In the rare case of a date that was entirely skipped (this happens when a
zone east of the international date-line switches to being west of it), the
- return shall be invalid. Passing Qt::TimeZone as \a spec (instead of
- passing a QTimeZone) or passing an invalid time-zone as \a zone will also
+ return shall be invalid. Passing an invalid time-zone as \a zone will also
produce an invalid result, as shall dates that start outside the range
representable by QDateTime.
\sa endOfDay()
*/
-QDateTime QDate::startOfDay(Qt::TimeSpec spec, int offsetSeconds) const
+QDateTime QDate::startOfDay(const QTimeZone &zone) const
{
- if (!inDateTimeRange(jd, true))
+ if (!inDateTimeRange(jd, DaySide::Start) || !zone.isValid())
return QDateTime();
- switch (spec) {
- case Qt::TimeZone: // should pass a QTimeZone instead of Qt::TimeZone
- qWarning() << "Called QDate::startOfDay(Qt::TimeZone) on" << *this;
- return QDateTime();
- case Qt::OffsetFromUTC:
- case Qt::UTC:
- return QDateTime(*this, QTime(0, 0), spec, offsetSeconds);
+ QDateTime when(*this, QTime(0, 0), zone,
+ QDateTime::TransitionResolution::RelativeToBefore);
+ if (Q_UNLIKELY(!when.isValid() || when.date() != *this)) {
+#if QT_CONFIG(timezone)
+ // The start of the day must have fallen in a spring-forward's gap; find the spring-forward:
+ if (zone.timeSpec() == Qt::TimeZone && zone.hasTransitions()) {
+ QTimeZone::OffsetData tran
+ // There's unlikely to be another transition before noon tomorrow.
+ // However, the whole of today may have been skipped !
+ = zone.previousTransition(QDateTime(addDays(1), QTime(12, 0), zone));
+ const QDateTime &at = tran.atUtc.toTimeZone(zone);
+ if (at.isValid() && at.date() == *this)
+ return at;
+ }
+#endif
- case Qt::LocalTime:
- if (offsetSeconds)
- qWarning("Ignoring offset (%d seconds) passed with Qt::LocalTime", offsetSeconds);
- break;
+ when = toEarliest(*this, zone);
}
- QDateTime when(*this, QTime(0, 0), spec);
- if (!when.isValid())
- when = toEarliest(*this, when);
- return when.isValid() ? when : QDateTime();
+ return when;
}
-#if QT_CONFIG(timezone)
/*!
- \overload
- \since 5.14
+ \overload
+ \since 6.5
*/
-QDateTime QDate::startOfDay(const QTimeZone &zone) const
+QDateTime QDate::startOfDay() const
{
- if (!inDateTimeRange(jd, true) || !zone.isValid())
- return QDateTime();
+ return startOfDay(QTimeZone::LocalTime);
+}
- QDateTime when(*this, QTime(0, 0), zone);
- if (when.isValid())
- return when;
+#if QT_DEPRECATED_SINCE(6, 9)
+/*!
+ \overload
+ \since 5.14
+ \deprecated [6.9] Use \c{startOfDay(const QTimeZone &)} instead.
- // The start of the day must have fallen in a spring-forward's gap; find the spring-forward:
- if (zone.hasTransitions()) {
- QTimeZone::OffsetData tran = zone.previousTransition(QDateTime(*this, QTime(23, 59, 59, 999), zone));
- const QDateTime &at = tran.atUtc.toTimeZone(zone);
- if (at.isValid() && at.date() == *this)
- return at;
- }
+ Returns the start-moment of the day.
- when = toEarliest(*this, when);
- return when.isValid() ? when : QDateTime();
+ When a day starts depends on a how time is described: each day starts and
+ ends earlier for those with higher offsets from UTC and later for those with
+ lower offsets from UTC. The time representation to use can be specified
+ either by a \a spec and \a offsetSeconds (ignored unless \a spec is
+ Qt::OffsetSeconds) or by a time zone.
+
+ Usually, the start of the day is midnight, 00:00: however, if a local time
+ transition causes the given date to skip over that midnight (e.g. a DST
+ spring-forward skipping over the first hour of the day day), the actual
+ earliest time in the day is returned.
+
+ When \a spec is Qt::OffsetFromUTC, \a offsetSeconds gives an implied zone's
+ offset from UTC. As UTC and such zones have no transitions, the start of the
+ day is QTime(0, 0) in these cases.
+
+ In the rare case of a date that was entirely skipped (this happens when a
+ zone east of the international date-line switches to being west of it), the
+ return shall be invalid. Passing Qt::TimeZone as \a spec (instead of passing
+ a QTimeZone) will also produce an invalid result, as shall dates that start
+ outside the range representable by QDateTime.
+*/
+QDateTime QDate::startOfDay(Qt::TimeSpec spec, int offsetSeconds) const
+{
+ QTimeZone zone = asTimeZone(spec, offsetSeconds, "QDate::startOfDay");
+ // If spec was Qt::TimeZone, zone's is Qt::LocalTime.
+ return zone.timeSpec() == spec ? startOfDay(zone) : QDateTime();
}
-#endif // timezone
+#endif // 6.9 deprecation
-static QDateTime toLatest(QDate day, const QDateTime &form)
+static QDateTime toLatest(QDate day, const QTimeZone &zone)
{
- const Qt::TimeSpec spec = form.timeSpec();
- const int offset = (spec == Qt::OffsetFromUTC) ? form.offsetFromUtc() : 0;
-#if QT_CONFIG(timezone)
- QTimeZone zone;
- if (spec == Qt::TimeZone)
- zone = form.timeZone();
-#endif
- auto moment = [=](QTime time) {
- switch (spec) {
- case Qt::OffsetFromUTC: return QDateTime(day, time, spec, offset);
-#if QT_CONFIG(timezone)
- case Qt::TimeZone: return QDateTime(day, time, zone);
-#endif
- default: return QDateTime(day, time, spec);
- }
+ Q_ASSERT(!zone.isUtcOrFixedOffset());
+ // And the day ends in a gap. First find a moment not in that gap:
+ const auto moment = [=](QTime time) {
+ return QDateTime(day, time, zone, QDateTime::TransitionResolution::Reject);
};
// Longest routine time-zone transition is 2 hours:
QDateTime when = moment(QTime(21, 59, 59, 999));
@@ -919,8 +1034,9 @@ static QDateTime toLatest(QDate day, const QDateTime &form)
int low = when.time().msecsSinceStartOfDay() / 60000;
// Binary chop to the right minute
while (high > low + 1) {
- int mid = (high + low) / 2;
- QDateTime probe = moment(QTime(mid / 60, mid % 60, 59, 999));
+ const int mid = (high + low) / 2;
+ const QDateTime probe = QDateTime(day, QTime(mid / 60, mid % 60, 59, 999), zone,
+ QDateTime::TransitionResolution::PreferAfter);
if (probe.isValid() && probe.date() == day) {
low = mid;
when = probe;
@@ -928,85 +1044,127 @@ static QDateTime toLatest(QDate day, const QDateTime &form)
high = mid;
}
}
- return when;
+ // Transitions out of local solar mean time, and the few international
+ // date-line crossings before that (Alaska, Philippines), may have happened
+ // between minute boundaries. Don't try to fix milliseconds.
+ if (QDateTime p = moment(when.time().addSecs(1)); Q_UNLIKELY(p.isValid() && p.date() == day)) {
+ high *= 60;
+ low *= 60;
+ while (high > low + 1) {
+ const int mid = (high + low) / 2;
+ const int min = mid / 60;
+ const QDateTime probe = moment(QTime(min / 60, min % 60, mid % 60, 999));
+ if (probe.isValid() && probe.date() == day) {
+ low = mid;
+ when = probe;
+ } else {
+ high = mid;
+ }
+ }
+ }
+ return when.isValid() ? when : QDateTime();
}
/*!
\since 5.14
- \fn QDateTime QDate::endOfDay(Qt::TimeSpec spec, int offsetSeconds) const
- \fn QDateTime QDate::endOfDay(const QTimeZone &zone) const
-
- Returns the end-moment of the day. Usually, this is one millisecond before
- the midnight at the end of the day: however, if a time-zone transition
- causes the given date to skip over that midnight (e.g. a DST spring-forward
- skipping from just before 23:00 to the start of the next day), the actual
- latest time in the day is returned. This can only arise when the
- start-moment is specified in terms of a time-zone (by passing its QTimeZone
- as \a zone) or in terms of local time (by passing Qt::LocalTime as \a spec;
- this is its default).
-
- The \a offsetSeconds is ignored unless \a spec is Qt::OffsetFromUTC, when it
- gives the implied zone's offset from UTC. As UTC and such zones have no
- transitions, the end of the day is QTime(23, 59, 59, 999) in these cases.
+
+ Returns the end-moment of the day.
+
+ When a day ends depends on a how time is described: each day starts and ends
+ earlier for those in time-zones further west and later for those in
+ time-zones further east. The time representation to use can be specified by
+ an optional time \a zone. The default time representation is the system's
+ local time.
+
+ Usually, the end of the day is one millisecond before the midnight, 24:00:
+ however, if a time-zone transition causes the given date to skip over that
+ moment (e.g. a DST spring-forward skipping over 23:00 and the following
+ hour), the actual latest time in the day is returned. This can only arise
+ when the time representation is a time-zone or local time.
+
+ When \a zone has a timeSpec() of Qt::OffsetFromUTC or Qt::UTC, the time
+ representation has no transitions so the end of the day is QTime(23, 59, 59,
+ 999).
In the rare case of a date that was entirely skipped (this happens when a
zone east of the international date-line switches to being west of it), the
- return shall be invalid. Passing Qt::TimeZone as \a spec (instead of
- passing a QTimeZone) will also produce an invalid result, as shall dates
- that end outside the range representable by QDateTime.
+ return shall be invalid. Passing an invalid time-zone as \a zone will also
+ produce an invalid result, as shall dates that end outside the range
+ representable by QDateTime.
\sa startOfDay()
*/
-QDateTime QDate::endOfDay(Qt::TimeSpec spec, int offsetSeconds) const
+QDateTime QDate::endOfDay(const QTimeZone &zone) const
{
- if (!inDateTimeRange(jd, false))
+ if (!inDateTimeRange(jd, DaySide::End) || !zone.isValid())
return QDateTime();
- switch (spec) {
- case Qt::TimeZone: // should pass a QTimeZone instead of Qt::TimeZone
- qWarning() << "Called QDate::endOfDay(Qt::TimeZone) on" << *this;
- return QDateTime();
- case Qt::UTC:
- case Qt::OffsetFromUTC:
- return QDateTime(*this, QTime(23, 59, 59, 999), spec, offsetSeconds);
+ QDateTime when(*this, QTime(23, 59, 59, 999), zone,
+ QDateTime::TransitionResolution::RelativeToAfter);
+ if (Q_UNLIKELY(!when.isValid() || when.date() != *this)) {
+#if QT_CONFIG(timezone)
+ // The end of the day must have fallen in a spring-forward's gap; find the spring-forward:
+ if (zone.timeSpec() == Qt::TimeZone && zone.hasTransitions()) {
+ QTimeZone::OffsetData tran
+ // It's unlikely there's been another transition since yesterday noon.
+ // However, the whole of today may have been skipped !
+ = zone.nextTransition(QDateTime(addDays(-1), QTime(12, 0), zone));
+ const QDateTime &at = tran.atUtc.toTimeZone(zone);
+ if (at.isValid() && at.date() == *this)
+ return at;
+ }
+#endif
- case Qt::LocalTime:
- if (offsetSeconds)
- qWarning("Ignoring offset (%d seconds) passed with Qt::LocalTime", offsetSeconds);
- break;
+ when = toLatest(*this, zone);
}
- QDateTime when(*this, QTime(23, 59, 59, 999), spec);
- if (!when.isValid())
- when = toLatest(*this, when);
- return when.isValid() ? when : QDateTime();
+ return when;
}
-#if QT_CONFIG(timezone)
/*!
- \overload
- \since 5.14
+ \overload
+ \since 6.5
*/
-QDateTime QDate::endOfDay(const QTimeZone &zone) const
+QDateTime QDate::endOfDay() const
{
- if (!inDateTimeRange(jd, false) || !zone.isValid())
- return QDateTime();
+ return endOfDay(QTimeZone::LocalTime);
+}
- QDateTime when(*this, QTime(23, 59, 59, 999), zone);
- if (when.isValid())
- return when;
+#if QT_DEPRECATED_SINCE(6, 9)
+/*!
+ \overload
+ \since 5.14
+ \deprecated [6.9] Use \c{endOfDay(const QTimeZone &) instead.
- // The end of the day must have fallen in a spring-forward's gap; find the spring-forward:
- if (zone.hasTransitions()) {
- QTimeZone::OffsetData tran = zone.nextTransition(QDateTime(*this, QTime(0, 0), zone));
- const QDateTime &at = tran.atUtc.toTimeZone(zone);
- if (at.isValid() && at.date() == *this)
- return at;
- }
+ Returns the end-moment of the day.
- when = toLatest(*this, when);
- return when.isValid() ? when : QDateTime();
+ When a day ends depends on a how time is described: each day starts and ends
+ earlier for those with higher offsets from UTC and later for those with
+ lower offsets from UTC. The time representation to use can be specified
+ either by a \a spec and \a offsetSeconds (ignored unless \a spec is
+ Qt::OffsetSeconds) or by a time zone.
+
+ Usually, the end of the day is one millisecond before the midnight, 24:00:
+ however, if a local time transition causes the given date to skip over that
+ moment (e.g. a DST spring-forward skipping over 23:00 and the following
+ hour), the actual latest time in the day is returned.
+
+ When \a spec is Qt::OffsetFromUTC, \a offsetSeconds gives the implied zone's
+ offset from UTC. As UTC and such zones have no transitions, the end of the
+ day is QTime(23, 59, 59, 999) in these cases.
+
+ In the rare case of a date that was entirely skipped (this happens when a
+ zone east of the international date-line switches to being west of it), the
+ return shall be invalid. Passing Qt::TimeZone as \a spec (instead of passing
+ a QTimeZone) will also produce an invalid result, as shall dates that end
+ outside the range representable by QDateTime.
+*/
+QDateTime QDate::endOfDay(Qt::TimeSpec spec, int offsetSeconds) const
+{
+ QTimeZone zone = asTimeZone(spec, offsetSeconds, "QDate::endOfDay");
+ // If spec was Qt::TimeZone, zone's is Qt::LocalTime.
+ return endOfDay(zone);
}
-#endif // timezone
+#endif // 6.9 deprecation
#if QT_CONFIG(datestring) // depends on, so implies, textdate
@@ -1019,7 +1177,8 @@ static QString toStringTextDate(QDate date)
const QLatin1Char sp(' ');
return QLocale::c().dayName(cal.dayOfWeek(date), QLocale::ShortFormat) + sp
+ cal.monthName(QLocale::c(), parts.month, parts.year, QLocale::ShortFormat)
- + sp + QString::number(parts.day) + sp + QString::number(parts.year);
+ // Documented to use 4-digit year
+ + sp + QString::asprintf("%d %04d", parts.day, parts.year);
}
}
return QString();
@@ -1082,12 +1241,14 @@ QString QDate::toString(Qt::DateFormat format) const
/*!
\fn QString QDate::toString(const QString &format, QCalendar cal) const
\fn QString QDate::toString(QStringView format, QCalendar cal) const
+ \since 5.14
Returns the date as a string. The \a format parameter determines the format
of the result string. If \a cal is supplied, it determines the calendar used
- to represent the date; it defaults to Gregorian.
+ to represent the date; it defaults to Gregorian. Prior to Qt 5.14, there was
+ no \a cal parameter and the Gregorian calendar was always used.
- These expressions may be used:
+ These expressions may be used in the \a format parameter:
\table
\header \li Expression \li Output
@@ -1127,25 +1288,41 @@ QString QDate::toString(Qt::DateFormat format) const
If the datetime is invalid, an empty string will be returned.
- \note If localized month and day names are desired, please switch to using
- QLocale::system().toString() as QDate methods shall change to use English (C
- locale) names at Qt 6.
+ \note Day and month names are given in English (C locale). To get localized
+ month and day names, use QLocale::system().toString().
- \sa fromString(), QDateTime::toString(), QTime::toString(), QLocale::toString()
+ \note If a format character is repeated more times than the longest
+ expression in the table above using it, this part of the format will be read
+ as several expressions with no separator between them; the longest above,
+ possibly repeated as many times as there are copies of it, ending with a
+ residue that may be a shorter expression. Thus \c{'MMMMMMMMMM'} for a date
+ in May will contribute \c{"MayMay05"} to the output.
+ \sa fromString(), QDateTime::toString(), QTime::toString(), QLocale::toString()
*/
QString QDate::toString(QStringView format, QCalendar cal) const
{
return QLocale::c().toString(*this, format, cal);
}
-#if QT_STRINGVIEW_LEVEL < 2
-QString QDate::toString(const QString &format, QCalendar cal) const
+// Out-of-line no-calendar overloads, since QCalendar is a non-trivial type
+/*!
+ \overload
+ \since 5.10
+*/
+QString QDate::toString(QStringView format) const
{
- return toString(qToStringViewIgnoringNull(format), cal);
+ return QLocale::c().toString(*this, format, QCalendar());
}
-#endif
+/*!
+ \overload
+ \since 4.6
+*/
+QString QDate::toString(const QString &format) const
+{
+ return QLocale::c().toString(*this, qToStringViewIgnoringNull(format), QCalendar());
+}
#endif // datestring
/*!
@@ -1160,11 +1337,9 @@ QString QDate::toString(const QString &format, QCalendar cal) const
*/
bool QDate::setDate(int year, int month, int day)
{
- if (QGregorianCalendar::julianFromParts(year, month, day, &jd))
- return true;
-
- jd = nullJd();
- return false;
+ const auto maybe = QGregorianCalendar::julianFromParts(year, month, day);
+ jd = maybe.value_or(nullJd());
+ return bool(maybe);
}
/*!
@@ -1226,12 +1401,35 @@ QDate QDate::addDays(qint64 ndays) const
if (isNull())
return QDate();
- // Due to limits on minJd() and maxJd() we know that any overflow
- // will be invalid and caught by fromJulianDay().
- return fromJulianDay(jd + ndays);
+ if (qint64 r; Q_UNLIKELY(qAddOverflow(jd, ndays, &r)))
+ return QDate();
+ else
+ return fromJulianDay(r);
}
/*!
+ \fn QDate QDate::addDuration(std::chrono::days ndays) const
+
+ \since 6.4
+
+ Returns a QDate object containing a date \a ndays later than the
+ date of this object (or earlier if \a ndays is negative).
+
+ Returns a null date if the current date is invalid or the new date is
+ out of range.
+
+ \note Adding durations expressed in \c{std::chrono::months} or
+ \c{std::chrono::years} does not yield the same result obtained by using
+ addMonths() or addYears(). The former are fixed durations, calculated in
+ relation to the solar year; the latter use the Gregorian calendar definitions
+ of months/years.
+
+ \note This function requires C++20.
+
+ \sa addMonths(), addYears(), daysTo()
+*/
+
+/*!
Returns a QDate object containing a date \a nmonths later than the
date of this object (or earlier if \a nmonths is negative).
@@ -1269,7 +1467,7 @@ QDate QDate::addMonths(int nmonths, QCalendar cal) const
count = (++parts.year || cal.hasYearZero()) ? cal.monthsInYear(parts.year) : 0;
}
- return fixedDate(std::move(parts), cal);
+ return fixedDate(parts, cal);
}
/*!
@@ -1301,7 +1499,7 @@ QDate QDate::addMonths(int nmonths) const
++parts.year;
}
- return fixedDate(std::move(parts));
+ return fixedDate(parts);
}
/*!
@@ -1330,11 +1528,11 @@ QDate QDate::addYears(int nyears, QCalendar cal) const
int old_y = parts.year;
parts.year += nyears;
- // If we just crossed (or hit) a missing year zero, adjust year by +/- 1:
+ // If we just crossed (or hit) a missing year zero, adjust year by ±1:
if (!cal.hasYearZero() && ((old_y > 0) != (parts.year > 0) || !parts.year))
parts.year += nyears > 0 ? +1 : -1;
- return fixedDate(std::move(parts), cal);
+ return fixedDate(parts, cal);
}
/*!
@@ -1353,11 +1551,11 @@ QDate QDate::addYears(int nyears) const
int old_y = parts.year;
parts.year += nyears;
- // If we just crossed (or hit) a missing year zero, adjust year by +/- 1:
+ // If we just crossed (or hit) a missing year zero, adjust year by ±1:
if ((old_y > 0) != (parts.year > 0) || !parts.year)
parts.year += nyears > 0 ? +1 : -1;
- return fixedDate(std::move(parts));
+ return fixedDate(parts);
}
/*!
@@ -1383,81 +1581,59 @@ qint64 QDate::daysTo(QDate d) const
/*!
- \fn bool QDate::operator==(QDate d) const
+ \fn bool QDate::operator==(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date and \a d represent the same day, otherwise
+ Returns \c true if \a lhs and \a rhs represent the same day, otherwise
\c false.
*/
/*!
- \fn bool QDate::operator!=(QDate d) const
+ \fn bool QDate::operator!=(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date is different from \a d; otherwise
+ Returns \c true if \a lhs and \a rhs represent distinct days; otherwise
returns \c false.
\sa operator==()
*/
/*!
- \fn bool QDate::operator<(QDate d) const
+ \fn bool QDate::operator<(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date is earlier than \a d; otherwise returns
- false.
+ Returns \c true if \a lhs is earlier than \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QDate::operator<=(QDate d) const
+ \fn bool QDate::operator<=(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date is earlier than or equal to \a d;
+ Returns \c true if \a lhs is earlier than or equal to \a rhs;
otherwise returns \c false.
*/
/*!
- \fn bool QDate::operator>(QDate d) const
+ \fn bool QDate::operator>(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date is later than \a d; otherwise returns
- false.
+ Returns \c true if \a lhs is later than \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QDate::operator>=(QDate d) const
+ \fn bool QDate::operator>=(const QDate &lhs, const QDate &rhs)
- Returns \c true if this date is later than or equal to \a d;
+ Returns \c true if \a lhs is later than or equal to \a rhs;
otherwise returns \c false.
*/
/*!
\fn QDate::currentDate()
- Returns the current date, as reported by the system clock.
+ Returns the system clock's current date.
\sa QTime::currentTime(), QDateTime::currentDateTime()
*/
#if QT_CONFIG(datestring) // depends on, so implies, textdate
-namespace {
-
-struct ParsedInt { int value = 0; bool ok = false; };
-
-/*
- /internal
-
- Read an int that must be the whole text. QStringView ::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;
-}
-
-}
/*!
+ \fn QDate QDate::fromString(const QString &string, Qt::DateFormat format)
+
Returns the QDate represented by the \a string, using the
\a format given, or an invalid date if the string cannot be
parsed.
@@ -1468,7 +1644,11 @@ ParsedInt readInt(QStringView text)
\sa toString(), QLocale::toDate()
*/
-QDate QDate::fromString(const QString &string, Qt::DateFormat format)
+/*!
+ \overload
+ \since 6.0
+*/
+QDate QDate::fromString(QStringView string, Qt::DateFormat format)
{
if (string.isEmpty())
return QDate();
@@ -1478,9 +1658,14 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
return rfcDateImpl(string).date;
default:
case Qt::TextDate: {
- auto parts = QStringView{string}.split(QLatin1Char(' '), Qt::SkipEmptyParts);
-
- if (parts.count() != 4)
+ // Documented as "ddd MMM d yyyy"
+ QVarLengthArray<QStringView, 4> parts;
+ auto tokens = string.tokenize(u' ', Qt::SkipEmptyParts);
+ auto it = tokens.begin();
+ for (int i = 0; i < 4 && it != tokens.end(); ++i, ++it)
+ parts.emplace_back(*it);
+
+ if (parts.size() != 4 || it != tokens.end())
return QDate();
bool ok = false;
@@ -1497,14 +1682,13 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
}
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);
+ if (string.size() >= 10 && string[4].isPunct() && string[7].isPunct()
+ && (string.size() == 10 || !string[10].isDigit())) {
+ const ParsedInt year = readInt(string.first(4));
+ const ParsedInt month = readInt(string.sliced(5, 2));
+ const ParsedInt day = readInt(string.sliced(8, 2));
+ if (year.ok() && year.result > 0 && year.result <= 9999 && month.ok() && day.ok())
+ return QDate(year.result, month.result, day.result);
}
break;
}
@@ -1512,7 +1696,7 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
}
/*!
- \fn QDate QDate::fromString(const QString &string, const QString &format, QCalendar cal)
+ \fn QDate QDate::fromString(const QString &string, const QString &format, int baseYear, QCalendar cal)
Returns the QDate represented by the \a string, using the \a
format given, or an invalid date if the string cannot be parsed.
@@ -1538,9 +1722,8 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
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.
+ \note Day and month names must be given in English (C locale). If localized
+ month and day names are to be recognized, use QLocale::system().toDate().
All other input characters will be treated as text. Any non-empty sequence
of characters enclosed in single quotes will also be treated (stripped of
@@ -1563,38 +1746,157 @@ QDate QDate::fromString(const QString &string, Qt::DateFormat format)
\table
\header \li Field \li Default value
- \row \li Year \li 1900
- \row \li Month \li 1
+ \row \li Year \li \a baseYear (or 1900)
+ \row \li Month \li 1 (January)
\row \li Day \li 1
\endtable
+ When \a format only specifies the last two digits of a year, the 100 years
+ starting at \a baseYear are the candidates first considered. Prior to 6.7
+ there was no \a baseYear parameter and 1900 was always used. This is the
+ default for \a baseYear, selecting a year from then to 1999. Passing 1976 as
+ \a baseYear will select a year from 1976 through 2075, for example. When the
+ format also includes month, day (of month) and day-of-week, these suffice to
+ imply the century. In such a case, a matching date is selected in the
+ nearest century to the one indicated by \a baseYear, prefering later over
+ earlier. See \l QCalendar::matchCenturyToWeekday() and \l {Date ambiguities}
+ for further details,
+
The following examples demonstrate the default values:
\snippet code/src_corelib_time_qdatetime.cpp 3
- \note If localized month and day names are used, please switch to using
- QLocale::system().toDate() as QDate methods shall change to only recognize
- English (C locale) names at Qt 6.
+ \note If a format character is repeated more times than the longest
+ expression in the table above using it, this part of the format will be read
+ as several expressions with no separator between them; the longest above,
+ possibly repeated as many times as there are copies of it, ending with a
+ residue that may be a shorter expression. Thus \c{'MMMMMMMMMM'} would match
+ \c{"MayMay05"} and set the month to May. Likewise, \c{'MMMMMM'} would match
+ \c{"May08"} and find it inconsistent, leading to an invalid date.
+
+ \section2 Date ambiguities
+
+ Different cultures use different formats for dates and, as a result, users
+ may mix up the order in which date fields should be given. For example,
+ \c{"Wed 28-Nov-01"} might mean either 2028 November 1st or the 28th of
+ November, 2001 (each of which happens to be a Wednesday). Using format
+ \c{"ddd yy-MMM-dd"} it shall be interpreted the first way, using \c{"ddd
+ dd-MMM-yy"} the second. However, which the user meant may depend on the way
+ the user normally writes dates, rather than the format the code was
+ expecting.
+
+ The example considered above mixed up day of the month and a two-digit year.
+ Similar confusion can arise over interchanging the month and day of the
+ month, when both are given as numbers. In these cases, including a day of
+ the week field in the date format can provide some redundancy, that may help
+ to catch errors of this kind. However, as in the example above, this is not
+ always effective: the interchange of two fields (or their meanings) may
+ produce dates with the same day of the week.
+
+ Including a day of the week in the format can also resolve the century of a
+ date specified using only the last two digits of its year. Unfortunately,
+ when combined with a date in which the user (or other source of data) has
+ mixed up two of the fields, this resolution can lead to finding a date which
+ does match the format's reading but isn't the one intended by its author.
+ Likewise, if the user simply gets the day of the week wrong, in an otherwise
+ correct date, this can lead a date in a different century. In each case,
+ finding a date in a different century can turn a wrongly-input date into a
+ wildly different one.
+
+ The best way to avoid date ambiguities is to use four-digit years and months
+ specified by name (whether full or abbreviated), ideally collected via user
+ interface idioms that make abundantly clear to the user which part of the
+ date they are selecting. Including a day of the week can also help by
+ providing the means to check consistency of the data. Where data comes from
+ the user, using a format supplied by a locale selected by the user, it is
+ best to use a long format as short formats are more likely to use two-digit
+ years. Of course, it is not always possible to control the format - data may
+ come from a source you do not control, for example.
+
+ As a result of these possible sources of confusion, particularly when you
+ cannot be sure an unambiguous format is in use, it is important to check
+ that the result of reading a string as a date is not just valid but
+ reasonable for the purpose for which it was supplied. If the result is
+ outside some range of reasonable values, it may be worth getting the user to
+ confirm their date selection, showing the date read from the string in a
+ long format that does include month name and four-digit year, to make it
+ easier for them to recognize any errors.
\sa toString(), QDateTime::fromString(), QTime::fromString(),
QLocale::toDate()
*/
-QDate QDate::fromString(const QString &string, const QString &format, QCalendar cal)
+/*!
+ \fn QDate QDate::fromString(QStringView string, QStringView format, QCalendar cal)
+ \overload
+ \since 6.0
+*/
+
+/*!
+ \overload
+ \since 6.0
+*/
+QDate QDate::fromString(const QString &string, QStringView format, int baseYear, QCalendar cal)
{
QDate date;
#if QT_CONFIG(datetimeparser)
QDateTimeParser dt(QMetaType::QDate, QDateTimeParser::FromString, cal);
dt.setDefaultLocale(QLocale::c());
if (dt.parseFormat(format))
- dt.fromString(string, &date, nullptr);
+ dt.fromString(string, &date, nullptr, baseYear);
#else
Q_UNUSED(string);
Q_UNUSED(format);
+ Q_UNUSED(baseYear);
Q_UNUSED(cal);
#endif
return date;
}
+
+/*!
+ \fn QDate QDate::fromString(const QString &string, const QString &format, QCalendar cal)
+ \overload
+ \since 5.14
+*/
+
+/*!
+ \fn QDate QDate::fromString(const QString &string, QStringView format, QCalendar cal)
+ \overload
+ \since 6.0
+*/
+
+/*!
+ \fn QDate QDate::fromString(QStringView string, QStringView format, int baseYear, QCalendar cal)
+ \overload
+ \since 6.7
+*/
+
+/*!
+ \fn QDate QDate::fromString(QStringView string, QStringView format, int baseYear)
+ \overload
+ \since 6.7
+
+ Uses a default-constructed QCalendar.
+*/
+
+/*!
+ \overload
+ \since 6.7
+
+ Uses a default-constructed QCalendar.
+*/
+QDate QDate::fromString(const QString &string, QStringView format, int baseYear)
+{
+ return fromString(string, format, baseYear, QCalendar());
+}
+
+/*!
+ \fn QDate QDate::fromString(const QString &string, const QString &format, int baseYear)
+ \overload
+ \since 6.7
+
+ Uses a default-constructed QCalendar.
+*/
#endif // datestring
/*!
@@ -1653,6 +1955,8 @@ bool QDate::isLeapYear(int y)
\brief The QTime class provides clock time functions.
+ \compares strong
+
A QTime object contains a clock time, which it can express as the numbers of
hours, minutes, seconds, and milliseconds since midnight. It provides
functions for comparing times and for manipulating a time by adding a number
@@ -1784,7 +2088,7 @@ int QTime::second() const
if (!isValid())
return -1;
- return (ds() / 1000)%SECS_PER_MIN;
+ return (ds() / MSECS_PER_SEC) % SECS_PER_MIN;
}
/*!
@@ -1800,7 +2104,7 @@ int QTime::msec() const
if (!isValid())
return -1;
- return ds() % 1000;
+ return ds() % MSECS_PER_SEC;
}
#if QT_CONFIG(datestring) // depends on, so implies, textdate
@@ -1867,19 +2171,49 @@ QString QTime::toString(Qt::DateFormat format) const
\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
- precision, including trailing zeroes where applicable (000 to 999).
+ \row \li z or zz
+ \li The fractional part of the second, to go after a decimal point,
+ without trailing zeroes. Thus \c{"s.z"} reports the seconds to full
+ available (millisecond) precision without trailing zeroes (0 to
+ 999). For example, \c{"s.z"} would produce \c{"0.25"} for a time a
+ quarter second into a minute.
+ \row \li zzz
+ \li The fractional part of the second, to millisecond precision,
+ including trailing zeroes where applicable (000 to 999). For
+ example, \c{"ss.zzz"} would produce \c{"00.250"} for a time a
+ quarter second into a minute.
\row \li AP or A
- \li Use AM/PM display. \e A/AP will be replaced by an upper-case
- version of either QLocale::amText() or QLocale::pmText().
+ \li Use AM/PM display. \c A/AP will be replaced by 'AM' or 'PM'. In
+ localized forms (only relevant to \l{QLocale::toString()}), the
+ locale-appropriate text is converted to upper-case.
\row \li ap or a
- \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")
+ \li Use am/pm display. \c a/ap will be replaced by 'am' or 'pm'. In
+ localized forms (only relevant to \l{QLocale::toString()}), the
+ locale-appropriate text is converted to lower-case.
+ \row \li aP or Ap
+ \li Use AM/PM display (since 6.3). \c aP/Ap will be replaced by 'AM' or
+ 'PM'. In localized forms (only relevant to
+ \l{QLocale::toString()}), the locale-appropriate text (returned by
+ \l{QLocale::amText()} or \l{QLocale::pmText()}) is used without
+ change of case.
+ \row \li t
+ \li The timezone abbreviation (for example "CEST"). Note that time zone
+ abbreviations are not unique. In particular, \l toString() cannot
+ parse this.
+ \row \li tt
+ \li The timezone's offset from UTC with no colon between the hours and
+ minutes (for example "+0200").
+ \row \li ttt
+ \li The timezone's offset from UTC with a colon between the hours and
+ minutes (for example "+02:00").
+ \row \li tttt
+ \li The timezone name (for example "Europe/Berlin"). Note that this
+ gives no indication of whether the datetime was in daylight-saving
+ time or standard time, which may lead to ambiguity if the datetime
+ falls in an hour repeated by a transition between the two. The name
+ used is the one provided by \l QTimeZone::displayName() with the \l
+ QTimeZone::LongName type. This may depend on the operating system
+ in use.
\endtable
Any non-empty sequence of characters enclosed in single quotes will be
@@ -1893,8 +2227,7 @@ QString QTime::toString(Qt::DateFormat format) const
produces "212" it could mean either the 2nd of December or the 21st of
February).
- Example format strings (assuming that the QTime is 14:13:09.042 and the system
- locale is \c{en_US})
+ Example format strings (assuming that the QTime is 14:13:09.042)
\table
\header \li Format \li Result
@@ -1904,26 +2237,24 @@ QString QTime::toString(Qt::DateFormat format) const
\endtable
If the time is invalid, an empty string will be returned.
- If \a format is empty, the default format "hh:mm:ss" is used.
- \note If localized forms of am or pm (the AP, ap, A or a formats) are
- desired, please switch to using QLocale::system().toString() as QTime
- methods shall change to use English (C locale) at Qt 6.
+ \note To get localized forms of AM or PM (the AP, ap, A, a, aP or Ap
+ formats), use QLocale::system().toString().
+
+ \note If a format character is repeated more times than the longest
+ expression in the table above using it, this part of the format will be read
+ as several expressions with no separator between them; the longest above,
+ possibly repeated as many times as there are copies of it, ending with a
+ residue that may be a shorter expression. Thus \c{'HHHHH'} for the time
+ 08:00 will contribute \c{"08088"} to the output.
\sa fromString(), QDate::toString(), QDateTime::toString(), QLocale::toString()
*/
+// ### Qt 7 The 't' format specifiers should be specific to QDateTime (compare fromString).
QString QTime::toString(QStringView format) const
{
return QLocale::c().toString(*this, format);
}
-
-#if QT_STRINGVIEW_VERSION < 2
-QString QTime::toString(const QString &format) const
-{
- return toString(qToStringViewIgnoringNull(format));
-}
-#endif
-
#endif // datestring
/*!
@@ -1943,7 +2274,8 @@ bool QTime::setHMS(int h, int m, int s, int ms)
mds = NullTime; // make this invalid
return false;
}
- mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
+ mds = ((h * MINS_PER_HOUR + m) * SECS_PER_MIN + s) * MSECS_PER_SEC + ms;
+ Q_ASSERT(mds >= 0 && mds < MSECS_PER_DAY);
return true;
}
@@ -1965,7 +2297,7 @@ bool QTime::setHMS(int h, int m, int s, int ms)
QTime QTime::addSecs(int s) const
{
s %= SECS_PER_DAY;
- return addMSecs(s * 1000);
+ return addMSecs(s * MSECS_PER_SEC);
}
/*!
@@ -1989,8 +2321,8 @@ int QTime::secsTo(QTime t) const
return 0;
// Truncate milliseconds as we do not want to consider them.
- int ourSeconds = ds() / 1000;
- int theirSeconds = t.ds() / 1000;
+ int ourSeconds = ds() / MSECS_PER_SEC;
+ int theirSeconds = t.ds() / MSECS_PER_SEC;
return theirSeconds - ourSeconds;
}
@@ -2009,15 +2341,8 @@ int QTime::secsTo(QTime t) const
QTime QTime::addMSecs(int ms) const
{
QTime t;
- if (isValid()) {
- if (ms < 0) {
- // %,/ not well-defined for -ve, so always work with +ve.
- int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
- t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
- } else {
- t.mds = (ds() + ms) % MSECS_PER_DAY;
- }
- }
+ if (isValid())
+ t.mds = QRoundingDown::qMod<MSECS_PER_DAY>(ds() + ms);
return t;
}
@@ -2044,40 +2369,40 @@ int QTime::msecsTo(QTime t) const
/*!
- \fn bool QTime::operator==(QTime t) const
+ \fn bool QTime::operator==(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is equal to \a t; otherwise returns \c false.
+ Returns \c true if \a lhs is equal to \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QTime::operator!=(QTime t) const
+ \fn bool QTime::operator!=(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is different from \a t; otherwise returns \c false.
+ Returns \c true if \a lhs is different from \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QTime::operator<(QTime t) const
+ \fn bool QTime::operator<(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is earlier than \a t; otherwise returns \c false.
+ Returns \c true if \a lhs is earlier than \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QTime::operator<=(QTime t) const
+ \fn bool QTime::operator<=(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is earlier than or equal to \a t;
+ Returns \c true if \a lhs is earlier than or equal to \a rhs;
otherwise returns \c false.
*/
/*!
- \fn bool QTime::operator>(QTime t) const
+ \fn bool QTime::operator>(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is later than \a t; otherwise returns \c false.
+ Returns \c true if \a lhs is later than \a rhs; otherwise returns \c false.
*/
/*!
- \fn bool QTime::operator>=(QTime t) const
+ \fn bool QTime::operator>=(const QTime &lhs, const QTime &rhs)
- Returns \c true if this time is later than or equal to \a t;
+ Returns \c true if \a lhs is later than or equal to \a rhs;
otherwise returns \c false.
*/
@@ -2119,97 +2444,121 @@ int QTime::msecsTo(QTime t) const
static QTime fromIsoTimeString(QStringView string, Qt::DateFormat format, bool *isMidnight24)
{
+ Q_ASSERT(format == Qt::TextDate || format == Qt::ISODate || format == Qt::ISODateWithMs);
if (isMidnight24)
*isMidnight24 = false;
+ // Match /\d\d(:\d\d(:\d\d)?)?([,.]\d+)?/ as "HH[:mm[:ss]][.zzz]"
+ // The fractional part, if present, is in the same units as the field it follows.
+ // TextDate restricts fractional parts to the seconds field.
+
+ QStringView tail;
+ const qsizetype dot = string.indexOf(u'.'), comma = string.indexOf(u',');
+ if (dot != -1) {
+ tail = string.sliced(dot + 1);
+ if (tail.indexOf(u'.') != -1) // Forbid second dot:
+ return QTime();
+ string = string.first(dot);
+ } else if (comma != -1) {
+ tail = string.sliced(comma + 1);
+ string = string.first(comma);
+ }
+ if (tail.indexOf(u',') != -1) // Forbid comma after first dot-or-comma:
+ return QTime();
- const int size = string.size();
- if (size < 5 || string.at(2) != QLatin1Char(':'))
+ const ParsedInt frac = readInt(tail);
+ // There must be *some* digits in a fractional part; and it must be all digits:
+ if (tail.isEmpty() ? dot != -1 || comma != -1 : !frac.ok())
return QTime();
+ Q_ASSERT(frac.ok() ^ tail.isEmpty());
+ double fraction = frac.ok() ? frac.result * std::pow(0.1, tail.size()) : 0.0;
- ParsedInt hour = readInt(string.mid(0, 2));
- ParsedInt minute = readInt(string.mid(3, 2));
- if (!hour.ok || !minute.ok)
+ const qsizetype size = string.size();
+ if (size < 2 || size > 8)
return QTime();
- // FIXME: ISO 8601 allows [,.]\d+ after hour, just as it does after minute
- int second = 0;
- int msec = 0;
+ ParsedInt hour = readInt(string.first(2));
+ if (!hour.ok() || hour.result > (format == Qt::TextDate ? 23 : 24))
+ return QTime();
- if (size == 5) {
- // HH:mm format
- second = 0;
- msec = 0;
- } else if (string.at(5) == QLatin1Char(',') || string.at(5) == QLatin1Char('.')) {
- if (format == Qt::TextDate)
+ ParsedInt minute{};
+ if (string.size() > 2) {
+ if (string[2] == u':' && string.size() > 4)
+ minute = readInt(string.sliced(3, 2));
+ if (!minute.ok() || minute.result >= MINS_PER_HOUR)
return QTime();
- // ISODate HH:mm.ssssss format
- // We only want 5 digits worth of fraction of minute. This follows the existing
- // behavior that determines how milliseconds are read; 4 millisecond digits are
- // read and then rounded to 3. If we read at most 5 digits for fraction of minute,
- // the maximum amount of millisecond digits it will expand to once converted to
- // 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 QStringView minuteFractionStr = string.mid(6, qMin(qsizetype(5), string.size() - 6));
- const ParsedInt parsed = readInt(minuteFractionStr);
- if (!parsed.ok)
+ } else if (format == Qt::TextDate) { // Requires minutes
+ return QTime();
+ } else if (frac.ok()) {
+ Q_ASSERT(!(fraction < 0.0) && fraction < 1.0);
+ fraction *= MINS_PER_HOUR;
+ minute.result = qulonglong(fraction);
+ fraction -= minute.result;
+ }
+
+ ParsedInt second{};
+ if (string.size() > 5) {
+ if (string[5] == u':' && string.size() == 8)
+ second = readInt(string.sliced(6, 2));
+ if (!second.ok() || second.result >= SECS_PER_MIN)
return QTime();
- const float secondWithMs
- = double(parsed.value) * 60 / (std::pow(double(10), minuteFractionStr.size()));
-
- second = std::floor(secondWithMs);
- const float secondFraction = secondWithMs - second;
- msec = qMin(qRound(secondFraction * 1000.0), 999);
- } else if (string.at(5) == QLatin1Char(':')) {
- // HH:mm:ss or HH:mm:ss.zzz
- const ParsedInt parsed = readInt(string.mid(6, qMin(qsizetype(2), string.size() - 6)));
- if (!parsed.ok)
+ } else if (frac.ok()) {
+ if (format == Qt::TextDate) // Doesn't allow fraction of minutes
return QTime();
- 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.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();
+ Q_ASSERT(!(fraction < 0.0) && fraction < 1.0);
+ fraction *= SECS_PER_MIN;
+ second.result = qulonglong(fraction);
+ fraction -= second.result;
+ }
+
+ Q_ASSERT(!(fraction < 0.0) && fraction < 1.0);
+ // Round millis to nearest (unlike minutes and seconds, rounded down):
+ int msec = frac.ok() ? qRound(MSECS_PER_SEC * fraction) : 0;
+ // But handle overflow gracefully:
+ if (msec == MSECS_PER_SEC) {
+ // If we can (when data were otherwise valid) validly propagate overflow
+ // into other fields, do so:
+ if (isMidnight24 || hour.result < 23 || minute.result < 59 || second.result < 59) {
+ msec = 0;
+ if (++second.result == SECS_PER_MIN) {
+ second.result = 0;
+ if (++minute.result == MINS_PER_HOUR) {
+ minute.result = 0;
+ ++hour.result;
+ // May need to propagate further via isMidnight24, see below
+ }
}
-#endif
+ } else {
+ // QTime::fromString() or Qt::TextDate: rounding up would cause
+ // 23:59:59.999... to become invalid; clip to 999 ms instead:
+ msec = MSECS_PER_SEC - 1;
}
- } else {
- return QTime();
}
- const bool isISODate = format == Qt::ISODate || format == Qt::ISODateWithMs;
- if (isISODate && hour.value == 24 && minute.value == 0 && second == 0 && msec == 0) {
+ // For ISO date format, 24:0:0 means 0:0:0 on the next day:
+ if (hour.result == 24 && minute.result == 0 && second.result == 0 && msec == 0) {
+ Q_ASSERT(format != Qt::TextDate); // It clipped hour at 23, above.
if (isMidnight24)
*isMidnight24 = true;
- hour.value = 0;
+ hour.result = 0;
}
- return QTime(hour.value, minute.value, second, msec);
+ return QTime(hour.result, minute.result, second.result, msec);
}
/*!
+ \fn QTime QTime::fromString(const QString &string, Qt::DateFormat format)
+
Returns the time represented in the \a string as a QTime using the
\a format given, or an invalid time if this is not possible.
\sa toString(), QLocale::toTime()
*/
-QTime QTime::fromString(const QString &string, Qt::DateFormat format)
+
+/*!
+ \overload
+ \since 6.0
+*/
+QTime QTime::fromString(QStringView string, Qt::DateFormat format)
{
if (string.isEmpty())
return QTime();
@@ -2221,11 +2570,13 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
case Qt::ISODateWithMs:
case Qt::TextDate:
default:
- return fromIsoTimeString(QStringView(string), format, nullptr);
+ return fromIsoTimeString(string, format, nullptr);
}
}
/*!
+ \fn QTime QTime::fromString(const QString &string, const QString &format)
+
Returns the QTime represented by the \a string, using the \a
format given, or an invalid time if the string cannot be parsed.
@@ -2245,18 +2596,23 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
\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
- precision, including trailing zeroes where applicable (000 to 999).
- \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 z or zz
+ \li The fractional part of the second, as would usually follow a
+ decimal point, without requiring trailing zeroes (0 to 999). Thus
+ \c{"s.z"} matches the seconds with up to three digits of fractional
+ part supplying millisecond precision, without needing trailing
+ zeroes. For example, \c{"s.z"} would recognize either \c{"00.250"}
+ or \c{"0.25"} as representing a time a quarter second into its
+ minute.
+ \row \li zzz
+ \li Three digit fractional part of the second, to millisecond
+ precision, including trailing zeroes where applicable (000 to 999).
+ For example, \c{"ss.zzz"} would reject \c{"0.25"} but recognize
+ \c{"00.250"} as representing a time a quarter second into its
+ minute.
+ \row \li AP, A, ap, a, aP or Ap
+ \li Either 'AM' indicating a time before 12:00 or 'PM' for later times,
+ matched case-insensitively.
\endtable
All other input characters will be treated as text. Any non-empty sequence
@@ -2267,7 +2623,7 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
If the format is not satisfied, an invalid QTime is returned.
Expressions that do not expect leading zeroes to be given (h, m, s
- and z) are greedy. This means that they will use two digits even if
+ and z) are greedy. This means that they will use two digits (or three, for z) even if
this puts them outside the range of accepted values and leaves too
few digits for other sections. For example, the following string
could have meant 00:07:10, but the m will grab two digits, resulting
@@ -2280,15 +2636,33 @@ QTime QTime::fromString(const QString &string, Qt::DateFormat format)
\snippet code/src_corelib_time_qdatetime.cpp 8
- \note If localized forms of am or pm (the AP, ap, A or a formats) are used,
- please switch to using QLocale::system().toTime() as QTime methods shall
- change to only recognize English (C locale) at Qt 6.
+ \note If localized forms of am or pm (the AP, ap, Ap, aP, A or a formats)
+ are to be recognized, use QLocale::system().toTime().
+
+ \note If a format character is repeated more times than the longest
+ expression in the table above using it, this part of the format will be read
+ as several expressions with no separator between them; the longest above,
+ possibly repeated as many times as there are copies of it, ending with a
+ residue that may be a shorter expression. Thus \c{'HHHHH'} would match
+ \c{"08088"} or \c{"080808"} and set the hour to 8; if the time string
+ contained "070809" it would "match" but produce an inconsistent result,
+ leading to an invalid time.
\sa toString(), QDateTime::fromString(), QDate::fromString(),
- QLocale::toTime()
+ QLocale::toTime(), QLocale::toDateTime()
*/
-QTime QTime::fromString(const QString &string, const QString &format)
+/*!
+ \fn QTime QTime::fromString(QStringView string, QStringView format)
+ \overload
+ \since 6.0
+*/
+
+/*!
+ \overload
+ \since 6.0
+*/
+QTime QTime::fromString(const QString &string, QStringView format)
{
QTime time;
#if QT_CONFIG(datetimeparser)
@@ -2302,7 +2676,6 @@ QTime QTime::fromString(const QString &string, const QString &format)
#endif
return time;
}
-
#endif // datestring
@@ -2322,7 +2695,8 @@ QTime QTime::fromString(const QString &string, const QString &format)
bool QTime::isValid(int h, int m, int s, int ms)
{
- return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
+ return (uint(h) < 24 && uint(m) < MINS_PER_HOUR && uint(s) < SECS_PER_MIN
+ && uint(ms) < MSECS_PER_SEC);
}
/*****************************************************************************
@@ -2333,374 +2707,353 @@ bool QTime::isValid(int h, int m, int s, int ms)
typedef QDateTimePrivate::QDateTimeShortData ShortData;
typedef QDateTimePrivate::QDateTimeData QDateTimeData;
-// Returns the platform variant of timezone, i.e. the standard time offset
-// The timezone external variable is documented as always holding the
-// Standard Time offset as seconds west of Greenwich, i.e. UTC+01:00 is -3600
-// Note this may not be historicaly accurate.
-// Relies on tzset, mktime, or localtime having been called to populate timezone
-static int qt_timezone()
-{
-#if defined(_MSC_VER)
- long offset;
- _get_timezone(&offset);
- return offset;
-#elif defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN)
- time_t clock = time(NULL);
- struct tm t;
- localtime_r(&clock, &t);
- // QTBUG-36080 Workaround for systems without the POSIX timezone
- // variable. This solution is not very efficient but fixing it is up to
- // the libc implementations.
- //
- // tm_gmtoff has some important differences compared to the timezone
- // variable:
- // - It returns the number of seconds east of UTC, and we want the
- // number of seconds west of UTC.
- // - It also takes DST into account, so we need to adjust it to always
- // get the Standard Time offset.
- return -t.tm_gmtoff + (t.tm_isdst ? (long)SECS_PER_HOUR : 0L);
-#elif defined(Q_OS_INTEGRITY) || defined(Q_OS_RTEMS)
- return 0;
-#else
- return timezone;
-#endif // Q_OS_WIN
+// Converts milliseconds since the start of 1970 into a date and/or time:
+static qint64 msecsToJulianDay(qint64 msecs)
+{
+ return JULIAN_DAY_FOR_EPOCH + QRoundingDown::qDiv<MSECS_PER_DAY>(msecs);
}
-// Returns the tzname, assume tzset has been called already
-static QString qt_tzname(QDateTimePrivate::DaylightStatus daylightStatus)
+static QDate msecsToDate(qint64 msecs)
{
- int isDst = (daylightStatus == QDateTimePrivate::DaylightTime) ? 1 : 0;
-#if defined(Q_CC_MSVC)
- size_t s = 0;
- char name[512];
- if (_get_tzname(&s, name, 512, isDst))
- return QString();
- return QString::fromLocal8Bit(name);
-#else
- return QString::fromLocal8Bit(tzname[isDst]);
-#endif // Q_OS_WIN
+ return QDate::fromJulianDay(msecsToJulianDay(msecs));
}
-#if QT_CONFIG(datetimeparser)
-/*
- \internal
- Implemented here to share qt_tzname()
-*/
-int QDateTimeParser::startsWithLocalTimeZone(QStringView name)
+static QTime msecsToTime(qint64 msecs)
{
- QDateTimePrivate::DaylightStatus zones[2] = {
- QDateTimePrivate::StandardTime,
- QDateTimePrivate::DaylightTime
- };
- for (const auto z : zones) {
- QString zone(qt_tzname(z));
- if (name.startsWith(zone))
- return zone.size();
- }
- return 0;
+ return QTime::fromMSecsSinceStartOfDay(QRoundingDown::qMod<MSECS_PER_DAY>(msecs));
}
-#endif // datetimeparser
-
-// Calls the platform variant of mktime for the given date, time and daylightStatus,
-// and updates the date, time, daylightStatus and abbreviation with the returned values
-// If the date falls outside the 1970 to 2037 range supported by mktime / time_t
-// then null date/time will be returned, you should adjust the date first if
-// you need a guaranteed result.
-static qint64 qt_mktime(QDate *date, QTime *time, QDateTimePrivate::DaylightStatus *daylightStatus,
- QString *abbreviation, bool *ok = nullptr)
-{
- const qint64 msec = time->msec();
- int yy, mm, dd;
- date->getDate(&yy, &mm, &dd);
-
- // All other platforms provide standard C library time functions
- tm local;
- memset(&local, 0, sizeof(local)); // tm_[wy]day plus any non-standard fields
- local.tm_sec = time->second();
- local.tm_min = time->minute();
- local.tm_hour = time->hour();
- local.tm_mday = dd;
- local.tm_mon = mm - 1;
- local.tm_year = yy - 1900;
- local.tm_isdst = daylightStatus ? int(*daylightStatus) : -1;
-#if defined(Q_OS_WIN)
- int hh = local.tm_hour;
-#endif // Q_OS_WIN
- time_t secsSinceEpoch = qMkTime(&local);
- if (secsSinceEpoch != time_t(-1)) {
- *date = QDate(local.tm_year + 1900, local.tm_mon + 1, local.tm_mday);
- *time = QTime(local.tm_hour, local.tm_min, local.tm_sec, msec);
-#if defined(Q_OS_WIN)
- // Windows mktime for the missing hour subtracts 1 hour from the time
- // instead of adding 1 hour. If time differs and is standard time then
- // this has happened, so add 2 hours to the time and 1 hour to the msecs
- if (local.tm_isdst == 0 && local.tm_hour != hh) {
- if (time->hour() >= 22)
- *date = date->addDays(1);
- *time = time->addSecs(2 * SECS_PER_HOUR);
- secsSinceEpoch += SECS_PER_HOUR;
- local.tm_isdst = 1;
- }
-#endif // Q_OS_WIN
- if (local.tm_isdst > 0) {
- if (daylightStatus)
- *daylightStatus = QDateTimePrivate::DaylightTime;
- if (abbreviation)
- *abbreviation = qt_tzname(QDateTimePrivate::DaylightTime);
- } else {
- if (daylightStatus) {
- *daylightStatus = (local.tm_isdst == 0
- ? QDateTimePrivate::StandardTime
- : QDateTimePrivate::UnknownDaylightTime);
- }
- if (abbreviation)
- *abbreviation = qt_tzname(QDateTimePrivate::StandardTime);
- }
- } else if (yy == 1969 && mm == 12 && dd == 31
- && time->second() == MSECS_PER_DAY - 1) {
- // There was, of course, a last second in 1969, at time_t(-1); we won't
- // rescue it if it's not in normalised form, and we don't know its DST
- // status (unless we did already), but let's not wantonly declare it
- // invalid.
- } else {
- *date = QDate();
- *time = QTime();
- if (daylightStatus)
- *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
- if (abbreviation)
- *abbreviation = QString();
- if (ok)
- *ok = false;
- return 0;
- }
- if (ok)
- *ok = true;
+// True if combining days with millis overflows; otherwise, stores result in *sumMillis
+// The inputs should not have opposite signs.
+static inline bool daysAndMillisOverflow(qint64 days, qint64 millisInDay, qint64 *sumMillis)
+{
+ return qMulOverflow(days, std::integral_constant<qint64, MSECS_PER_DAY>(), sumMillis)
+ || qAddOverflow(*sumMillis, millisInDay, sumMillis);
+}
- return qint64(secsSinceEpoch) * 1000 + msec;
+// Converts a date/time value into msecs
+static qint64 timeToMSecs(QDate date, QTime time)
+{
+ qint64 days = date.toJulianDay() - JULIAN_DAY_FOR_EPOCH;
+ qint64 msecs, dayms = time.msecsSinceStartOfDay();
+ if (days < 0 && dayms > 0) {
+ ++days;
+ dayms -= MSECS_PER_DAY;
+ }
+ if (daysAndMillisOverflow(days, dayms, &msecs)) {
+ using Bound = std::numeric_limits<qint64>;
+ return days < 0 ? Bound::min() : Bound::max();
+ }
+ return msecs;
}
-// Calls the platform variant of localtime for the given msecs, and updates
-// the date, time, and DST status with the returned values.
-static bool qt_localtime(qint64 msecsSinceEpoch, QDate *localDate, QTime *localTime,
- QDateTimePrivate::DaylightStatus *daylightStatus)
+/*!
+ \internal
+ Tests whether system functions can handle a given time.
+
+ The range of milliseconds for which the time_t-based functions work depends
+ somewhat on platform (see computeSystemMillisRange() for details). This
+ function tests whether the UTC time \a millis milliseconds from the epoch is
+ in the supported range.
+
+ To test a local time, pass an upper bound on the magnitude of time-zone
+ correction potentially needed as \a slack: in this case the range is
+ extended by this many milliseconds at each end (where applicable). The
+ function then returns true precisely if \a millis is within this (possibly)
+ widened range. This doesn't guarantee that the time_t functions can handle
+ the time, so check their returns to be sure. Values for which the function
+ returns false should be assumed unrepresentable.
+*/
+static inline bool millisInSystemRange(qint64 millis, qint64 slack = 0)
{
- const time_t secsSinceEpoch = msecsSinceEpoch / 1000;
- const int msec = msecsSinceEpoch % 1000;
+ static const auto bounds = QLocalTime::computeSystemMillisRange();
+ return (bounds.minClip || millis >= bounds.min - slack)
+ && (bounds.maxClip || millis <= bounds.max + slack);
+}
- tm local;
- bool valid = false;
+/*!
+ \internal
+ Returns a year, in the system range, with the same day-of-week pattern
- // localtime() is specified to work as if it called tzset().
- // localtime_r() does not have this constraint, so make an explicit call.
- // The explicit call should also request the timezone info be re-parsed.
- qTzSet();
-#if QT_CONFIG(thread) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
- // Use the reentrant version of localtime() where available
- // as is thread-safe and doesn't use a shared static data area
- if (tm *res = localtime_r(&secsSinceEpoch, &local)) {
- Q_ASSERT(res == &local);
- valid = true;
- }
-#elif defined(Q_CC_MSVC)
- if (!_localtime64_s(&local, &secsSinceEpoch))
- valid = true;
-#else
- // Returns shared static data which may be overwritten at any time
- // So copy the result asap
- if (tm *res = localtime(&secsSinceEpoch)) {
- local = *res;
- valid = true;
- }
+ Returns the number of a year, in the range supported by system time_t
+ functions, that starts and ends on the same days of the week as \a year.
+ This implies it is a leap year precisely if \a year is. If year is before
+ the epoch, a year early in the supported range is used; otherwise, one late
+ in that range. For a leap year, this may be as much as 26 years years from
+ the range's relevant end; for normal years at most a decade from the end.
+
+ This ensures that any DST rules based on, e.g., the last Sunday in a
+ particular month will select the same date in the returned year as they
+ would if applied to \a year. Of course, the zone's rules may be different in
+ \a year than in the selected year, but it's hard to do better.
+*/
+static int systemTimeYearMatching(int year)
+{
+#if defined(Q_OS_WIN) || defined(Q_OS_WASM)// They don't support times before the epoch
+ static constexpr int forLeapEarly[] = { 1984, 1996, 1980, 1992, 1976, 1988, 1972 };
+ static constexpr int regularEarly[] = { 1978, 1973, 1974, 1975, 1970, 1971, 1977 };
+#else // First year fully in 32-bit time_t range is 1902
+ static constexpr int forLeapEarly[] = { 1928, 1912, 1924, 1908, 1920, 1904, 1916 };
+ static constexpr int regularEarly[] = { 1905, 1906, 1907, 1902, 1903, 1909, 1910 };
#endif
- if (valid) {
- *localDate = QDate(local.tm_year + 1900, local.tm_mon + 1, local.tm_mday);
- *localTime = QTime(local.tm_hour, local.tm_min, local.tm_sec, msec);
- if (daylightStatus) {
- if (local.tm_isdst > 0)
- *daylightStatus = QDateTimePrivate::DaylightTime;
- else if (local.tm_isdst < 0)
- *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
- else
- *daylightStatus = QDateTimePrivate::StandardTime;
- }
- return true;
- } else {
- *localDate = QDate();
- *localTime = QTime();
- if (daylightStatus)
- *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
- return false;
+ static constexpr int forLeapLate[] = { 2012, 2024, 2036, 2020, 2032, 2016, 2028 };
+ static constexpr int regularLate[] = { 2034, 2035, 2030, 2031, 2037, 2027, 2033 };
+ const int dow = QGregorianCalendar::yearStartWeekDay(year);
+ Q_ASSERT(dow == QDate(year, 1, 1).dayOfWeek());
+ const int res = (QGregorianCalendar::leapTest(year)
+ ? (year < 1970 ? forLeapEarly : forLeapLate)
+ : (year < 1970 ? regularEarly : regularLate))[dow == 7 ? 0 : dow];
+ Q_ASSERT(QDate(res, 1, 1).dayOfWeek() == dow);
+ Q_ASSERT(QDate(res, 12, 31).dayOfWeek() == QDate(year, 12, 31).dayOfWeek());
+ return res;
+}
+
+// Sets up d and status to represent local time at the given UTC msecs since epoch:
+QDateTimePrivate::ZoneState QDateTimePrivate::expressUtcAsLocal(qint64 utcMSecs)
+{
+ ZoneState result{utcMSecs};
+ // Within the time_t supported range, localtime() can handle it:
+ if (millisInSystemRange(utcMSecs)) {
+ result = QLocalTime::utcToLocal(utcMSecs);
+ if (result.valid)
+ return result;
}
-}
-// Converts an msecs value into a date and time
-static void msecsToTime(qint64 msecs, QDate *date, QTime *time)
-{
- qint64 jd = JULIAN_DAY_FOR_EPOCH;
- qint64 ds = 0;
+ // Docs state any LocalTime after 2038-01-18 *will* have any DST applied.
+ // When this falls outside the supported range, we need to fake it.
+#if QT_CONFIG(timezone) // Use the system time-zone.
+ if (const auto sys = QTimeZone::systemTimeZone(); sys.isValid()) {
+ result.offset = sys.d->offsetFromUtc(utcMSecs);
+ if (qAddOverflow(utcMSecs, result.offset * MSECS_PER_SEC, &result.when))
+ return result;
+ result.dst = sys.d->isDaylightTime(utcMSecs) ? DaylightTime : StandardTime;
+ result.valid = true;
+ return result;
+ }
+#endif // timezone
- if (msecs >= MSECS_PER_DAY || msecs <= -MSECS_PER_DAY) {
- jd += msecs / MSECS_PER_DAY;
- msecs %= MSECS_PER_DAY;
+ // Kludge
+ // Do the conversion in a year with the same days of the week, so DST
+ // dates might be right, and adjust by the number of days that was off:
+ const qint64 jd = msecsToJulianDay(utcMSecs);
+ const auto ymd = QGregorianCalendar::partsFromJulian(jd);
+ qint64 diffMillis, fakeUtc;
+ const auto fakeJd = QGregorianCalendar::julianFromParts(systemTimeYearMatching(ymd.year),
+ ymd.month, ymd.day);
+ if (Q_UNLIKELY(!fakeJd
+ || qMulOverflow(jd - *fakeJd, std::integral_constant<qint64, MSECS_PER_DAY>(),
+ &diffMillis)
+ || qSubOverflow(utcMSecs, diffMillis, &fakeUtc))) {
+ return result;
}
- if (msecs < 0) {
- ds = MSECS_PER_DAY - msecs - 1;
- jd -= ds / MSECS_PER_DAY;
- ds = ds % MSECS_PER_DAY;
- ds = MSECS_PER_DAY - ds - 1;
- } else {
- ds = msecs;
+ result = QLocalTime::utcToLocal(fakeUtc);
+ // Now correct result.when for the use of the fake date:
+ if (!result.valid || qAddOverflow(result.when, diffMillis, &result.when)) {
+ // If utcToLocal() failed, its return has the fake when; restore utcMSecs.
+ // Fail on overflow, but preserve offset and DST-ness.
+ result.when = utcMSecs;
+ result.valid = false;
}
+ return result;
+}
- if (date)
- *date = QDate::fromJulianDay(jd);
- if (time)
- *time = QTime::fromMSecsSinceStartOfDay(ds);
+static auto millisToWithinRange(qint64 millis)
+{
+ struct R {
+ qint64 shifted = 0;
+ bool good = false;
+ } result;
+ qint64 jd = msecsToJulianDay(millis);
+ auto ymd = QGregorianCalendar::partsFromJulian(jd);
+ const auto fakeJd = QGregorianCalendar::julianFromParts(systemTimeYearMatching(ymd.year),
+ ymd.month, ymd.day);
+ result.good = fakeJd && !daysAndMillisOverflow(*fakeJd - jd, millis, &result.shifted);
+ return result;
}
-// Converts a date/time value into msecs
-static qint64 timeToMSecs(QDate date, QTime time)
+/*!
+ \internal
+ \enum QDateTimePrivate::TransitionOption
+
+ This enumeration is used to resolve datetime combinations which fall in \l
+ {Timezone transitions}. The transition is described as a "gap" if there are
+ time representations skipped over by the zone, as is common in the "spring
+ forward" transitions in many zones on entering daylight-saving time. The
+ transition is described as a "fold" if there are time representations
+ repeated in the zone, as in a "fall back" transition out of daylight-saving
+ time.
+
+ When the options specified do not determine a resolution for a datetime, it
+ is marked invalid.
+
+ The prepared option sets above are in fact composed from low-level atomic
+ options. For each of gap and fold you can chose between two candidate times,
+ one before or after the transition, based on the time requested; or you can
+ pick the moment of transition, or the start or end of the transition
+ interval. For a gap, the start and end of the interval are the moment of the
+ transition, but for a repeated interval the start of the first pass is the
+ start of the transition interval, the end of the second pass is the end of
+ the transition interval and the moment of the transition itself is both the
+ end of the first pass and the start of the second.
+
+ \value GapUseBefore For a time in a gap, use a time before the transition,
+ as if stepping back from a later time.
+ \value GapUseAfter For a time in a gap, use a time after the transition, as
+ if stepping forward from an earlier time.
+ \value FoldUseBefore For a repeated time, use the first candidate, which is
+ before the transition.
+ \value FoldUseAfter For a repeated time, use the second candidate, which is
+ after the transition.
+ \value FlipForReverseDst For "reversed" DST, this reverses the preceding
+ four options (see below).
+
+ The last has no effect unless the "daylight-saving" time side of the
+ transition is known to have a lower offset from UTC than the standard time
+ side. (This is the "reversed" DST case of \l {Timezone transitions}.) In
+ that case, if other options would select a time after the transition, a time
+ before is used instead, and vice versa. This effectively turns a preference
+ for the side with lower offset into a preference for the side that is
+ officially standard time, even if it has higher offset; and conversely a
+ preference for higher offset into a preference for daylight-saving time,
+ even if it has a lower offset. This option has no effect on a resolution
+ that selects the moment of transition or the start or end of the transition
+ interval.
+
+ The result of combining more than one of the \c GapUse* options is
+ undefined; likewise for the \c FoldUse*. Each of QDateTime's
+ TransitionResolution values, aside from Reject, maps to a combination that
+ incorporates one from each of these sets.
+*/
+
+constexpr static QDateTimePrivate::TransitionOptions
+toTransitionOptions(QDateTime::TransitionResolution res)
+{
+ switch (res) {
+ case QDateTime::TransitionResolution::RelativeToBefore:
+ return QDateTimePrivate::GapUseAfter | QDateTimePrivate::FoldUseBefore;
+ case QDateTime::TransitionResolution::RelativeToAfter:
+ return QDateTimePrivate::GapUseBefore | QDateTimePrivate::FoldUseAfter;
+ case QDateTime::TransitionResolution::PreferBefore:
+ return QDateTimePrivate::GapUseBefore | QDateTimePrivate::FoldUseBefore;
+ case QDateTime::TransitionResolution::PreferAfter:
+ return QDateTimePrivate::GapUseAfter | QDateTimePrivate::FoldUseAfter;
+ case QDateTime::TransitionResolution::PreferStandard:
+ return QDateTimePrivate::GapUseBefore
+ | QDateTimePrivate::FoldUseAfter
+ | QDateTimePrivate::FlipForReverseDst;
+ case QDateTime::TransitionResolution::PreferDaylightSaving:
+ return QDateTimePrivate::GapUseAfter
+ | QDateTimePrivate::FoldUseBefore
+ | QDateTimePrivate::FlipForReverseDst;
+ case QDateTime::TransitionResolution::Reject: break;
+ }
+ return {};
+}
+
+constexpr static QDateTimePrivate::TransitionOptions
+toTransitionOptions(QDateTimePrivate::DaylightStatus dst)
{
- return ((date.toJulianDay() - JULIAN_DAY_FOR_EPOCH) * MSECS_PER_DAY)
- + time.msecsSinceStartOfDay();
+ return toTransitionOptions(dst == QDateTimePrivate::DaylightTime
+ ? QDateTime::TransitionResolution::PreferDaylightSaving
+ : QDateTime::TransitionResolution::PreferStandard);
}
-// Convert an MSecs Since Epoch into Local Time
-static bool epochMSecsToLocalTime(qint64 msecs, QDate *localDate, QTime *localTime,
- QDateTimePrivate::DaylightStatus *daylightStatus = nullptr)
+QString QDateTimePrivate::localNameAtMillis(qint64 millis, DaylightStatus dst)
{
- if (msecs < 0) {
- // Docs state any LocalTime before 1970-01-01 will *not* have any Daylight Time applied
- // Instead just use the standard offset from UTC to convert to UTC time
- qTzSet();
- msecsToTime(msecs - qt_timezone() * 1000, localDate, localTime);
- if (daylightStatus)
- *daylightStatus = QDateTimePrivate::StandardTime;
- return true;
- } else if (msecs > (qint64(TIME_T_MAX) * 1000)) {
- // Docs state any LocalTime after 2037-12-31 *will* have any DST applied
- // but this may fall outside the supported time_t range, so need to fake it.
- // Use existing method to fake the conversion, but this is deeply flawed as it may
- // apply the conversion from the wrong day number, e.g. if rule is last Sunday of month
- // TODO Use QTimeZone when available to apply the future rule correctly
- QDate utcDate;
- QTime utcTime;
- msecsToTime(msecs, &utcDate, &utcTime);
- int year, month, day;
- utcDate.getDate(&year, &month, &day);
- // 2037 is not a leap year, so make sure date isn't Feb 29
- if (month == 2 && day == 29)
- --day;
- QDate fakeDate(2037, month, day);
- qint64 fakeMsecs = QDateTime(fakeDate, utcTime, Qt::UTC).toMSecsSinceEpoch();
- bool res = qt_localtime(fakeMsecs, localDate, localTime, daylightStatus);
- *localDate = localDate->addDays(fakeDate.daysTo(utcDate));
- return res;
- } else {
- // Falls inside time_t suported range so can use localtime
- return qt_localtime(msecs, localDate, localTime, daylightStatus);
+ const QDateTimePrivate::TransitionOptions resolve = toTransitionOptions(dst);
+ QString abbreviation;
+ if (millisInSystemRange(millis, MSECS_PER_DAY)) {
+ abbreviation = QLocalTime::localTimeAbbbreviationAt(millis, resolve);
+ if (!abbreviation.isEmpty())
+ return abbreviation;
+ }
+
+ // Otherwise, outside the system range.
+#if QT_CONFIG(timezone)
+ // Use the system zone:
+ const auto sys = QTimeZone::systemTimeZone();
+ if (sys.isValid()) {
+ ZoneState state = zoneStateAtMillis(sys, millis, resolve);
+ if (state.valid)
+ return sys.d->abbreviation(state.when - state.offset * MSECS_PER_SEC);
}
+#endif // timezone
+
+ // Kludge
+ // Use a time in the system range with the same day-of-week pattern to its year:
+ auto fake = millisToWithinRange(millis);
+ if (Q_LIKELY(fake.good))
+ return QLocalTime::localTimeAbbbreviationAt(fake.shifted, resolve);
+
+ // Overflow, apparently.
+ return {};
}
-// Convert a LocalTime expressed in local msecs encoding and the corresponding
-// DST status into a UTC epoch msecs. Optionally populate the returned
-// values from mktime for the adjusted local date and time.
-static qint64 localMSecsToEpochMSecs(qint64 localMsecs,
- QDateTimePrivate::DaylightStatus *daylightStatus,
- QDate *localDate = nullptr, QTime *localTime = nullptr,
- QString *abbreviation = nullptr)
+// Determine the offset from UTC at the given local time as millis.
+QDateTimePrivate::ZoneState QDateTimePrivate::localStateAtMillis(
+ qint64 millis, QDateTimePrivate::TransitionOptions resolve)
{
- QDate dt;
- QTime tm;
- msecsToTime(localMsecs, &dt, &tm);
-
- const qint64 msecsMax = qint64(TIME_T_MAX) * 1000;
-
- if (localMsecs <= qint64(MSECS_PER_DAY)) {
-
- // Docs state any LocalTime before 1970-01-01 will *not* have any DST applied
-
- // First, if localMsecs is within +/- 1 day of minimum time_t try mktime in case it does
- // fall after minimum and needs proper DST conversion
- if (localMsecs >= -qint64(MSECS_PER_DAY)) {
- bool valid;
- qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation, &valid);
- if (valid && utcMsecs >= 0) {
- // mktime worked and falls in valid range, so use it
- if (localDate)
- *localDate = dt;
- if (localTime)
- *localTime = tm;
- return utcMsecs;
+ // First, if millis is within a day of the viable range, try mktime() in
+ // case it does fall in the range and gets useful information:
+ if (millisInSystemRange(millis, MSECS_PER_DAY)) {
+ auto result = QLocalTime::mapLocalTime(millis, resolve);
+ if (result.valid)
+ return result;
+ }
+
+ // Otherwise, outside the system range.
+#if QT_CONFIG(timezone)
+ // Use the system zone:
+ const auto sys = QTimeZone::systemTimeZone();
+ if (sys.isValid())
+ return zoneStateAtMillis(sys, millis, resolve);
+#endif // timezone
+
+ // Kludge
+ // Use a time in the system range with the same day-of-week pattern to its year:
+ auto fake = millisToWithinRange(millis);
+ if (Q_LIKELY(fake.good)) {
+ auto result = QLocalTime::mapLocalTime(fake.shifted, resolve);
+ if (result.valid) {
+ qint64 adjusted;
+ if (Q_UNLIKELY(qAddOverflow(result.when, millis - fake.shifted, &adjusted))) {
+ using Bound = std::numeric_limits<qint64>;
+ adjusted = millis < fake.shifted ? Bound::min() : Bound::max();
}
+ result.when = adjusted;
} else {
- // If we don't call mktime then need to call tzset to get offset
- qTzSet();
+ result.when = millis;
}
- // Time is clearly before 1970-01-01 so just use standard offset to convert
- qint64 utcMsecs = localMsecs + qt_timezone() * 1000;
- if (localDate || localTime)
- msecsToTime(localMsecs, localDate, localTime);
- if (daylightStatus)
- *daylightStatus = QDateTimePrivate::StandardTime;
- if (abbreviation)
- *abbreviation = qt_tzname(QDateTimePrivate::StandardTime);
- return utcMsecs;
-
- } else if (localMsecs >= msecsMax - MSECS_PER_DAY) {
-
- // Docs state any LocalTime after 2037-12-31 *will* have any DST applied
- // but this may fall outside the supported time_t range, so need to fake it.
-
- // First, if localMsecs is within +/- 1 day of maximum time_t try mktime in case it does
- // fall before maximum and can use proper DST conversion
- if (localMsecs <= msecsMax + MSECS_PER_DAY) {
- bool valid;
- qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation, &valid);
- if (valid && utcMsecs <= msecsMax) {
- // mktime worked and falls in valid range, so use it
- if (localDate)
- *localDate = dt;
- if (localTime)
- *localTime = tm;
- return utcMsecs;
- }
- }
- // Use existing method to fake the conversion, but this is deeply flawed as it may
- // apply the conversion from the wrong day number, e.g. if rule is last Sunday of month
- // TODO Use QTimeZone when available to apply the future rule correctly
- int year, month, day;
- dt.getDate(&year, &month, &day);
- // 2037 is not a leap year, so make sure date isn't Feb 29
- if (month == 2 && day == 29)
- --day;
- QDate fakeDate(2037, month, day);
- qint64 fakeDiff = fakeDate.daysTo(dt);
- qint64 utcMsecs = qt_mktime(&fakeDate, &tm, daylightStatus, abbreviation);
- if (localDate)
- *localDate = fakeDate.addDays(fakeDiff);
- if (localTime)
- *localTime = tm;
- QDate utcDate;
- QTime utcTime;
- msecsToTime(utcMsecs, &utcDate, &utcTime);
- utcDate = utcDate.addDays(fakeDiff);
- utcMsecs = timeToMSecs(utcDate, utcTime);
- return utcMsecs;
-
- } else {
+ return result;
+ }
+ // Overflow, apparently.
+ return {millis};
+}
- // Clearly falls inside 1970-2037 suported range so can use mktime
- qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation);
- if (localDate)
- *localDate = dt;
- if (localTime)
- *localTime = tm;
- return utcMsecs;
+#if QT_CONFIG(timezone)
+// For a TimeZone and a time expressed in zone msecs encoding, compute the
+// actual DST-ness and offset, adjusting the time if needed to escape a
+// spring-forward.
+QDateTimePrivate::ZoneState QDateTimePrivate::zoneStateAtMillis(
+ const QTimeZone &zone, qint64 millis, QDateTimePrivate::TransitionOptions resolve)
+{
+ Q_ASSERT(zone.isValid());
+ Q_ASSERT(zone.timeSpec() == Qt::TimeZone);
+ return zone.d->stateAtZoneTime(millis, resolve);
+}
+#endif // timezone
- }
+static inline QDateTimePrivate::ZoneState stateAtMillis(const QTimeZone &zone, qint64 millis,
+ QDateTimePrivate::TransitionOptions resolve)
+{
+ if (zone.timeSpec() == Qt::LocalTime)
+ return QDateTimePrivate::localStateAtMillis(millis, resolve);
+#if QT_CONFIG(timezone)
+ if (zone.timeSpec() == Qt::TimeZone && zone.isValid())
+ return QDateTimePrivate::zoneStateAtMillis(zone, millis, resolve);
+#endif
+ return {millis};
}
static inline bool specCanBeSmall(Qt::TimeSpec spec)
@@ -2710,7 +3063,7 @@ static inline bool specCanBeSmall(Qt::TimeSpec spec)
static inline bool msecsCanBeSmall(qint64 msecs)
{
- if (!QDateTimeData::CanBeSmall)
+ if constexpr (!QDateTimeData::CanBeSmall)
return false;
ShortData sd;
@@ -2721,13 +3074,14 @@ static inline bool msecsCanBeSmall(qint64 msecs)
static constexpr inline
QDateTimePrivate::StatusFlags mergeSpec(QDateTimePrivate::StatusFlags status, Qt::TimeSpec spec)
{
- return QDateTimePrivate::StatusFlags((status & ~QDateTimePrivate::TimeSpecMask) |
- (int(spec) << QDateTimePrivate::TimeSpecShift));
+ status &= ~QDateTimePrivate::TimeSpecMask;
+ status |= QDateTimePrivate::StatusFlags::fromInt(int(spec) << QDateTimePrivate::TimeSpecShift);
+ return status;
}
static constexpr inline Qt::TimeSpec extractSpec(QDateTimePrivate::StatusFlags status)
{
- return Qt::TimeSpec((status & QDateTimePrivate::TimeSpecMask) >> QDateTimePrivate::TimeSpecShift);
+ return Qt::TimeSpec((status & QDateTimePrivate::TimeSpecMask).toInt() >> QDateTimePrivate::TimeSpecShift);
}
// Set the Daylight Status if LocalTime set via msecs
@@ -2747,9 +3101,9 @@ mergeDaylightStatus(QDateTimePrivate::StatusFlags sf, QDateTimePrivate::Daylight
static constexpr inline
QDateTimePrivate::DaylightStatus extractDaylightStatus(QDateTimePrivate::StatusFlags status)
{
- if (status & QDateTimePrivate::SetToDaylightTime)
+ if (status.testFlag(QDateTimePrivate::SetToDaylightTime))
return QDateTimePrivate::DaylightTime;
- if (status & QDateTimePrivate::SetToStandardTime)
+ if (status.testFlag(QDateTimePrivate::SetToStandardTime))
return QDateTimePrivate::StandardTime;
return QDateTimePrivate::UnknownDaylightTime;
}
@@ -2779,56 +3133,90 @@ static inline Qt::TimeSpec getSpec(const QDateTimeData &d)
return extractSpec(getStatus(d));
}
-#if QT_CONFIG(timezone)
-void QDateTimePrivate::setUtcOffsetByTZ(qint64 atMSecsSinceEpoch)
+/* True if we *can cheaply determine* that a and b use the same offset.
+ If they use different offsets or it would be expensive to find out, false.
+ Calls to toMSecsSinceEpoch() are expensive, for these purposes.
+ See QDateTime's comparison operators.
+*/
+static inline bool usesSameOffset(const QDateTimeData &a, const QDateTimeData &b)
{
- m_offsetFromUtc = m_timeZone.d->offsetFromUtc(atMSecsSinceEpoch);
+ const auto status = getStatus(a);
+ if (status != getStatus(b))
+ return false;
+ // Status includes DST-ness, so we now know they match in it.
+
+ switch (extractSpec(status)) {
+ case Qt::LocalTime:
+ case Qt::UTC:
+ return true;
+
+ case Qt::TimeZone:
+ /* TimeZone always determines its offset during construction of the
+ private data. Even if we're in different zones, what matters is the
+ offset actually in effect at the specific time. (DST can cause things
+ with the same time-zone to use different offsets, but we already
+ checked their DSTs match.) */
+ case Qt::OffsetFromUTC: // always knows its offset, which is all that matters.
+ Q_ASSERT(!a.isShort() && !b.isShort());
+ return a->m_offsetFromUtc == b->m_offsetFromUtc;
+ }
+ Q_UNREACHABLE_RETURN(false);
}
-#endif
// Refresh the LocalTime or TimeZone validity and offset
-static void refreshZonedDateTime(QDateTimeData &d, Qt::TimeSpec spec)
+static void refreshZonedDateTime(QDateTimeData &d, const QTimeZone &zone,
+ QDateTimePrivate::TransitionOptions resolve)
{
- Q_ASSERT(spec == Qt::TimeZone || spec == Qt::LocalTime);
+ Q_ASSERT(zone.timeSpec() == Qt::TimeZone || zone.timeSpec() == Qt::LocalTime);
auto status = getStatus(d);
- Q_ASSERT(extractSpec(status) == spec);
+ Q_ASSERT(extractSpec(status) == zone.timeSpec());
int offsetFromUtc = 0;
+ /* Callers are:
+ * QDTP::create(), where d is too new to be shared yet
+ * reviseTimeZone(), which detach()es if not short before calling this
+ * checkValidDateTime(), always follows a setDateTime() that detach()ed if not short
+
+ So we can assume d is not shared. We only need to detach() if we convert
+ from short to pimpled to accommodate an oversize msecs, which can only be
+ needed in the unlikely event we revise it.
+ */
// If not valid date and time then is invalid
- if (!(status & QDateTimePrivate::ValidDate) || !(status & QDateTimePrivate::ValidTime)) {
- status &= ~QDateTimePrivate::ValidDateTime;
+ if (!status.testFlags(QDateTimePrivate::ValidDate | QDateTimePrivate::ValidTime)) {
+ status.setFlag(QDateTimePrivate::ValidDateTime, false);
} else {
- // We have a valid date and time and a Qt::LocalTime or Qt::TimeZone that needs calculating
- // LocalTime and TimeZone might fall into a "missing" DST transition hour
- // Calling toEpochMSecs will adjust the returned date/time if it does
- const qint64 msecs = getMSecs(d);
- qint64 epochMSecs = 0;
- QDate testDate;
- QTime testTime;
- if (spec == Qt::LocalTime) {
- auto dstStatus = extractDaylightStatus(status);
- epochMSecs = localMSecsToEpochMSecs(msecs, &dstStatus, &testDate, &testTime);
- status = mergeDaylightStatus(status, dstStatus);
-#if QT_CONFIG(timezone)
- // else spec == Qt::TimeZone, so check zone is valid:
- } else if (d->m_timeZone.isValid()) {
- epochMSecs = QDateTimePrivate::zoneMSecsToEpochMSecs(
- msecs, d->m_timeZone, extractDaylightStatus(status), &testDate, &testTime);
- d->setUtcOffsetByTZ(epochMSecs);
-#endif // timezone
- } // else: testDate, testTime haven't been set, so are invalid.
- if (testDate.isValid() && testTime.isValid()
- && timeToMSecs(testDate, testTime) == msecs) {
- status |= QDateTimePrivate::ValidDateTime;
- // Cache the offset to use in offsetFromUtc()
- offsetFromUtc = (msecs - epochMSecs) / 1000;
+ // We have a valid date and time and a Qt::LocalTime or Qt::TimeZone
+ // that might fall into a "missing" DST transition hour.
+ qint64 msecs = getMSecs(d);
+ QDateTimePrivate::ZoneState state = stateAtMillis(zone, msecs, resolve);
+ Q_ASSERT(!state.valid || (state.offset >= -SECS_PER_DAY && state.offset <= SECS_PER_DAY));
+ if (state.dst == QDateTimePrivate::UnknownDaylightTime) { // Overflow
+ status.setFlag(QDateTimePrivate::ValidDateTime, false);
+ } else if (state.valid) {
+ status = mergeDaylightStatus(status, state.dst);
+ offsetFromUtc = state.offset;
+ status.setFlag(QDateTimePrivate::ValidDateTime, true);
+ if (Q_UNLIKELY(msecs != state.when)) {
+ // Update msecs to the resolution:
+ if (status.testFlag(QDateTimePrivate::ShortData)) {
+ if (msecsCanBeSmall(state.when)) {
+ d.data.msecs = qintptr(state.when);
+ } else {
+ // Convert to long-form so we can hold the revised msecs:
+ status.setFlag(QDateTimePrivate::ShortData, false);
+ d.detach();
+ }
+ }
+ if (!status.testFlag(QDateTimePrivate::ShortData))
+ d->m_msecs = state.when;
+ }
} else {
- status &= ~QDateTimePrivate::ValidDateTime;
+ status.setFlag(QDateTimePrivate::ValidDateTime, false);
}
}
- if (status & QDateTimePrivate::ShortData) {
- d.data.status = status;
+ if (status.testFlag(QDateTimePrivate::ShortData)) {
+ d.data.status = status.toInt();
} else {
d->m_status = status;
d->m_offsetFromUtc = offsetFromUtc;
@@ -2839,23 +3227,20 @@ static void refreshZonedDateTime(QDateTimeData &d, Qt::TimeSpec spec)
static void refreshSimpleDateTime(QDateTimeData &d)
{
auto status = getStatus(d);
- Q_ASSERT(extractSpec(status) == Qt::UTC || extractSpec(status) == Qt::OffsetFromUTC);
- if ((status & QDateTimePrivate::ValidDate) && (status & QDateTimePrivate::ValidTime))
- status |= QDateTimePrivate::ValidDateTime;
- else
- status &= ~QDateTimePrivate::ValidDateTime;
+ Q_ASSERT(QTimeZone::isUtcOrFixedOffset(extractSpec(status)));
+ status.setFlag(QDateTimePrivate::ValidDateTime,
+ status.testFlags(QDateTimePrivate::ValidDate | QDateTimePrivate::ValidTime));
- if (status & QDateTimePrivate::ShortData)
- d.data.status = status;
+ if (status.testFlag(QDateTimePrivate::ShortData))
+ d.data.status = status.toInt();
else
d->m_status = status;
}
// Clean up and set status after assorted set-up or reworking:
-static void checkValidDateTime(QDateTimeData &d)
+static void checkValidDateTime(QDateTimeData &d, QDateTime::TransitionResolution resolve)
{
- auto status = getStatus(d);
- auto spec = extractSpec(status);
+ auto spec = extractSpec(getStatus(d));
switch (spec) {
case Qt::OffsetFromUTC:
case Qt::UTC:
@@ -2864,54 +3249,61 @@ static void checkValidDateTime(QDateTimeData &d)
break;
case Qt::TimeZone:
case Qt::LocalTime:
- // for these, we need to check whether the timezone is valid and whether
- // the time is valid in that timezone. Expensive, but no other option.
- refreshZonedDateTime(d, spec);
+ // For these, we need to check whether (the zone is valid and) the time
+ // is valid for the zone. Expensive, but we have no other option.
+ refreshZonedDateTime(d, d.timeZone(), toTransitionOptions(resolve));
break;
}
}
-// Caller needs to refresh after calling this
-static void setTimeSpec(QDateTimeData &d, Qt::TimeSpec spec, int offsetSeconds)
+static void reviseTimeZone(QDateTimeData &d, const QTimeZone &zone,
+ QDateTime::TransitionResolution resolve)
{
- auto status = getStatus(d);
- status &= ~(QDateTimePrivate::ValidDateTime | QDateTimePrivate::DaylightMask |
- QDateTimePrivate::TimeSpecMask);
+ Qt::TimeSpec spec = zone.timeSpec();
+ auto status = mergeSpec(getStatus(d), spec);
+ bool reuse = d.isShort();
+ int offset = 0;
switch (spec) {
+ case Qt::UTC:
+ Q_ASSERT(zone.fixedSecondsAheadOfUtc() == 0);
+ break;
case Qt::OffsetFromUTC:
- if (offsetSeconds == 0)
- spec = Qt::UTC;
+ reuse = false;
+ offset = zone.fixedSecondsAheadOfUtc();
+ Q_ASSERT(offset);
break;
case Qt::TimeZone:
- qWarning("Using TimeZone in setTimeSpec() is unsupported"); // Use system time zone instead
- spec = Qt::LocalTime;
- Q_FALLTHROUGH();
- case Qt::UTC:
+ reuse = false;
+ break;
case Qt::LocalTime:
- offsetSeconds = 0;
break;
}
- status = mergeSpec(status, spec);
- if (d.isShort() && offsetSeconds == 0) {
- d.data.status = status;
+ status &= ~(QDateTimePrivate::ValidDateTime | QDateTimePrivate::DaylightMask);
+ if (reuse) {
+ d.data.status = status.toInt();
} else {
d.detach();
d->m_status = status & ~QDateTimePrivate::ShortData;
- d->m_offsetFromUtc = offsetSeconds;
+ d->m_offsetFromUtc = offset;
#if QT_CONFIG(timezone)
- d->m_timeZone = QTimeZone();
+ if (spec == Qt::TimeZone)
+ d->m_timeZone = zone;
#endif // timezone
}
+
+ if (QTimeZone::isUtcOrFixedOffset(spec))
+ refreshSimpleDateTime(d);
+ else
+ refreshZonedDateTime(d, zone, toTransitionOptions(resolve));
}
static void setDateTime(QDateTimeData &d, QDate date, QTime time)
{
// If the date is valid and the time is not we set time to 00:00:00
- QTime useTime = time;
- if (!useTime.isValid() && date.isValid())
- useTime = QTime::fromMSecsSinceStartOfDay(0);
+ if (!time.isValid() && date.isValid())
+ time = QTime::fromMSecsSinceStartOfDay(0);
QDateTimePrivate::StatusFlags newStatus = { };
@@ -2924,20 +3316,31 @@ static void setDateTime(QDateTimeData &d, QDate date, QTime time)
// Set time value and status
int ds = 0;
- if (useTime.isValid()) {
- ds = useTime.msecsSinceStartOfDay();
+ if (time.isValid()) {
+ ds = time.msecsSinceStartOfDay();
newStatus |= QDateTimePrivate::ValidTime;
}
+ Q_ASSERT(ds < MSECS_PER_DAY);
+ // Only the later parts of the very first day are representable - its start
+ // would overflow - so get ds the same side of 0 as days:
+ if (days < 0 && ds > 0) {
+ days++;
+ ds -= MSECS_PER_DAY;
+ }
- // Set msecs serial value
- qint64 msecs = (days * MSECS_PER_DAY) + ds;
+ // Check in representable range:
+ qint64 msecs = 0;
+ if (daysAndMillisOverflow(days, qint64(ds), &msecs)) {
+ newStatus = QDateTimePrivate::StatusFlags{};
+ msecs = 0;
+ }
if (d.isShort()) {
// let's see if we can keep this short
if (msecsCanBeSmall(msecs)) {
// yes, we can
d.data.msecs = qintptr(msecs);
- d.data.status &= ~(QDateTimePrivate::ValidityMask | QDateTimePrivate::DaylightMask);
- d.data.status |= newStatus;
+ d.data.status &= ~(QDateTimePrivate::ValidityMask | QDateTimePrivate::DaylightMask).toInt();
+ d.data.status |= newStatus.toInt();
} else {
// nope...
d.detach();
@@ -2951,56 +3354,61 @@ static void setDateTime(QDateTimeData &d, QDate date, QTime time)
}
}
-static QPair<QDate, QTime> getDateTime(const QDateTimeData &d)
+static std::pair<QDate, QTime> getDateTime(const QDateTimeData &d)
{
- QPair<QDate, QTime> result;
- qint64 msecs = getMSecs(d);
auto status = getStatus(d);
- msecsToTime(msecs, &result.first, &result.second);
-
- if (!status.testFlag(QDateTimePrivate::ValidDate))
- result.first = QDate();
-
- if (!status.testFlag(QDateTimePrivate::ValidTime))
- result.second = QTime();
-
- return result;
+ const qint64 msecs = getMSecs(d);
+ const auto dayMilli = QRoundingDown::qDivMod<MSECS_PER_DAY>(msecs);
+ return { status.testFlag(QDateTimePrivate::ValidDate)
+ ? QDate::fromJulianDay(JULIAN_DAY_FOR_EPOCH + dayMilli.quotient)
+ : QDate(),
+ status.testFlag(QDateTimePrivate::ValidTime)
+ ? QTime::fromMSecsSinceStartOfDay(dayMilli.remainder)
+ : QTime() };
}
/*****************************************************************************
QDateTime::Data member functions
*****************************************************************************/
-inline QDateTime::Data::Data()
+inline QDateTime::Data::Data() noexcept
{
// default-constructed data has a special exception:
// it can be small even if CanBeSmall == false
// (optimization so we don't allocate memory in the default constructor)
- quintptr value = quintptr(mergeSpec(QDateTimePrivate::ShortData, Qt::LocalTime));
+ quintptr value = mergeSpec(QDateTimePrivate::ShortData, Qt::LocalTime).toInt();
d = reinterpret_cast<QDateTimePrivate *>(value);
}
-inline QDateTime::Data::Data(Qt::TimeSpec spec)
+inline QDateTime::Data::Data(const QTimeZone &zone)
{
+ Qt::TimeSpec spec = zone.timeSpec();
if (CanBeSmall && Q_LIKELY(specCanBeSmall(spec))) {
- d = reinterpret_cast<QDateTimePrivate *>(quintptr(mergeSpec(QDateTimePrivate::ShortData, spec)));
+ quintptr value = mergeSpec(QDateTimePrivate::ShortData, spec).toInt();
+ d = reinterpret_cast<QDateTimePrivate *>(value);
+ Q_ASSERT(isShort());
} else {
// the structure is too small, we need to detach
d = new QDateTimePrivate;
d->ref.ref();
d->m_status = mergeSpec({}, spec);
+ if (spec == Qt::OffsetFromUTC)
+ d->m_offsetFromUtc = zone.fixedSecondsAheadOfUtc();
+ else if (spec == Qt::TimeZone)
+ d->m_timeZone = zone;
+ Q_ASSERT(!isShort());
}
}
-inline QDateTime::Data::Data(const Data &other)
- : d(other.d)
+inline QDateTime::Data::Data(const Data &other) noexcept
+ : data(other.data)
{
if (!isShort()) {
// check if we could shrink
if (specCanBeSmall(extractSpec(d->m_status)) && msecsCanBeSmall(d->m_msecs)) {
ShortData sd;
sd.msecs = qintptr(d->m_msecs);
- sd.status = d->m_status | QDateTimePrivate::ShortData;
+ sd.status = (d->m_status | QDateTimePrivate::ShortData).toInt();
data = sd;
} else {
// no, have to keep it big
@@ -3009,18 +3417,18 @@ inline QDateTime::Data::Data(const Data &other)
}
}
-inline QDateTime::Data::Data(Data &&other)
- : d(other.d)
+inline QDateTime::Data::Data(Data &&other) noexcept
+ : data(other.data)
{
// reset the other to a short state
Data dummy;
Q_ASSERT(dummy.isShort());
- other.d = dummy.d;
+ other.data = dummy.data;
}
-inline QDateTime::Data &QDateTime::Data::operator=(const Data &other)
+inline QDateTime::Data &QDateTime::Data::operator=(const Data &other) noexcept
{
- if (d == other.d)
+ if (isShort() ? data == other.data : d == other.d)
return *this;
auto x = d;
@@ -3030,7 +3438,7 @@ inline QDateTime::Data &QDateTime::Data::operator=(const Data &other)
if (specCanBeSmall(extractSpec(other.d->m_status)) && msecsCanBeSmall(other.d->m_msecs)) {
ShortData sd;
sd.msecs = qintptr(other.d->m_msecs);
- sd.status = other.d->m_status | QDateTimePrivate::ShortData;
+ sd.status = (other.d->m_status | QDateTimePrivate::ShortData).toInt();
data = sd;
} else {
// no, have to keep it big
@@ -3054,11 +3462,11 @@ inline bool QDateTime::Data::isShort() const
bool b = quintptr(d) & QDateTimePrivate::ShortData;
// sanity check:
- Q_ASSERT(b || (d->m_status & QDateTimePrivate::ShortData) == 0);
+ Q_ASSERT(b || !d->m_status.testFlag(QDateTimePrivate::ShortData));
// even if CanBeSmall = false, we have short data for a default-constructed
// QDateTime object. But it's unlikely.
- if (CanBeSmall)
+ if constexpr (CanBeSmall)
return Q_LIKELY(b);
return Q_UNLIKELY(b);
}
@@ -3070,7 +3478,7 @@ inline void QDateTime::Data::detach()
if (wasShort) {
// force enlarging
x = new QDateTimePrivate;
- x->m_status = QDateTimePrivate::StatusFlag(data.status & ~QDateTimePrivate::ShortData);
+ x->m_status = QDateTimePrivate::StatusFlags::fromInt(data.status) & ~QDateTimePrivate::ShortData;
x->m_msecs = data.msecs;
} else {
if (d->ref.loadRelaxed() == 1)
@@ -3085,6 +3493,35 @@ inline void QDateTime::Data::detach()
d = x;
}
+void QDateTime::Data::invalidate()
+{
+ if (isShort()) {
+ data.status &= ~int(QDateTimePrivate::ValidityMask);
+ } else {
+ detach();
+ d->m_status &= ~QDateTimePrivate::ValidityMask;
+ }
+}
+
+QTimeZone QDateTime::Data::timeZone() const
+{
+ switch (getSpec(*this)) {
+ case Qt::UTC:
+ return QTimeZone::UTC;
+ case Qt::OffsetFromUTC:
+ return QTimeZone::fromSecondsAheadOfUtc(d->m_offsetFromUtc);
+ case Qt::TimeZone:
+#if QT_CONFIG(timezone)
+ if (d->m_timeZone.isValid())
+ return d->m_timeZone;
+#endif
+ break;
+ case Qt::LocalTime:
+ return QTimeZone::LocalTime;
+ }
+ return QTimeZone();
+}
+
inline const QDateTimePrivate *QDateTime::Data::operator->() const
{
Q_ASSERT(!isShort());
@@ -3104,54 +3541,18 @@ inline QDateTimePrivate *QDateTime::Data::operator->()
*****************************************************************************/
Q_NEVER_INLINE
-QDateTime::Data QDateTimePrivate::create(QDate toDate, QTime toTime, Qt::TimeSpec toSpec,
- int offsetSeconds)
+QDateTime::Data QDateTimePrivate::create(QDate toDate, QTime toTime, const QTimeZone &zone,
+ QDateTime::TransitionResolution resolve)
{
- QDateTime::Data result(toSpec);
- setTimeSpec(result, toSpec, offsetSeconds);
+ QDateTime::Data result(zone);
setDateTime(result, toDate, toTime);
- if (toSpec == Qt::OffsetFromUTC || toSpec == Qt::UTC)
+ if (zone.isUtcOrFixedOffset())
refreshSimpleDateTime(result);
else
- refreshZonedDateTime(result, Qt::LocalTime);
- return result;
-}
-
-#if QT_CONFIG(timezone)
-inline QDateTime::Data QDateTimePrivate::create(QDate toDate, QTime toTime,
- const QTimeZone &toTimeZone)
-{
- QDateTime::Data result(Qt::TimeZone);
- Q_ASSERT(!result.isShort());
-
- result.d->m_status = mergeSpec(result.d->m_status, Qt::TimeZone);
- result.d->m_timeZone = toTimeZone;
- setDateTime(result, toDate, toTime);
- refreshZonedDateTime(result, Qt::TimeZone);
+ refreshZonedDateTime(result, zone, toTransitionOptions(resolve));
return result;
}
-// Convert a TimeZone time expressed in zone msecs encoding into a UTC epoch msecs
-// DST transitions are disambiguated by hint.
-inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QTimeZone &zone,
- 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
- // but all affected times afterwards will have DST applied.
- if (data.atMSecsSinceEpoch < 0) {
- msecsToTime(zoneMSecs, zoneDate, zoneTime);
- return zoneMSecs - data.standardTimeOffset * 1000;
- } else {
- msecsToTime(data.atMSecsSinceEpoch + data.offsetFromUtc * 1000, zoneDate, zoneTime);
- return data.atMSecsSinceEpoch;
- }
-}
-#endif // timezone
-
/*****************************************************************************
QDateTime member functions
*****************************************************************************/
@@ -3163,37 +3564,42 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
\reentrant
\brief The QDateTime class provides date and time functions.
+ \compares weak
- A QDateTime object encodes a calendar date and a clock time (a
- "datetime"). It combines features of the QDate and QTime classes.
- It can read the current datetime from the system clock. It
- provides functions for comparing datetimes and for manipulating a
+ A QDateTime object encodes a calendar date and a clock time (a "datetime")
+ in accordance with a time representation. It combines features of the QDate
+ and QTime classes. It can read the current datetime from the system
+ clock. It provides functions for comparing datetimes and for manipulating a
datetime by adding a number of seconds, days, months, or years.
QDateTime can describe datetimes with respect to \l{Qt::LocalTime}{local
time}, to \l{Qt::UTC}{UTC}, to a specified \l{Qt::OffsetFromUTC}{offset from
- UTC} or to a specified \l{Qt::TimeZone}{time zone}, in conjunction with the
- QTimeZone class. For example, a time zone of "Europe/Berlin" will apply the
- daylight-saving rules as used in Germany since 1970. In contrast, an offset
- from UTC of +3600 seconds is one hour ahead of UTC (usually written in ISO
- standard notation as "UTC+01:00"), with no daylight-saving offset or
- changes. When using either local time or a specified time zone, time-zone
- transitions such as the starts and ends of daylight-saving time (DST; but
- see below) are taken into account. The choice of system used to represent a
- datetime is described as its "timespec".
+ UTC} or to a specified \l{Qt::TimeZone}{time zone}. Each of these time
+ representations can be encapsulated in a suitable instance of the QTimeZone
+ class. For example, a time zone of "Europe/Berlin" will apply the
+ daylight-saving rules as used in Germany. In contrast, a fixed offset from
+ UTC of +3600 seconds is one hour ahead of UTC (usually written in ISO
+ standard notation as "UTC+01:00"), with no daylight-saving
+ complications. When using either local time or a specified time zone,
+ time-zone transitions (see \l {Timezone transitions}{below}) are taken into
+ account. A QDateTime's timeSpec() will tell you which of the four types of
+ time representation is in use; its timeRepresentation() provides a full
+ description of that time representation, as a QTimeZone.
A QDateTime object is typically created either by giving a date and time
explicitly in the constructor, or by using a static function such as
currentDateTime() or fromMSecsSinceEpoch(). The date and time can be changed
with setDate() and setTime(). A datetime can also be set using the
setMSecsSinceEpoch() function that takes the time, in milliseconds, since
- 00:00:00 on January 1, 1970. The fromString() function returns a QDateTime,
- given a string and a date format used to interpret the date within the
- string.
+ the start, in UTC, of the year 1970. The fromString() function returns a
+ QDateTime, given a string and a date format used to interpret the date
+ within the string.
QDateTime::currentDateTime() returns a QDateTime that expresses the current
- time with respect to local time. QDateTime::currentDateTimeUtc() returns a
- QDateTime that expresses the current time with respect to UTC.
+ date and time with respect to a specific time representation, such as local
+ time (its default). QDateTime::currentDateTimeUtc() returns a QDateTime that
+ expresses the current date and time with respect to UTC; it is equivalent to
+ \c {QDateTime::currentDateTime(QTimeZone::UTC)}.
The date() and time() functions provide access to the date and
time parts of the datetime. The same information is provided in
@@ -3212,17 +3618,17 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
daylight-saving time (DST) and other time-zone transitions, where
applicable.
- Use toTimeSpec() to express a datetime in local time or UTC,
- toOffsetFromUtc() to express in terms of an offset from UTC, or toTimeZone()
- to express it with respect to a general time zone. You can use timeSpec() to
- find out what time-spec a QDateTime object stores its time relative to. When
- that is Qt::TimeZone, you can use timeZone() to find out which zone it is
- using.
-
- \note QDateTime does not account for leap seconds.
+ Use toTimeZone() to re-express a datetime in terms of a different time
+ representation. By passing a lightweight QTimeZone that represents local
+ time, UTC or a fixed offset from UTC, you can convert the datetime to use
+ the corresponding time representation; or you can pass a full time zone
+ (whose \l {QTimeZone::timeSpec()}{timeSpec()} is \c {Qt::TimeZone}) to use
+ that instead.
\section1 Remarks
+ \note QDateTime does not account for leap seconds.
+
\note All conversion to and from string formats is done using the C locale.
For localized conversions, see QLocale.
@@ -3230,15 +3636,21 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
considered invalid. The year -1 is the year "1 before Christ" or "1 before
common era." The day before 1 January 1 CE is 31 December 1 BCE.
+ \note Using local time (the default) or a specified time zone implies a need
+ to resolve any issues around \l {Timezone transitions}{transitions}. As a
+ result, operations on such QDateTime instances (notably including
+ constructing them) may be more expensive than the equivalent when using UTC
+ or a fixed offset from it.
+
\section2 Range of Valid Dates
The range of values that QDateTime can represent is dependent on the
internal storage implementation. QDateTime is currently stored in a qint64
as a serial msecs value encoding the date and time. This restricts the date
- range to about +/- 292 million years, compared to the QDate range of +/- 2
- billion years. Care must be taken when creating a QDateTime with extreme
- values that you do not overflow the storage. The exact range of supported
- values varies depending on the Qt::TimeSpec and time zone.
+ range to about ±292 million years, compared to the QDate range of ±2 billion
+ years. Care must be taken when creating a QDateTime with extreme values that
+ you do not overflow the storage. The exact range of supported values varies
+ depending on the time representation used.
\section2 Use of Timezones
@@ -3255,34 +3667,106 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
information about historical transitions (including DST, see below) whenever
possible. On Windows, where the system doesn't support historical timezone
data, historical accuracy is not maintained with respect to timezone
- transitions, notably including DST.
-
- \section2 Daylight-Saving Time (DST)
-
- QDateTime takes into account transitions between Standard Time and
- Daylight-Saving Time. For example, if the transition is at 2am and the clock
- goes forward to 3am, then there is a "missing" hour from 02:00:00 to
- 02:59:59.999 which QDateTime considers to be invalid. Any date arithmetic
- performed will take this missing hour into account and return a valid
- result. For example, adding one minute to 01:59:59 will get 03:00:00.
-
- The range of valid dates taking DST into account is 1970-01-01 to the
- present, and rules are in place for handling DST correctly until 2037-12-31,
- but these could change. For dates after 2037, QDateTime makes a \e{best
- guess} using the rules for year 2037, but we can't guarantee accuracy;
- indeed, for \e{any} future date, the time-zone may change its rules before
- that date comes around. For dates before 1970, QDateTime doesn't take DST
- changes into account, even if the system's time zone database provides that
- information, although it does take into account changes to the time-zone's
- standard offset, where this information is available.
+ transitions, notably including DST. However, building Qt with the ICU
+ library will equip QTimeZone with the same timezone database as is used on
+ Unix.
+
+ \section2 Timezone transitions
+
+ QDateTime takes into account timezone transitions, both the transitions
+ between Standard Time and Daylight-Saving Time (DST) and the transitions
+ that arise when a zone changes its standard offset. For example, if the
+ transition is at 2am and the clock goes forward to 3am, then there is a
+ "missing" hour from 02:00:00 to 02:59:59.999. Such a transition is known as
+ a "spring forward" and the times skipped over have no meaning. When a
+ transition goes the other way, known as a "fall back", a time interval is
+ repeated, first in the old zone (usually DST), then in the new zone (usually
+ Standard Time), so times in this interval are ambiguous.
+
+ Some zones use "reversed" DST, using standard time in summer and
+ daylight-saving time (with a lowered offset) in winter. For such zones, the
+ spring forward still happens in spring and skips an hour, but is a
+ transition \e{out of} daylight-saving time, while the fall back still
+ repeats an autumn hour but is a transition \e to daylight-saving time.
+
+ When converting from a UTC time (or a time at fixed offset from UTC), there
+ is always an unambiguous valid result in any timezone. However, when
+ combining a date and time to make a datetime, expressed with respect to
+ local time or a specific time-zone, the nominal result may fall in a
+ transition, making it either invalid or ambiguous. Methods where this
+ situation may arise take a \c resolve parameter: this is always ignored if
+ the requested datetime is valid and unambiguous. See \l TransitionResolution
+ for the options it lets you control. Prior to Qt 6.7, the equivalent of its
+ \l LegacyBehavior was selected.
+
+ For a spring forward's skipped interval, interpreting the requested time
+ with either offset yields an actual time at which the other offset was in
+ use; so passing \c TransitionResolution::RelativeToBefore for \c resolve
+ will actually result in a time after the transition, that would have had the
+ requested representation had the transition not happened. Likewise, \c
+ TransitionResolution::RelativeToAfter for \c resolve results in a time
+ before the transition, that would have had the requested representation, had
+ the transition happened earlier.
+
+ When QDateTime performs arithmetic, as with addDay() or addSecs(), it takes
+ care to produce a valid result. For example, on a day when there is a spring
+ forward from 02:00 to 03:00, adding one second to 01:59:59 will get
+ 03:00:00. Adding one day to 02:30 on the preceding day will get 03:30 on the
+ day of the transition, while subtracting one day, by calling \c{addDay(-1)},
+ to 02:30 on the following day will get 01:30 on the day of the transition.
+ While addSecs() will deliver a time offset by the given number of seconds,
+ addDays() adjusts the date and only adjusts time if it would otherwise get
+ an invalid result. Applying \c{addDays(1)} to 03:00 on the day before the
+ spring-forward will simply get 03:00 on the day of the transition, even
+ though the latter is only 23 hours after the former; but \c{addSecs(24 * 60
+ * 60)} will get 04:00 on the day of the transition, since that's 24 hours
+ later. Typical transitions make some days 23 or 25 hours long.
+
+ For datetimes that the system \c time_t can represent (from 1901-12-14 to
+ 2038-01-18 on systems with 32-bit \c time_t; for the full range QDateTime
+ can represent if the type is 64-bit), the standard system APIs are used to
+ determine local time's offset from UTC. For datetimes not handled by these
+ system APIs (potentially including some within the \c time_t range),
+ QTimeZone::systemTimeZone() is used, if available, or a best effort is made
+ to estimate. In any case, the offset information used depends on the system
+ and may be incomplete or, for past times, historically
+ inaccurate. Furthermore, for future dates, the local time zone's offsets and
+ DST rules may change before that date comes around.
+
+ \section3 Whole day transitions
+
+ A small number of zones have skipped or repeated entire days as part of
+ moving The International Date Line across themselves. For these, daysTo()
+ will be unaware of the duplication or gap, simply using the difference in
+ calendar date; in contrast, msecsTo() and secsTo() know the true time
+ interval. Likewise, addMSecs() and addSecs() correspond directly to elapsed
+ time, where addDays(), addMonths() and addYears() follow the nominal
+ calendar, aside from where landing in a gap or duplication requires
+ resolving an ambiguity or invalidity due to a duplication or omission.
+
+ \note Days "lost" during a change of calendar, such as from Julian to
+ Gregorian, do not affect QDateTime. Although the two calendars describe
+ dates differently, the successive days across the change are described by
+ consecutive QDate instances, each one day later than the previous, as
+ described by either calendar or by their toJulianDay() values. In contrast,
+ a zone skipping or duplicating a day is changing its description of \e time,
+ not date, for all that it does so by a whole 24 hours.
\section2 Offsets From UTC
+ Offsets from UTC are measured in seconds east of Greenwich. The moment
+ described by a particular date and time, such as noon on a particular day,
+ depends on the time representation used. Those with a higher offset from UTC
+ describe an earlier moment, and those with a lower offset a later moment, by
+ any given combination of date and time.
+
There is no explicit size restriction on an offset from UTC, but there is an
implicit limit imposed when using the toString() and fromString() methods
- which use a [+|-]hh:mm format, effectively limiting the range to +/- 99
- hours and 59 minutes and whole minutes only. Note that currently no time
- zone lies outside the range of +/- 14 hours.
+ which use a ±hh:mm format, effectively limiting the range to ± 99 hours and
+ 59 minutes and whole minutes only. Note that currently no time zone has an
+ offset outside the range of ±14 hours and all known offsets are multiples of
+ five minutes. Historical time zones have a wider range and may have offsets
+ including seconds; these last cannot be faithfully represented in strings.
\sa QDate, QTime, QDateTimeEdit, QTimeZone
*/
@@ -3308,53 +3792,230 @@ inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QT
*/
/*!
- Constructs a null datetime (i.e. null date and null time). A null
- datetime is invalid, since the date is invalid.
+ \since 6.7
+ \enum QDateTime::TransitionResolution
+
+ This enumeration is used to resolve datetime combinations which fall in \l
+ {Timezone transitions}.
+
+ When constructing a datetime, specified in terms of local time or a
+ time-zone that has daylight-saving time, or revising one with setDate(),
+ setTime() or setTimeZone(), the given parameters may imply a time
+ representation that either has no meaning or has two meanings in the
+ zone. Such time representations are described as being in the transition. In
+ either case, we can simply return an invalid datetime, to indicate that the
+ operation is ill-defined. In the ambiguous case, we can alternatively select
+ one of the two times that could be meant. When there is no meaning, we can
+ select a time either side of it that might plausibly have been meant. For
+ example, when advancing from an earlier time, we can select the time after
+ the transition that is actually the specified amount of time after the
+ earlier time in question. The options specified here configure how such
+ selection is performed.
+
+ \value Reject
+ Treat any time in a transition as invalid. Either it really is, or it
+ is ambiguous.
+ \value RelativeToBefore
+ Selects a time as if stepping forward from a time before the
+ transition. This interprets the requested time using the offset in
+ effect before the transition and, if necessary, converts the result
+ to the offset in effect at the resulting time.
+ \value RelativeToAfter
+ Select a time as if stepping backward from a time after the
+ transition. This interprets the requested time using the offset in
+ effect after the transition and, if necessary, converts the result to
+ the offset in effect at the resulting time.
+ \value PreferBefore
+ Selects a time before the transition,
+ \value PreferAfter
+ Selects a time after the transition.
+ \value PreferStandard
+ Selects a time on the standard time side of the transition.
+ \value PreferDaylightSaving
+ Selects a time on the daylight-saving-time side of the transition.
+ \value LegacyBehavior
+ An alias for RelativeToBefore, which is used as default for
+ TransitionResolution parameters, as this most closely matches the
+ behavior prior to Qt 6.7.
+
+ For \l addDays(), \l addMonths() or \l addYears(), the behavior is and
+ (mostly) was to use \c RelativeToBefore if adding a positive adjustment and \c
+ RelativeToAfter if adding a negative adjustment.
+
+ \note In time zones where daylight-saving increases the offset from UTC in
+ summer (known as "positive DST"), PreferStandard is an alias for
+ RelativeToAfter and PreferDaylightSaving for RelativeToBefore. In time zones
+ where the daylight-saving mechanism is a decrease in offset from UTC in
+ winter (known as "negative DST"), the reverse applies, provided the
+ operating system reports - as it does on most platforms - whether a datetime
+ is in DST or standard time. For some platforms, where transition times are
+ unavailable even for Qt::TimeZone datetimes, QTimeZone is obliged to presume
+ that the side with lower offset from UTC is standard time, effectively
+ assuming positive DST.
+
+ The following tables illustrate how a QDateTime constructor resolves a
+ request for 02:30 on a day when local time has a transition between 02:00
+ and 03:00, with a nominal standard time LST and daylight-saving time LDT on
+ the two sides, in the various possible cases. The transition type may be to
+ skip an hour or repeat it. The type of transition and value of a parameter
+ \c resolve determine which actual time on the given date is selected. First,
+ the common case of positive daylight-saving, where:
- \sa isValid()
+ \table
+ \header \li Before \li 02:00--03:00 \li After \li \c resolve \li selected
+ \row \li LST \li skip \li LDT \li RelativeToBefore \li 03:30 LDT
+ \row \li LST \li skip \li LDT \li RelativeToAfter \li 01:30 LST
+ \row \li LST \li skip \li LDT \li PreferBefore \li 01:30 LST
+ \row \li LST \li skip \li LDT \li PreferAfter \li 03:30 LDT
+ \row \li LST \li skip \li LDT \li PreferStandard \li 01:30 LST
+ \row \li LST \li skip \li LDT \li PreferDaylightSaving \li 03:30 LDT
+ \row \li LDT \li repeat \li LST \li RelativeToBefore \li 02:30 LDT
+ \row \li LDT \li repeat \li LST \li RelativeToAfter \li 02:30 LST
+ \row \li LDT \li repeat \li LST \li PreferBefore \li 02:30 LDT
+ \row \li LDT \li repeat \li LST \li PreferAfter \li 02:30 LST
+ \row \li LDT \li repeat \li LST \li PreferStandard \li 02:30 LST
+ \row \li LDT \li repeat \li LST \li PreferDaylightSaving \li 02:30 LDT
+ \endtable
+
+ Second, the case for negative daylight-saving, using LDT in winter and
+ skipping an hour to transition to LST in summer, then repeating an hour at
+ the transition back to winter:
+
+ \table
+ \row \li LDT \li skip \li LST \li RelativeToBefore \li 03:30 LST
+ \row \li LDT \li skip \li LST \li RelativeToAfter \li 01:30 LDT
+ \row \li LDT \li skip \li LST \li PreferBefore \li 01:30 LDT
+ \row \li LDT \li skip \li LST \li PreferAfter \li 03:30 LST
+ \row \li LDT \li skip \li LST \li PreferStandard \li 03:30 LST
+ \row \li LDT \li skip \li LST \li PreferDaylightSaving \li 01:30 LDT
+ \row \li LST \li repeat \li LDT \li RelativeToBefore \li 02:30 LST
+ \row \li LST \li repeat \li LDT \li RelativeToAfter \li 02:30 LDT
+ \row \li LST \li repeat \li LDT \li PreferBefore \li 02:30 LST
+ \row \li LST \li repeat \li LDT \li PreferAfter \li 02:30 LDT
+ \row \li LST \li repeat \li LDT \li PreferStandard \li 02:30 LST
+ \row \li LST \li repeat \li LDT \li PreferDaylightSaving \li 02:30 LDT
+ \endtable
+
+ Reject can be used to prompt relevant QDateTime APIs to return an invalid
+ datetime object so that your code can deal with transitions for itself, for
+ example by alerting a user to the fact that the datetime they have selected
+ is in a transition interval, to offer them the opportunity to resolve a
+ conflict or ambiguity. Code using this may well find the other options above
+ useful to determine relevant information to use in its own (or the user's)
+ resolution. If the start or end of the transition, or the moment of the
+ transition itself, is the right resolution, QTimeZone's transition APIs can
+ be used to obtain that information. You can determine whether the transition
+ is a repeated or skipped interval by using \l secsTo() to measure the actual
+ time between noon on the previous and following days. The result will be
+ less than 48 hours for a skipped interval (such as a spring-forward) and
+ more than 48 hours for a repeated interval (such as a fall-back).
+
+ \note When a resolution other than Reject is specified, a valid QDateTime
+ object is returned, if possible. If the requested date-time falls in a gap,
+ the returned date-time will not have the time() requested - or, in some
+ cases, the date(), if a whole day was skipped. You can thus detect when a
+ gap is hit by comparing date() and time() to what was requested.
+
+ \section2 Relation to other datetime software
+
+ The Python programming language's datetime APIs have a \c fold parameter
+ that corresponds to \c RelativeToBefore (\c{fold = True}) and \c
+ RelativeToAfter (\c{fold = False}).
+
+ The \c Temporal proposal to replace JavaScript's \c Date offers four options
+ for how to resolve a transition, as value for a \c disambiguation
+ parameter. Its \c{'reject'} raises an exception, which roughly corresponds
+ to \c Reject producing an invalid result. Its \c{'earlier'} and \c{'later'}
+ options correspond to \c PreferBefore and \c PreferAfter. Its
+ \c{'compatible'} option corresponds to \c RelativeToBefore (and Python's
+ \c{fold = True}).
+
+ \sa {Timezone transitions}, QDateTime::TransitionResolution
+*/
+
+/*!
+ Constructs a null datetime, nominally using local time.
+
+ A null datetime is invalid, since its date and time are invalid.
+
+ \sa isValid(), setMSecsSinceEpoch(), setDate(), setTime(), setTimeZone()
*/
-QDateTime::QDateTime() noexcept(Data::CanBeSmall)
+QDateTime::QDateTime() noexcept
{
+#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0) || defined(QT_BOOTSTRAPPED) || QT_POINTER_SIZE == 8
+ static_assert(sizeof(ShortData) == sizeof(qint64));
+ static_assert(sizeof(Data) == sizeof(qint64));
+#endif
+ static_assert(sizeof(ShortData) >= sizeof(void*), "oops, Data::swap() is broken!");
}
+#if QT_DEPRECATED_SINCE(6, 9)
/*!
- Constructs a datetime with the given \a date and \a time, using
- the time specification defined by \a spec and \a offsetSeconds seconds.
+ \deprecated [6.9] Use \c{QDateTime(date, time)} or \c{QDateTime(date, time, QTimeZone::fromSecondsAheadOfUtc(offsetSeconds))}.
- If \a date is valid and \a time is not, the time will be set to midnight.
+ Constructs a datetime with the given \a date and \a time, using the time
+ representation implied by \a spec and \a offsetSeconds seconds.
- If the \a spec is not Qt::OffsetFromUTC then \a offsetSeconds will be ignored.
+ If \a date is valid and \a time is not, the time will be set to midnight.
- If the \a spec is Qt::OffsetFromUTC and \a offsetSeconds is 0 then the
+ If \a spec is not Qt::OffsetFromUTC then \a offsetSeconds will be
+ ignored. If \a spec is Qt::OffsetFromUTC and \a offsetSeconds is 0 then the
timeSpec() will be set to Qt::UTC, i.e. an offset of 0 seconds.
If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
i.e. the current system time zone. To create a Qt::TimeZone datetime
use the correct constructor.
-*/
+ If \a date lies outside the range of dates representable by QDateTime, the
+ result is invalid. If \a spec is Qt::LocalTime and the system's time-zone
+ skipped over the given date and time, the result is invalid.
+*/
QDateTime::QDateTime(QDate date, QTime time, Qt::TimeSpec spec, int offsetSeconds)
- : d(QDateTimePrivate::create(date, time, spec, offsetSeconds))
+ : d(QDateTimePrivate::create(date, time, asTimeZone(spec, offsetSeconds, "QDateTime"),
+ TransitionResolution::LegacyBehavior))
{
}
+#endif // 6.9 deprecation
-#if QT_CONFIG(timezone)
/*!
\since 5.2
- Constructs a datetime with the given \a date and \a time, using
- the Time Zone specified by \a timeZone.
+ Constructs a datetime with the given \a date and \a time, using the time
+ representation described by \a timeZone.
- If \a date is valid and \a time is not, the time will be set to 00:00:00.
+ If \a date is valid and \a time is not, the time will be set to midnight.
+ If \a timeZone is invalid then the datetime will be invalid. If \a date and
+ \a time describe a moment close to a transition for \a timeZone, \a resolve
+ controls how that situation is resolved.
- If \a timeZone is invalid then the datetime will be invalid.
+//! [pre-resolve-note]
+ \note Prior to Qt 6.7, the version of this function lacked the \a resolve
+ parameter so had no way to resolve the ambiguities related to transitions.
+//! [pre-resolve-note]
*/
-QDateTime::QDateTime(QDate date, QTime time, const QTimeZone &timeZone)
- : d(QDateTimePrivate::create(date, time, timeZone))
+QDateTime::QDateTime(QDate date, QTime time, const QTimeZone &timeZone, TransitionResolution resolve)
+ : d(QDateTimePrivate::create(date, time, timeZone, resolve))
+{
+}
+
+/*!
+ \since 6.5
+ \overload
+
+ Constructs a datetime with the given \a date and \a time, using local time.
+
+ If \a date is valid and \a time is not, midnight will be used as the
+ time. If \a date and \a time describe a moment close to a transition for
+ local time, \a resolve controls how that situation is resolved.
+
+ \include qdatetime.cpp pre-resolve-note
+*/
+
+QDateTime::QDateTime(QDate date, QTime time, TransitionResolution resolve)
+ : d(QDateTimePrivate::create(date, time, QTimeZone::LocalTime, resolve))
{
}
-#endif // timezone
/*!
Constructs a copy of the \a other datetime.
@@ -3382,8 +4043,7 @@ QDateTime::~QDateTime()
}
/*!
- Makes a copy of the \a other datetime and returns a reference to the
- copy.
+ Copies the \a other datetime into this and returns this copy.
*/
QDateTime &QDateTime::operator=(const QDateTime &other) noexcept
@@ -3408,65 +4068,60 @@ QDateTime &QDateTime::operator=(const QDateTime &other) noexcept
bool QDateTime::isNull() const
{
- auto status = getStatus(d);
- return !status.testFlag(QDateTimePrivate::ValidDate) &&
- !status.testFlag(QDateTimePrivate::ValidTime);
+ // If date or time is invalid, we don't set datetime valid.
+ return !getStatus(d).testAnyFlag(QDateTimePrivate::ValidityMask);
}
/*!
- Returns \c true if both the date and the time are valid and they are valid in
- the current Qt::TimeSpec, otherwise returns \c false.
+ Returns \c true if this datetime represents a definite moment, otherwise \c false.
- If the timeSpec() is Qt::LocalTime or Qt::TimeZone then the date and time are
- checked to see if they fall in the Standard Time to Daylight-Saving Time transition
- hour, i.e. if the transition is at 2am and the clock goes forward to 3am
- then the time from 02:00:00 to 02:59:59.999 is considered to be invalid.
+ A datetime is valid if both its date and its time are valid and the time
+ representation used gives a valid meaning to their combination. When the
+ time representation is a specific time-zone or local time, there may be
+ times on some dates that the zone skips in its representation, as when a
+ daylight-saving transition skips an hour (typically during a night in
+ spring). For example, if DST ends at 2am with the clock advancing to 3am,
+ then datetimes from 02:00:00 to 02:59:59.999 on that day are invalid.
\sa QDateTime::YearRange, QDate::isValid(), QTime::isValid()
*/
bool QDateTime::isValid() const
{
- auto status = getStatus(d);
- return status & QDateTimePrivate::ValidDateTime;
+ return getStatus(d).testFlag(QDateTimePrivate::ValidDateTime);
}
/*!
Returns the date part of the datetime.
- \sa setDate(), time(), timeSpec()
+ \sa setDate(), time(), timeRepresentation()
*/
QDate QDateTime::date() const
{
- auto status = getStatus(d);
- if (!status.testFlag(QDateTimePrivate::ValidDate))
- return QDate();
- QDate dt;
- msecsToTime(getMSecs(d), &dt, nullptr);
- return dt;
+ return getStatus(d).testFlag(QDateTimePrivate::ValidDate) ? msecsToDate(getMSecs(d)) : QDate();
}
/*!
Returns the time part of the datetime.
- \sa setTime(), date(), timeSpec()
+ \sa setTime(), date(), timeRepresentation()
*/
QTime QDateTime::time() const
{
- auto status = getStatus(d);
- if (!status.testFlag(QDateTimePrivate::ValidTime))
- return QTime();
- QTime tm;
- msecsToTime(getMSecs(d), nullptr, &tm);
- return tm;
+ return getStatus(d).testFlag(QDateTimePrivate::ValidTime) ? msecsToTime(getMSecs(d)) : QTime();
}
/*!
Returns the time specification of the datetime.
- \sa setTimeSpec(), date(), time(), Qt::TimeSpec
+ This classifies its time representation as local time, UTC, a fixed offset
+ from UTC (without indicating the offset) or a time zone (without giving the
+ details of that time zone). Equivalent to
+ \c{timeRepresentation().timeSpec()}.
+
+ \sa setTimeSpec(), timeRepresentation(), date(), time()
*/
Qt::TimeSpec QDateTime::timeSpec() const
@@ -3474,41 +4129,51 @@ Qt::TimeSpec QDateTime::timeSpec() const
return getSpec(d);
}
+/*!
+ \since 6.5
+ Returns a QTimeZone identifying how this datetime represents time.
+
+ The timeSpec() of the returned QTimeZone will coincide with that of this
+ datetime; if it is not Qt::TimeZone then the returned QTimeZone is a time
+ representation. When their timeSpec() is Qt::OffsetFromUTC, the returned
+ QTimeZone's fixedSecondsAheadOfUtc() supplies the offset. When timeSpec()
+ is Qt::TimeZone, the QTimeZone object itself is the full representation of
+ that time zone.
+
+ \sa timeZone(), setTimeZone(), QTimeZone::asBackendZone()
+*/
+
+QTimeZone QDateTime::timeRepresentation() const
+{
+ return d.timeZone();
+}
+
#if QT_CONFIG(timezone)
/*!
\since 5.2
Returns the time zone of the datetime.
- If the timeSpec() is Qt::LocalTime then an instance of the current system
- time zone will be returned. Note however that if you copy this time zone
- the instance will not remain in sync if the system time zone changes.
+ The result is the same as \c{timeRepresentation().asBackendZone()}. In all
+ cases, the result's \l {QTimeZone::timeSpec()}{timeSpec()} is Qt::TimeZone.
- \sa setTimeZone(), Qt::TimeSpec
+ When timeSpec() is Qt::LocalTime, the result will describe local time at the
+ time this method was called. It will not reflect subsequent changes to the
+ system time zone, even when the QDateTime from which it was obtained does.
+
+ \sa timeRepresentation(), setTimeZone(), Qt::TimeSpec, QTimeZone::asBackendZone()
*/
QTimeZone QDateTime::timeZone() const
{
- switch (getSpec(d)) {
- case Qt::UTC:
- return QTimeZone::utc();
- case Qt::OffsetFromUTC:
- return QTimeZone(d->m_offsetFromUtc);
- case Qt::TimeZone:
- if (d->m_timeZone.isValid())
- return d->m_timeZone;
- break;
- case Qt::LocalTime:
- return QTimeZone::systemTimeZone();
- }
- return QTimeZone();
+ return d.timeZone().asBackendZone();
}
#endif // timezone
/*!
\since 5.2
- Returns this date-time's Offset From UTC in seconds.
+ Returns this datetime's Offset From UTC in seconds.
The result depends on timeSpec():
\list
@@ -3519,27 +4184,28 @@ QTimeZone QDateTime::timeZone() const
\endlist
For the last two, the offset at this date and time will be returned, taking
- account of Daylight-Saving Offset unless the date precedes the start of
- 1970. The offset is the difference between the local time or time in the
- given time-zone and UTC time; it is positive in time-zones ahead of UTC
- (East of The Prime Meridian), negative for those behind UTC (West of The
- Prime Meridian).
+ account of Daylight-Saving Offset. The offset is the difference between the
+ local time or time in the given time-zone and UTC time; it is positive in
+ time-zones ahead of UTC (East of The Prime Meridian), negative for those
+ behind UTC (West of The Prime Meridian).
\sa setOffsetFromUtc()
*/
int QDateTime::offsetFromUtc() const
{
+ const auto status = getStatus(d);
+ if (!status.testFlags(QDateTimePrivate::ValidDate | QDateTimePrivate::ValidTime))
+ return 0;
+ // But allow invalid date-time (e.g. gap's resolution) to report its offset.
if (!d.isShort())
return d->m_offsetFromUtc;
- if (!isValid())
- return 0;
- auto spec = getSpec(d);
+ auto spec = extractSpec(status);
if (spec == Qt::LocalTime) {
- // we didn't cache the value, so we need to calculate it now...
- qint64 msecs = getMSecs(d);
- return (msecs - toMSecsSinceEpoch()) / 1000;
+ // We didn't cache the value, so we need to calculate it:
+ const auto resolve = toTransitionOptions(extractDaylightStatus(status));
+ return QDateTimePrivate::localStateAtMillis(getMSecs(d), resolve).offset;
}
Q_ASSERT(spec == Qt::UTC);
@@ -3549,22 +4215,22 @@ int QDateTime::offsetFromUtc() const
/*!
\since 5.2
- Returns the Time Zone Abbreviation for the datetime.
-
- If the timeSpec() is Qt::UTC this will be "UTC".
+ Returns the Time Zone Abbreviation for this datetime.
- If the timeSpec() is Qt::OffsetFromUTC this will be in the format
- "UTC[+-]00:00".
+ The returned string depends on timeSpec():
- If the timeSpec() is Qt::LocalTime then the host system is queried for the
- correct abbreviation.
-
- Note that abbreviations may or may not be localized.
+ \list
+ \li For Qt::UTC it is "UTC".
+ \li For Qt::OffsetFromUTC it will be in the format "UTC±00:00".
+ \li For Qt::LocalTime, the host system is queried.
+ \li For Qt::TimeZone, the associated QTimeZone object is queried.
+ \endlist
- Note too that the abbreviation is not guaranteed to be a unique value,
- i.e. different time zones may have the same abbreviation.
+ \note The abbreviation is not guaranteed to be unique, i.e. different time
+ zones may have the same abbreviation. For Qt::LocalTime and Qt::TimeZone,
+ when returned by the host system, the abbreviation may be localized.
- \sa timeSpec()
+ \sa timeSpec(), QTimeZone::abbreviation()
*/
QString QDateTime::timeZoneAbbreviation() const
@@ -3574,22 +4240,19 @@ QString QDateTime::timeZoneAbbreviation() const
switch (getSpec(d)) {
case Qt::UTC:
- return QLatin1String("UTC");
+ return "UTC"_L1;
case Qt::OffsetFromUTC:
- return QLatin1String("UTC") + toOffsetString(Qt::ISODate, d->m_offsetFromUtc);
+ return "UTC"_L1 + toOffsetString(Qt::ISODate, d->m_offsetFromUtc);
case Qt::TimeZone:
#if !QT_CONFIG(timezone)
break;
#else
Q_ASSERT(d->m_timeZone.isValid());
- return d->m_timeZone.d->abbreviation(toMSecsSinceEpoch());
+ return d->m_timeZone.abbreviation(*this);
#endif // timezone
- case Qt::LocalTime: {
- QString abbrev;
- auto status = extractDaylightStatus(getStatus(d));
- localMSecsToEpochMSecs(getMSecs(d), &status, nullptr, nullptr, &abbrev);
- return abbrev;
- }
+ case Qt::LocalTime:
+ return QDateTimePrivate::localNameAtMillis(getMSecs(d),
+ extractDaylightStatus(getStatus(d)));
}
return QString();
}
@@ -3619,29 +4282,43 @@ bool QDateTime::isDaylightTime() const
break;
#else
Q_ASSERT(d->m_timeZone.isValid());
+ if (auto dst = extractDaylightStatus(getStatus(d));
+ dst != QDateTimePrivate::UnknownDaylightTime) {
+ return dst == QDateTimePrivate::DaylightTime;
+ }
return d->m_timeZone.d->isDaylightTime(toMSecsSinceEpoch());
#endif // timezone
case Qt::LocalTime: {
- auto status = extractDaylightStatus(getStatus(d));
- if (status == QDateTimePrivate::UnknownDaylightTime)
- localMSecsToEpochMSecs(getMSecs(d), &status);
- return (status == QDateTimePrivate::DaylightTime);
+ auto dst = extractDaylightStatus(getStatus(d));
+ if (dst == QDateTimePrivate::UnknownDaylightTime) {
+ dst = QDateTimePrivate::localStateAtMillis(
+ getMSecs(d), toTransitionOptions(TransitionResolution::LegacyBehavior)).dst;
+ }
+ return dst == QDateTimePrivate::DaylightTime;
}
}
return false;
}
/*!
- Sets the date part of this datetime to \a date. If no time is set yet, it
- is set to midnight. If \a date is invalid, this QDateTime becomes invalid.
+ Sets the date part of this datetime to \a date.
- \sa date(), setTime(), setTimeSpec()
+ If no time is set yet, it is set to midnight. If \a date is invalid, this
+ QDateTime becomes invalid.
+
+ If \a date and time() describe a moment close to a transition for this
+ datetime's time representation, \a resolve controls how that situation is
+ resolved.
+
+ \include qdatetime.cpp pre-resolve-note
+
+ \sa date(), setTime(), setTimeZone()
*/
-void QDateTime::setDate(QDate date)
+void QDateTime::setDate(QDate date, TransitionResolution resolve)
{
setDateTime(d, date, time());
- checkValidDateTime(d);
+ checkValidDateTime(d, resolve);
}
/*!
@@ -3654,18 +4331,27 @@ void QDateTime::setDate(QDate date)
dt.setTime(QTime());
\endcode
- \sa time(), setDate(), setTimeSpec()
+ If date() and \a time describe a moment close to a transition for this
+ datetime's time representation, \a resolve controls how that situation is
+ resolved.
+
+ \include qdatetime.cpp pre-resolve-note
+
+ \sa time(), setDate(), setTimeZone()
*/
-void QDateTime::setTime(QTime time)
+void QDateTime::setTime(QTime time, TransitionResolution resolve)
{
setDateTime(d, date(), time);
- checkValidDateTime(d);
+ checkValidDateTime(d, resolve);
}
+#if QT_DEPRECATED_SINCE(6, 9)
/*!
+ \deprecated [6.9] Use setTimeZone() instead
+
Sets the time specification used in this datetime to \a spec.
- The datetime will refer to a different point in time.
+ The datetime may refer to a different point in time.
If \a spec is Qt::OffsetFromUTC then the timeSpec() will be set
to Qt::UTC, i.e. an effective offset of 0.
@@ -3676,23 +4362,21 @@ void QDateTime::setTime(QTime time)
Example:
\snippet code/src_corelib_time_qdatetime.cpp 19
- \sa timeSpec(), setDate(), setTime(), setTimeZone(), Qt::TimeSpec
+ \sa setTimeZone(), timeSpec(), toTimeSpec(), setDate(), setTime()
*/
void QDateTime::setTimeSpec(Qt::TimeSpec spec)
{
- QT_PREPEND_NAMESPACE(setTimeSpec(d, spec, 0));
- if (spec == Qt::OffsetFromUTC || spec == Qt::UTC)
- refreshSimpleDateTime(d);
- else
- refreshZonedDateTime(d, Qt::LocalTime);
+ reviseTimeZone(d, asTimeZone(spec, 0, "QDateTime::setTimeSpec"),
+ TransitionResolution::LegacyBehavior);
}
/*!
\since 5.2
+ \deprecated [6.9] Use setTimeZone(QTimeZone::fromSecondsAheadOfUtc(offsetSeconds)) instead
Sets the timeSpec() to Qt::OffsetFromUTC and the offset to \a offsetSeconds.
- The datetime will refer to a different point in time.
+ The datetime may refer to a different point in time.
The maximum and minimum offset is 14 positive or negative hours. If
\a offsetSeconds is larger or smaller than that, then the result is
@@ -3700,42 +4384,46 @@ void QDateTime::setTimeSpec(Qt::TimeSpec spec)
If \a offsetSeconds is 0 then the timeSpec() will be set to Qt::UTC.
- \sa isValid(), offsetFromUtc()
+ \sa setTimeZone(), isValid(), offsetFromUtc(), toOffsetFromUtc()
*/
void QDateTime::setOffsetFromUtc(int offsetSeconds)
{
- QT_PREPEND_NAMESPACE(setTimeSpec(d, Qt::OffsetFromUTC, offsetSeconds));
- refreshSimpleDateTime(d);
+ reviseTimeZone(d, QTimeZone::fromSecondsAheadOfUtc(offsetSeconds),
+ TransitionResolution::Reject);
}
+#endif // 6.9 deprecations
-#if QT_CONFIG(timezone)
/*!
\since 5.2
Sets the time zone used in this datetime to \a toZone.
- The datetime will refer to a different point in time.
- If \a toZone is invalid then the datetime will be invalid.
+ The datetime may refer to a different point in time. It uses the time
+ representation of \a toZone, which may change the meaning of its unchanged
+ date() and time().
+
+ If \a toZone is invalid then the datetime will be invalid. Otherwise, this
+ datetime's timeSpec() after the call will match \c{toZone.timeSpec()}.
+
+ If date() and time() describe a moment close to a transition for \a toZone,
+ \a resolve controls how that situation is resolved.
+
+ \include qdatetime.cpp pre-resolve-note
- \sa timeZone(), Qt::TimeSpec
+ \sa timeRepresentation(), timeZone(), Qt::TimeSpec
*/
-void QDateTime::setTimeZone(const QTimeZone &toZone)
+void QDateTime::setTimeZone(const QTimeZone &toZone, TransitionResolution resolve)
{
- d.detach(); // always detach
- d->m_status = mergeSpec(d->m_status, Qt::TimeZone);
- d->m_offsetFromUtc = 0;
- d->m_timeZone = toZone;
- refreshZonedDateTime(d, Qt::TimeZone);
+ reviseTimeZone(d, toZone, resolve);
}
-#endif // timezone
/*!
\since 4.7
- Returns the datetime as the number of milliseconds that have passed
- since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
+ Returns the datetime as a number of milliseconds after the start, in UTC, of
+ the year 1970.
On systems that do not support time zones, this function will
behave as if local time were Qt::UTC.
@@ -3744,45 +4432,54 @@ void QDateTime::setTimeZone(const QTimeZone &toZone)
this object is not valid. However, for all valid dates, this function
returns a unique value.
- \sa toSecsSinceEpoch(), setMSecsSinceEpoch()
+ \sa toSecsSinceEpoch(), setMSecsSinceEpoch(), fromMSecsSinceEpoch()
*/
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)) {
+ // not what was asked for). Other things may be doing similar. But that's
+ // only relevant when we got enough data for resolution to find it invalid.
+ const auto status = getStatus(d);
+ if (!status.testFlags(QDateTimePrivate::ValidDate | QDateTimePrivate::ValidTime))
+ return 0;
+
+ switch (extractSpec(status)) {
case Qt::UTC:
return getMSecs(d);
case Qt::OffsetFromUTC:
- return d->m_msecs - (d->m_offsetFromUtc * 1000);
+ Q_ASSERT(!d.isShort());
+ return d->m_msecs - d->m_offsetFromUtc * MSECS_PER_SEC;
- case Qt::LocalTime: {
- // recalculate the local timezone
- auto status = extractDaylightStatus(getStatus(d));
- return localMSecsToEpochMSecs(getMSecs(d), &status);
- }
+ case Qt::LocalTime:
+ if (status.testFlag(QDateTimePrivate::ShortData)) {
+ // Short form has nowhere to cache the offset, so recompute.
+ const auto resolve = toTransitionOptions(extractDaylightStatus(getStatus(d)));
+ const auto state = QDateTimePrivate::localStateAtMillis(getMSecs(d), resolve);
+ return state.when - state.offset * MSECS_PER_SEC;
+ }
+ // Use the offset saved by refreshZonedDateTime() on creation.
+ return d->m_msecs - d->m_offsetFromUtc * MSECS_PER_SEC;
case Qt::TimeZone:
+ Q_ASSERT(!d.isShort());
#if QT_CONFIG(timezone)
- if (d->m_timeZone.isValid()) {
- return QDateTimePrivate::zoneMSecsToEpochMSecs(d->m_msecs, d->m_timeZone,
- extractDaylightStatus(getStatus(d)));
- }
+ // Use offset refreshZonedDateTime() saved on creation:
+ if (d->m_timeZone.isValid())
+ return d->m_msecs - d->m_offsetFromUtc * MSECS_PER_SEC;
#endif
return 0;
}
- Q_UNREACHABLE();
- return 0;
+ Q_UNREACHABLE_RETURN(0);
}
/*!
\since 5.8
- Returns the datetime as the number of seconds that have passed since
- 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
+ Returns the datetime as a number of seconds after the start, in UTC, of the
+ year 1970.
On systems that do not support time zones, this function will
behave as if local time were Qt::UTC.
@@ -3791,112 +4488,97 @@ qint64 QDateTime::toMSecsSinceEpoch() const
this object is not valid. However, for all valid dates, this function
returns a unique value.
- \sa toMSecsSinceEpoch(), setSecsSinceEpoch()
+ \sa toMSecsSinceEpoch(), fromSecsSinceEpoch(), setSecsSinceEpoch()
*/
qint64 QDateTime::toSecsSinceEpoch() const
{
- return toMSecsSinceEpoch() / 1000;
+ return toMSecsSinceEpoch() / MSECS_PER_SEC;
}
/*!
\since 4.7
- Sets the date and time given the number of milliseconds \a msecs that have
- passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
- (Qt::UTC). On systems that do not support time zones this function
- will behave as if local time were Qt::UTC.
+ Sets the datetime to represent a moment a given number, \a msecs, of
+ milliseconds after the start, in UTC, of the year 1970.
+
+ On systems that do not support time zones, this function will
+ behave as if local time were Qt::UTC.
Note that passing the minimum of \c qint64
(\c{std::numeric_limits<qint64>::min()}) to \a msecs will result in
undefined behavior.
- \sa toMSecsSinceEpoch(), setSecsSinceEpoch()
+ \sa setSecsSinceEpoch(), toMSecsSinceEpoch(), fromMSecsSinceEpoch()
*/
void QDateTime::setMSecsSinceEpoch(qint64 msecs)
{
- const auto spec = getSpec(d);
auto status = getStatus(d);
+ const auto spec = extractSpec(status);
+ Q_ASSERT(specCanBeSmall(spec) || !d.isShort());
+ QDateTimePrivate::ZoneState state(msecs);
status &= ~QDateTimePrivate::ValidityMask;
- switch (spec) {
- case Qt::UTC:
- status = status
- | QDateTimePrivate::ValidDate
- | QDateTimePrivate::ValidTime
- | QDateTimePrivate::ValidDateTime;
- break;
- case Qt::OffsetFromUTC:
- msecs = msecs + (d->m_offsetFromUtc * 1000);
- status = status
- | QDateTimePrivate::ValidDate
- | QDateTimePrivate::ValidTime
- | QDateTimePrivate::ValidDateTime;
- break;
- case Qt::TimeZone:
- Q_ASSERT(!d.isShort());
+ if (QTimeZone::isUtcOrFixedOffset(spec)) {
+ if (spec == Qt::OffsetFromUTC)
+ state.offset = d->m_offsetFromUtc;
+ if (!state.offset || !qAddOverflow(msecs, state.offset * MSECS_PER_SEC, &state.when))
+ status |= QDateTimePrivate::ValidityMask;
+ } else if (spec == Qt::LocalTime) {
+ state = QDateTimePrivate::expressUtcAsLocal(msecs);
+ if (state.valid)
+ status = mergeDaylightStatus(status | QDateTimePrivate::ValidityMask, state.dst);
#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.
- if (msecs >= 0) {
- status = mergeDaylightStatus(status,
- d->m_timeZone.d->isDaylightTime(msecs)
- ? QDateTimePrivate::DaylightTime
- : QDateTimePrivate::StandardTime);
- d->m_offsetFromUtc = d->m_timeZone.d->offsetFromUtc(msecs);
- } else {
- status = mergeDaylightStatus(status, QDateTimePrivate::StandardTime);
- d->m_offsetFromUtc = d->m_timeZone.d->standardTimeOffset(msecs);
- }
- msecs = msecs + (d->m_offsetFromUtc * 1000);
- status = status
- | QDateTimePrivate::ValidDate
- | QDateTimePrivate::ValidTime
- | QDateTimePrivate::ValidDateTime;
+ } else if (spec == Qt::TimeZone && (d.detach(), d->m_timeZone.isValid())) {
+ const auto data = d->m_timeZone.d->data(msecs);
+ if (Q_LIKELY(data.offsetFromUtc != QTimeZonePrivate::invalidSeconds())) {
+ state.offset = data.offsetFromUtc;
+ Q_ASSERT(state.offset >= -SECS_PER_DAY && state.offset <= SECS_PER_DAY);
+ if (!state.offset
+ || !Q_UNLIKELY(qAddOverflow(msecs, state.offset * MSECS_PER_SEC, &state.when))) {
+ d->m_status = mergeDaylightStatus(status | QDateTimePrivate::ValidityMask,
+ data.daylightTimeOffset
+ ? QDateTimePrivate::DaylightTime
+ : QDateTimePrivate::StandardTime);
+ d->m_msecs = state.when;
+ d->m_offsetFromUtc = state.offset;
+ return;
+ } // else: zone can't represent this UTC time
+ } // else: zone unable to represent given UTC time (should only happen on overflow).
#endif // timezone
- break;
- case Qt::LocalTime: {
- QDate dt;
- QTime tm;
- QDateTimePrivate::DaylightStatus dstStatus;
- epochMSecsToLocalTime(msecs, &dt, &tm, &dstStatus);
- setDateTime(d, dt, tm);
- refreshZonedDateTime(d, spec); // FIXME: we do this again, below
- msecs = getMSecs(d);
- status = mergeDaylightStatus(getStatus(d), dstStatus);
- break;
- }
}
+ Q_ASSERT(!status.testFlag(QDateTimePrivate::ValidDateTime)
+ || (state.offset >= -SECS_PER_DAY && state.offset <= SECS_PER_DAY));
- if (msecsCanBeSmall(msecs) && d.isShort()) {
+ if (msecsCanBeSmall(state.when) && d.isShort()) {
// we can keep short
- d.data.msecs = qintptr(msecs);
- d.data.status = status;
+ d.data.msecs = qintptr(state.when);
+ d.data.status = status.toInt();
} else {
d.detach();
d->m_status = status & ~QDateTimePrivate::ShortData;
- d->m_msecs = msecs;
+ d->m_msecs = state.when;
+ d->m_offsetFromUtc = state.offset;
}
-
- if (spec == Qt::LocalTime || spec == Qt::TimeZone)
- refreshZonedDateTime(d, spec);
}
/*!
\since 5.8
- Sets the date and time given the number of seconds \a secs that have
- passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
- (Qt::UTC). On systems that do not support time zones this function
- will behave as if local time were Qt::UTC.
+ Sets the datetime to represent a moment a given number, \a secs, of seconds
+ after the start, in UTC, of the year 1970.
- \sa toSecsSinceEpoch(), setMSecsSinceEpoch()
+ On systems that do not support time zones, this function will
+ behave as if local time were Qt::UTC.
+
+ \sa setMSecsSinceEpoch(), toSecsSinceEpoch(), fromSecsSinceEpoch()
*/
void QDateTime::setSecsSinceEpoch(qint64 secs)
{
- setMSecsSinceEpoch(secs * 1000);
+ qint64 msecs;
+ if (!qMulOverflow(secs, std::integral_constant<qint64, MSECS_PER_SEC>(), &msecs))
+ setMSecsSinceEpoch(msecs);
+ else
+ d.invalidate();
}
#if QT_CONFIG(datestring) // depends on, so implies, textdate
@@ -3910,15 +4592,14 @@ void QDateTime::setSecsSinceEpoch(qint64 secs)
formatting is "Wed May 20 03:40:13 1998". For localized formatting, see
\l{QLocale::toString()}.
- If the \a format is Qt::ISODate, the string format corresponds
- to the ISO 8601 extended specification for representations of
- dates and times, taking the form yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm],
- depending on the timeSpec() of the QDateTime. If the timeSpec()
- is Qt::UTC, Z will be appended to the string; if the timeSpec() is
- Qt::OffsetFromUTC, the offset in hours and minutes from UTC will
- be appended to the string. To include milliseconds in the ISO 8601
+ If the \a format is Qt::ISODate, the string format corresponds to the ISO
+ 8601 extended specification for representations of dates and times, taking
+ the form yyyy-MM-ddTHH:mm:ss[Z|±HH:mm], depending on the timeSpec() of the
+ QDateTime. If the timeSpec() is Qt::UTC, Z will be appended to the string;
+ if the timeSpec() is Qt::OffsetFromUTC, the offset in hours and minutes from
+ UTC will be appended to the string. To include milliseconds in the ISO 8601
date, use the \a format Qt::ISODateWithMs, which corresponds to
- yyyy-MM-ddTHH:mm:ss.zzz[Z|[+|-]HH:mm].
+ yyyy-MM-ddTHH:mm:ss.zzz[Z|±HH:mm].
If the \a format is Qt::RFC2822Date, the string is formatted
following \l{RFC 2822}.
@@ -3944,22 +4625,27 @@ QString QDateTime::toString(Qt::DateFormat format) const
return buf;
default:
case Qt::TextDate: {
- const QPair<QDate, QTime> p = getDateTime(d);
+ const std::pair<QDate, QTime> p = getDateTime(d);
buf = toStringTextDate(p.first);
// Insert time between date's day and year:
- buf.insert(buf.lastIndexOf(QLatin1Char(' ')),
- QLatin1Char(' ') + p.second.toString(Qt::TextDate));
+ buf.insert(buf.lastIndexOf(u' '),
+ u' ' + p.second.toString(Qt::TextDate));
// Append zone/offset indicator, as appropriate:
switch (timeSpec()) {
case Qt::LocalTime:
break;
#if QT_CONFIG(timezone)
case Qt::TimeZone:
- buf += QLatin1Char(' ') + d->m_timeZone.abbreviation(*this);
+ buf += u' ' + d->m_timeZone.displayName(
+ *this, QTimeZone::OffsetName, QLocale::c());
break;
#endif
default:
- buf += QLatin1String(" GMT");
+#if 0 // ### Qt 7 GMT: use UTC instead, see qnamespace.qdoc documentation
+ buf += " UTC"_L1;
+#else
+ buf += " GMT"_L1;
+#endif
if (getSpec(d) == Qt::OffsetFromUTC)
buf += toOffsetString(Qt::TextDate, offsetFromUtc());
}
@@ -3967,19 +4653,17 @@ QString QDateTime::toString(Qt::DateFormat format) const
}
case Qt::ISODate:
case Qt::ISODateWithMs: {
- const QPair<QDate, QTime> p = getDateTime(d);
+ const std::pair<QDate, QTime> p = getDateTime(d);
buf = toStringIsoDate(p.first);
if (buf.isEmpty())
return QString(); // failed to convert
- buf += QLatin1Char('T') + p.second.toString(format);
+ buf += u'T' + p.second.toString(format);
switch (getSpec(d)) {
case Qt::UTC:
- buf += QLatin1Char('Z');
+ buf += u'Z';
break;
case Qt::OffsetFromUTC:
-#if QT_CONFIG(timezone)
case Qt::TimeZone:
-#endif
buf += toOffsetString(Qt::ISODate, offsetFromUtc());
break;
default:
@@ -3993,12 +4677,14 @@ QString QDateTime::toString(Qt::DateFormat format) const
/*!
\fn QString QDateTime::toString(const QString &format, QCalendar cal) const
\fn QString QDateTime::toString(QStringView format, QCalendar cal) const
+ \since 5.14
Returns the datetime as a string. The \a format parameter determines the
- format of the result string. If \a cal is supplied, it determines the calendar
- used to represent the date; it defaults to Gregorian. See QTime::toString()
- and QDate::toString() for the supported specifiers for time and date,
- respectively.
+ format of the result string. If \a cal is supplied, it determines the
+ calendar used to represent the date; it defaults to Gregorian. Prior to Qt
+ 5.14, there was no \a cal parameter and the Gregorian calendar was always
+ used. See QTime::toString() and QDate::toString() for the supported
+ specifiers for time and date, respectively, in the \a format parameter.
Any sequence of characters enclosed in single quotes will be included
verbatim in the output string (stripped of the quotes), even if it contains
@@ -4025,8 +4711,9 @@ QString QDateTime::toString(Qt::DateFormat format) const
If the datetime is invalid, an empty string will be returned.
- \note If localized month and day names are desired, please switch to using
- QLocale::system().toString() as QDateTime methods use English (C locale) names.
+ \note Day and month names as well as AM/PM indicators are given in English
+ (C locale). To get localized month and day names and localized forms of
+ AM/PM, use QLocale::system().toDateTime().
\sa fromString(), QDate::toString(), QTime::toString(), QLocale::toString()
*/
@@ -4035,42 +4722,59 @@ QString QDateTime::toString(QStringView format, QCalendar cal) const
return QLocale::c().toString(*this, format, cal);
}
-# if QT_STRINGVIEW_LEVEL < 2
-QString QDateTime::toString(const QString &format, QCalendar cal) const
+// Out-of-line no-calendar overloads, since QCalendar is a non-trivial type
+/*!
+ \overload
+ \since 5.10
+*/
+QString QDateTime::toString(QStringView format) const
+{
+ return QLocale::c().toString(*this, format, QCalendar());
+}
+
+/*!
+ \overload
+ \since 4.6
+*/
+QString QDateTime::toString(const QString &format) const
{
- return toString(qToStringViewIgnoringNull(format), cal);
+ return QLocale::c().toString(*this, qToStringViewIgnoringNull(format), QCalendar());
}
-# endif
#endif // datestring
-static inline void massageAdjustedDateTime(QDateTimeData &d, QDate date, QTime time)
-{
- /*
- If we have just adjusted to a day with a DST transition, our given time
- may lie in the transition hour (either missing or duplicated). For any
- other time, telling mktime (deep in the bowels of localMSecsToEpochMSecs)
- we don't know its DST-ness will produce no adjustment (just a decision as
- to its DST-ness); but for a time in spring's missing hour it'll adjust the
- time while picking a DST-ness. (Handling of autumn is trickier, as either
- DST-ness is valid, without adjusting the time. We might want to propagate
- the daylight status in that case, but it's hard to do so without breaking
- (far more common) other cases; and it makes little difference, as the two
- answers do then differ only in DST-ness.)
- */
- auto spec = getSpec(d);
- if (spec == Qt::LocalTime) {
- QDateTimePrivate::DaylightStatus status = QDateTimePrivate::UnknownDaylightTime;
- localMSecsToEpochMSecs(timeToMSecs(date, time), &status, &date, &time);
-#if QT_CONFIG(timezone)
- } else if (spec == Qt::TimeZone && d->m_timeZone.isValid()) {
- QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(date, time),
- d->m_timeZone,
- QDateTimePrivate::UnknownDaylightTime,
- &date, &time);
-#endif // timezone
+static inline void massageAdjustedDateTime(QDateTimeData &d, QDate date, QTime time, bool forward)
+{
+ const QDateTimePrivate::TransitionOptions resolve = toTransitionOptions(
+ forward ? QDateTime::TransitionResolution::RelativeToBefore
+ : QDateTime::TransitionResolution::RelativeToAfter);
+ auto status = getStatus(d);
+ Q_ASSERT(status.testFlags(QDateTimePrivate::ValidDate | QDateTimePrivate::ValidTime
+ | QDateTimePrivate::ValidDateTime));
+ auto spec = extractSpec(status);
+ if (QTimeZone::isUtcOrFixedOffset(spec)) {
+ setDateTime(d, date, time);
+ refreshSimpleDateTime(d);
+ return;
+ }
+ qint64 local = timeToMSecs(date, time);
+ const QDateTimePrivate::ZoneState state = stateAtMillis(d.timeZone(), local, resolve);
+ Q_ASSERT(state.valid || state.dst == QDateTimePrivate::UnknownDaylightTime);
+ if (state.dst == QDateTimePrivate::UnknownDaylightTime)
+ status.setFlag(QDateTimePrivate::ValidDateTime, false);
+ else
+ status = mergeDaylightStatus(status | QDateTimePrivate::ValidDateTime, state.dst);
+
+ if (status & QDateTimePrivate::ShortData) {
+ d.data.msecs = state.when;
+ d.data.status = status.toInt();
+ } else {
+ d.detach();
+ d->m_status = status;
+ if (state.valid) {
+ d->m_msecs = state.when;
+ d->m_offsetFromUtc = state.offset;
+ }
}
- setDateTime(d, date, time);
- checkValidDateTime(d);
}
/*!
@@ -4078,20 +4782,24 @@ static inline void massageAdjustedDateTime(QDateTimeData &d, QDate date, QTime t
later than the datetime of this object (or earlier if \a ndays is
negative).
- If the timeSpec() is Qt::LocalTime and the resulting
- date and time fall in the Standard Time to Daylight-Saving Time transition
- hour then the result will be adjusted accordingly, i.e. if the transition
- is at 2am and the clock goes forward to 3am and the result falls between
- 2am and 3am then the result will be adjusted to fall after 3am.
+ If the timeSpec() is Qt::LocalTime or Qt::TimeZone and the resulting date
+ and time fall in the Standard Time to Daylight-Saving Time transition hour
+ then the result will be just beyond this gap, in the direction of change.
+ If the transition is at 2am and the clock goes forward to 3am, the result of
+ aiming between 2am and 3am will be adjusted to fall before 2am (if \c{ndays
+ < 0}) or after 3am (otherwise).
- \sa daysTo(), addMonths(), addYears(), addSecs()
+ \sa daysTo(), addMonths(), addYears(), addSecs(), {Timezone transitions}
*/
QDateTime QDateTime::addDays(qint64 ndays) const
{
+ if (isNull())
+ return QDateTime();
+
QDateTime dt(*this);
- QPair<QDate, QTime> p = getDateTime(d);
- massageAdjustedDateTime(dt.d, p.first.addDays(ndays), p.second);
+ std::pair<QDate, QTime> p = getDateTime(d);
+ massageAdjustedDateTime(dt.d, p.first.addDays(ndays), p.second, ndays >= 0);
return dt;
}
@@ -4100,20 +4808,24 @@ QDateTime QDateTime::addDays(qint64 ndays) const
later than the datetime of this object (or earlier if \a nmonths
is negative).
- If the timeSpec() is Qt::LocalTime and the resulting
- date and time fall in the Standard Time to Daylight-Saving Time transition
- hour then the result will be adjusted accordingly, i.e. if the transition
- is at 2am and the clock goes forward to 3am and the result falls between
- 2am and 3am then the result will be adjusted to fall after 3am.
+ If the timeSpec() is Qt::LocalTime or Qt::TimeZone and the resulting date
+ and time fall in the Standard Time to Daylight-Saving Time transition hour
+ then the result will be just beyond this gap, in the direction of change.
+ If the transition is at 2am and the clock goes forward to 3am, the result of
+ aiming between 2am and 3am will be adjusted to fall before 2am (if
+ \c{nmonths < 0}) or after 3am (otherwise).
- \sa daysTo(), addDays(), addYears(), addSecs()
+ \sa daysTo(), addDays(), addYears(), addSecs(), {Timezone transitions}
*/
QDateTime QDateTime::addMonths(int nmonths) const
{
+ if (isNull())
+ return QDateTime();
+
QDateTime dt(*this);
- QPair<QDate, QTime> p = getDateTime(d);
- massageAdjustedDateTime(dt.d, p.first.addMonths(nmonths), p.second);
+ std::pair<QDate, QTime> p = getDateTime(d);
+ massageAdjustedDateTime(dt.d, p.first.addMonths(nmonths), p.second, nmonths >= 0);
return dt;
}
@@ -4122,20 +4834,24 @@ QDateTime QDateTime::addMonths(int nmonths) const
later than the datetime of this object (or earlier if \a nyears is
negative).
- If the timeSpec() is Qt::LocalTime and the resulting
- date and time fall in the Standard Time to Daylight-Saving Time transition
- hour then the result will be adjusted accordingly, i.e. if the transition
- is at 2am and the clock goes forward to 3am and the result falls between
- 2am and 3am then the result will be adjusted to fall after 3am.
+ If the timeSpec() is Qt::LocalTime or Qt::TimeZone and the resulting date
+ and time fall in the Standard Time to Daylight-Saving Time transition hour
+ then the result will be just beyond this gap, in the direction of change.
+ If the transition is at 2am and the clock goes forward to 3am, the result of
+ aiming between 2am and 3am will be adjusted to fall before 2am (if \c{nyears
+ < 0}) or after 3am (otherwise).
- \sa daysTo(), addDays(), addMonths(), addSecs()
+ \sa daysTo(), addDays(), addMonths(), addSecs(), {Timezone transitions}
*/
QDateTime QDateTime::addYears(int nyears) const
{
+ if (isNull())
+ return QDateTime();
+
QDateTime dt(*this);
- QPair<QDate, QTime> p = getDateTime(d);
- massageAdjustedDateTime(dt.d, p.first.addYears(nyears), p.second);
+ std::pair<QDate, QTime> p = getDateTime(d);
+ massageAdjustedDateTime(dt.d, p.first.addYears(nyears), p.second, nyears >= 0);
return dt;
}
@@ -4151,11 +4867,14 @@ QDateTime QDateTime::addYears(int nyears) const
QDateTime QDateTime::addSecs(qint64 s) const
{
- return addMSecs(s * 1000);
+ qint64 msecs;
+ if (qMulOverflow(s, std::integral_constant<qint64, MSECS_PER_SEC>(), &msecs))
+ return QDateTime();
+ return addMSecs(msecs);
}
/*!
- Returns a QDateTime object containing a datetime \a msecs miliseconds
+ Returns a QDateTime object containing a datetime \a msecs milliseconds
later than the datetime of this object (or earlier if \a msecs is
negative).
@@ -4169,30 +4888,52 @@ QDateTime QDateTime::addMSecs(qint64 msecs) const
return QDateTime();
QDateTime dt(*this);
- auto spec = getSpec(d);
- if (spec == Qt::LocalTime || spec == Qt::TimeZone) {
- // Convert to real UTC first in case crosses DST transition
- dt.setMSecsSinceEpoch(toMSecsSinceEpoch() + msecs);
- } else {
+ switch (getSpec(d)) {
+ case Qt::LocalTime:
+ case Qt::TimeZone:
+ // Convert to real UTC first in case this crosses a DST transition:
+ if (!qAddOverflow(toMSecsSinceEpoch(), msecs, &msecs))
+ dt.setMSecsSinceEpoch(msecs);
+ else
+ dt.d.invalidate();
+ break;
+ case Qt::UTC:
+ case Qt::OffsetFromUTC:
// No need to convert, just add on
- if (d.isShort()) {
- // need to check if we need to enlarge first
- msecs += dt.d.data.msecs;
- if (msecsCanBeSmall(msecs)) {
- dt.d.data.msecs = qintptr(msecs);
- } else {
- dt.d.detach();
- dt.d->m_msecs = msecs;
- }
+ if (qAddOverflow(getMSecs(d), msecs, &msecs)) {
+ dt.d.invalidate();
+ } else if (d.isShort() && msecsCanBeSmall(msecs)) {
+ dt.d.data.msecs = qintptr(msecs);
} else {
dt.d.detach();
- dt.d->m_msecs += msecs;
+ dt.d->m_msecs = msecs;
}
+ break;
}
return dt;
}
/*!
+ \fn QDateTime QDateTime::addDuration(std::chrono::milliseconds msecs) const
+
+ \since 6.4
+
+ Returns a QDateTime object containing a datetime \a msecs milliseconds
+ later than the datetime of this object (or earlier if \a msecs is
+ negative).
+
+ If this datetime is invalid, an invalid datetime will be returned.
+
+ \note Adding durations expressed in \c{std::chrono::months} or
+ \c{std::chrono::years} does not yield the same result obtained by using
+ addMonths() or addYears(). The former are fixed durations, calculated in
+ relation to the solar year; the latter use the Gregorian calendar definitions
+ of months/years.
+
+ \sa addMSecs(), msecsTo(), addDays(), addMonths(), addYears()
+*/
+
+/*!
Returns the number of days from this datetime to the \a other
datetime. The number of days is counted as the number of times
midnight is reached between this datetime to the \a other
@@ -4232,7 +4973,7 @@ qint64 QDateTime::daysTo(const QDateTime &other) const
qint64 QDateTime::secsTo(const QDateTime &other) const
{
- return (msecsTo(other) / 1000);
+ return msecsTo(other) / MSECS_PER_SEC;
}
/*!
@@ -4258,75 +4999,172 @@ qint64 QDateTime::msecsTo(const QDateTime &other) const
}
/*!
- Returns a copy of this datetime converted to the given time
- \a spec.
+ \fn std::chrono::milliseconds QDateTime::operator-(const QDateTime &lhs, const QDateTime &rhs)
+ \since 6.4
+
+ Returns the number of milliseconds between \a lhs and \a rhs.
+ If \a lhs is earlier than \a rhs, the result will be negative.
+
+ Returns 0 if either datetime is invalid.
+
+ \sa msecsTo()
+*/
+
+/*!
+ \fn QDateTime QDateTime::operator+(const QDateTime &dateTime, std::chrono::milliseconds duration)
+ \fn QDateTime QDateTime::operator+(std::chrono::milliseconds duration, const QDateTime &dateTime)
+
+ \since 6.4
+
+ Returns a QDateTime object containing a datetime \a duration milliseconds
+ later than \a dateTime (or earlier if \a duration is negative).
+
+ If \a dateTime is invalid, an invalid datetime will be returned.
+
+ \sa addMSecs()
+*/
+
+/*!
+ \fn QDateTime &QDateTime::operator+=(std::chrono::milliseconds duration)
+ \since 6.4
+
+ Modifies this datetime object by adding the given \a duration.
+ The updated object will be later if \a duration is positive,
+ or earlier if it is negative.
+
+ If this datetime is invalid, this function has no effect.
+
+ Returns a reference to this datetime object.
+
+ \sa addMSecs()
+*/
+
+/*!
+ \fn QDateTime QDateTime::operator-(const QDateTime &dateTime, std::chrono::milliseconds duration)
+
+ \since 6.4
+
+ Returns a QDateTime object containing a datetime \a duration milliseconds
+ earlier than \a dateTime (or later if \a duration is negative).
+
+ If \a dateTime is invalid, an invalid datetime will be returned.
+
+ \sa addMSecs()
+*/
+
+/*!
+ \fn QDateTime &QDateTime::operator-=(std::chrono::milliseconds duration)
+ \since 6.4
+
+ Modifies this datetime object by subtracting the given \a duration.
+ The updated object will be earlier if \a duration is positive,
+ or later if it is negative.
+
+ If this datetime is invalid, this function has no effect.
+
+ Returns a reference to this datetime object.
+
+ \sa addMSecs
+*/
+
+#if QT_DEPRECATED_SINCE(6, 9)
+/*!
+ \deprecated [6.9] Use \l toTimeZone() instead.
+
+ Returns a copy of this datetime converted to the given time \a spec.
- If \a spec is Qt::OffsetFromUTC then it is set to Qt::UTC. To set to a
- spec of Qt::OffsetFromUTC use toOffsetFromUtc().
+ The result represents the same moment in time as, and is equal to, this datetime.
- If \a spec is Qt::TimeZone then it is set to Qt::LocalTime,
- i.e. the local Time Zone.
+ If \a spec is Qt::OffsetFromUTC then it is set to Qt::UTC. To set to a fixed
+ offset from UTC, use toTimeZone() or toOffsetFromUtc().
+
+ If \a spec is Qt::TimeZone then it is set to Qt::LocalTime, i.e. the local
+ Time Zone. To set a specified time-zone, use toTimeZone().
Example:
\snippet code/src_corelib_time_qdatetime.cpp 16
- \sa timeSpec(), toTimeZone(), toOffsetFromUtc()
+ \sa setTimeSpec(), timeSpec(), toTimeZone()
*/
QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const
{
- if (getSpec(d) == spec && (spec == Qt::UTC || spec == Qt::LocalTime))
- return *this;
-
- if (!isValid()) {
- QDateTime ret = *this;
- ret.setTimeSpec(spec);
- return ret;
- }
-
- return fromMSecsSinceEpoch(toMSecsSinceEpoch(), spec, 0);
+ return toTimeZone(asTimeZone(spec, 0, "toTimeSpec"));
}
+#endif // 6.9 deprecation
/*!
\since 5.2
- \fn QDateTime QDateTime::toOffsetFromUtc(int offsetSeconds) const
-
Returns a copy of this datetime converted to a spec of Qt::OffsetFromUTC
- with the given \a offsetSeconds.
+ with the given \a offsetSeconds. Equivalent to
+ \c{toTimeZone(QTimeZone::fromSecondsAheadOfUtc(offsetSeconds))}.
+
+ If the \a offsetSeconds equals 0 then a UTC datetime will be returned.
- If the \a offsetSeconds equals 0 then a UTC datetime will be returned
+ The result represents the same moment in time as, and is equal to, this datetime.
- \sa setOffsetFromUtc(), offsetFromUtc(), toTimeSpec()
+ \sa setOffsetFromUtc(), offsetFromUtc(), toTimeZone()
*/
QDateTime QDateTime::toOffsetFromUtc(int offsetSeconds) const
{
- if (getSpec(d) == Qt::OffsetFromUTC
- && d->m_offsetFromUtc == offsetSeconds)
- return *this;
+ return toTimeZone(QTimeZone::fromSecondsAheadOfUtc(offsetSeconds));
+}
- if (!isValid()) {
- QDateTime ret = *this;
- ret.setOffsetFromUtc(offsetSeconds);
- return ret;
- }
+/*!
+ Returns a copy of this datetime converted to local time.
+
+ The result represents the same moment in time as, and is equal to, this datetime.
+
+ Example:
+
+ \snippet code/src_corelib_time_qdatetime.cpp 17
- return fromMSecsSinceEpoch(toMSecsSinceEpoch(), Qt::OffsetFromUTC, offsetSeconds);
+ \sa toTimeZone(), toUTC(), toOffsetFromUtc()
+*/
+QDateTime QDateTime::toLocalTime() const
+{
+ return toTimeZone(QTimeZone::LocalTime);
+}
+
+/*!
+ Returns a copy of this datetime converted to UTC.
+
+ The result represents the same moment in time as, and is equal to, this datetime.
+
+ Example:
+
+ \snippet code/src_corelib_time_qdatetime.cpp 18
+
+ \sa toTimeZone(), toLocalTime(), toOffsetFromUtc()
+*/
+QDateTime QDateTime::toUTC() const
+{
+ return toTimeZone(QTimeZone::UTC);
}
-#if QT_CONFIG(timezone)
/*!
\since 5.2
- Returns a copy of this datetime converted to the given \a timeZone
+ Returns a copy of this datetime converted to the given \a timeZone.
+
+ The result represents the same moment in time as, and is equal to, this datetime.
- \sa timeZone(), toTimeSpec()
+ The result describes the moment in time in terms of \a timeZone's time
+ representation. For example:
+
+ \snippet code/src_corelib_time_qdatetime.cpp 23
+
+ If \a timeZone is invalid then the datetime will be invalid. Otherwise the
+ returned datetime's timeSpec() will match \c{timeZone.timeSpec()}.
+
+ \sa timeRepresentation(), toLocalTime(), toUTC(), toOffsetFromUtc()
*/
QDateTime QDateTime::toTimeZone(const QTimeZone &timeZone) const
{
- if (getSpec(d) == Qt::TimeZone && d->m_timeZone == timeZone)
+ if (timeRepresentation() == timeZone)
return *this;
if (!isValid()) {
@@ -4337,26 +5175,23 @@ QDateTime QDateTime::toTimeZone(const QTimeZone &timeZone) const
return fromMSecsSinceEpoch(toMSecsSinceEpoch(), timeZone);
}
-#endif // timezone
/*!
+ \internal
Returns \c true if this datetime is equal to the \a other datetime;
otherwise returns \c false.
- Since 5.14, all invalid datetimes are equal to one another and differ from
- all other datetimes.
-
- \sa operator!=()
+ \sa precedes(), operator==()
*/
-bool QDateTime::operator==(const QDateTime &other) const
+bool QDateTime::equals(const QDateTime &other) const
{
if (!isValid())
return !other.isValid();
if (!other.isValid())
return false;
- if (getSpec(d) == Qt::LocalTime && getStatus(d) == getStatus(other.d))
+ if (usesSameOffset(d, other.d))
return getMSecs(d) == getMSecs(other.d);
// Convert to UTC and compare
@@ -4364,82 +5199,137 @@ bool QDateTime::operator==(const QDateTime &other) const
}
/*!
- \fn bool QDateTime::operator!=(const QDateTime &other) const
+ \fn bool QDateTime::operator==(const QDateTime &lhs, const QDateTime &rhs)
+
+ Returns \c true if \a lhs represents the same moment in time as \a rhs;
+ otherwise returns \c false.
- Returns \c true if this datetime is different from the \a other
- datetime; otherwise returns \c false.
+//! [datetime-order-details]
+ Two datetimes using different time representations can have different
+ offsets from UTC. In this case, they may compare equivalent even if their \l
+ date() and \l time() differ, if that difference matches the difference in
+ UTC offset. If their \c date() and \c time() coincide, the one with higher
+ offset from UTC is less (earlier) than the one with lower offset. As a
+ result, datetimes are only weakly ordered.
- Two datetimes are different if either the date, the time, or the time zone
- components are different. Since 5.14, any invalid datetime is less than all
- valid datetimes.
+ Since 5.14, all invalid datetimes are equivalent and less than all valid
+ datetimes.
+//! [datetime-order-details]
- \sa operator==()
+ \sa operator!=(), operator<(), operator<=(), operator>(), operator>=()
*/
/*!
- Returns \c true if this datetime is earlier than the \a other
- datetime; otherwise returns \c false.
+ \fn bool QDateTime::operator!=(const QDateTime &lhs, const QDateTime &rhs)
+
+ Returns \c true if \a lhs is different from \a rhs; otherwise returns \c
+ false.
+
+ \include qdatetime.cpp datetime-order-details
+
+ \sa operator==()
*/
-bool QDateTime::operator<(const QDateTime &other) const
+Qt::weak_ordering compareThreeWay(const QDateTime &lhs, const QDateTime &rhs)
{
- if (!isValid())
- return other.isValid();
- if (!other.isValid())
- return false;
+ if (!lhs.isValid())
+ return rhs.isValid() ? Qt::weak_ordering::less : Qt::weak_ordering::equivalent;
- if (getSpec(d) == Qt::LocalTime && getStatus(d) == getStatus(other.d))
- return getMSecs(d) < getMSecs(other.d);
+ if (!rhs.isValid())
+ return Qt::weak_ordering::greater; // we know that lhs is valid here
+
+ if (usesSameOffset(lhs.d, rhs.d))
+ return Qt::compareThreeWay(getMSecs(lhs.d), getMSecs(rhs.d));
// Convert to UTC and compare
- return toMSecsSinceEpoch() < other.toMSecsSinceEpoch();
+ return Qt::compareThreeWay(lhs.toMSecsSinceEpoch(), rhs.toMSecsSinceEpoch());
}
/*!
- \fn bool QDateTime::operator<=(const QDateTime &other) const
+ \fn bool QDateTime::operator<(const QDateTime &lhs, const QDateTime &rhs)
+
+ Returns \c true if \a lhs is earlier than \a rhs;
+ otherwise returns \c false.
+
+ \include qdatetime.cpp datetime-order-details
- Returns \c true if this datetime is earlier than or equal to the
- \a other datetime; otherwise returns \c false.
+ \sa operator==()
*/
/*!
- \fn bool QDateTime::operator>(const QDateTime &other) const
+ \fn bool QDateTime::operator<=(const QDateTime &lhs, const QDateTime &rhs)
- Returns \c true if this datetime is later than the \a other datetime;
- otherwise returns \c false.
+ Returns \c true if \a lhs is earlier than or equal to \a rhs; otherwise
+ returns \c false.
+
+ \include qdatetime.cpp datetime-order-details
+
+ \sa operator==()
+*/
+
+/*!
+ \fn bool QDateTime::operator>(const QDateTime &lhs, const QDateTime &rhs)
+
+ Returns \c true if \a lhs is later than \a rhs; otherwise returns \c false.
+
+ \include qdatetime.cpp datetime-order-details
+
+ \sa operator==()
*/
/*!
- \fn bool QDateTime::operator>=(const QDateTime &other) const
+ \fn bool QDateTime::operator>=(const QDateTime &lhs, const QDateTime &rhs)
+
+ Returns \c true if \a lhs is later than or equal to \a rhs;
+ otherwise returns \c false.
+
+ \include qdatetime.cpp datetime-order-details
- Returns \c true if this datetime is later than or equal to the
- \a other datetime; otherwise returns \c false.
+ \sa operator==()
*/
/*!
- \fn QDateTime QDateTime::currentDateTime()
- Returns the current datetime, as reported by the system clock, in
- the local time zone.
+ \since 6.5
+ \fn QDateTime QDateTime::currentDateTime(const QTimeZone &zone)
+
+ Returns the system clock's current datetime, using the time representation
+ described by \a zone. If \a zone is omitted, local time is used.
\sa currentDateTimeUtc(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
*/
/*!
+ \overload
+ \since 0.90
+*/
+QDateTime QDateTime::currentDateTime()
+{
+ return currentDateTime(QTimeZone::LocalTime);
+}
+
+/*!
\fn QDateTime QDateTime::currentDateTimeUtc()
\since 4.7
- Returns the current datetime, as reported by the system clock, in
- UTC.
+ Returns the system clock's current datetime, expressed in terms of UTC.
+
+ Equivalent to \c{currentDateTime(QTimeZone::UTC)}.
\sa currentDateTime(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
*/
+QDateTime QDateTime::currentDateTimeUtc()
+{
+ return currentDateTime(QTimeZone::UTC);
+}
+
/*!
\fn qint64 QDateTime::currentMSecsSinceEpoch()
\since 4.7
- Returns the number of milliseconds since 1970-01-01T00:00:00 Universal
- Coordinated Time. This number is like the POSIX time_t variable, but
- expressed in milliseconds instead.
+ Returns the current number of milliseconds since the start, in UTC, of the year 1970.
+
+ This number is like the POSIX time_t variable, but expressed in milliseconds
+ instead of seconds.
\sa currentDateTime(), currentDateTimeUtc(), toTimeSpec()
*/
@@ -4448,22 +5338,101 @@ bool QDateTime::operator<(const QDateTime &other) const
\fn qint64 QDateTime::currentSecsSinceEpoch()
\since 5.8
- Returns the number of seconds since 1970-01-01T00:00:00 Universal
- Coordinated Time.
+ Returns the number of seconds since the start, in UTC, of the year 1970.
+
+ This number is like the POSIX time_t variable.
\sa currentMSecsSinceEpoch()
*/
+/*!
+ \fn template <typename Clock, typename Duration> QDateTime QDateTime::fromStdTimePoint(const std::chrono::time_point<Clock, Duration> &time)
+ \since 6.4
+
+ Constructs a datetime representing the same point in time as \a time,
+ using Qt::UTC as its specification.
+
+ The clock of \a time must be compatible with \c{std::chrono::system_clock},
+ and the duration type must be convertible to \c{std::chrono::milliseconds}.
+
+ \note This function requires C++20.
+
+ \sa toStdSysMilliseconds(), fromMSecsSinceEpoch()
+*/
+
+/*!
+ \fn QDateTime QDateTime::fromStdTimePoint(const std::chrono::local_time<std::chrono::milliseconds> &time)
+ \since 6.4
+
+ Constructs a datetime whose date and time are the number of milliseconds
+ represented by \a time, counted since 1970-01-01T00:00:00.000 in local
+ time (Qt::LocalTime).
+
+ \note This function requires C++20.
+
+ \sa toStdSysMilliseconds(), fromMSecsSinceEpoch()
+*/
+
+/*!
+ \fn QDateTime QDateTime::fromStdLocalTime(const std::chrono::local_time<std::chrono::milliseconds> &time)
+ \since 6.4
+
+ Constructs a datetime whose date and time are the number of milliseconds
+ represented by \a time, counted since 1970-01-01T00:00:00.000 in local
+ time (Qt::LocalTime).
+
+ \note This function requires C++20.
+
+ \sa toStdSysMilliseconds(), fromMSecsSinceEpoch()
+*/
+
+/*!
+ \fn QDateTime QDateTime::fromStdZonedTime(const std::chrono::zoned_time<std::chrono::milliseconds, const std::chrono::time_zone *> &time);
+ \since 6.4
+
+ Constructs a datetime representing the same point in time as \a time.
+ The result will be expressed in \a{time}'s time zone.
+
+ \note This function requires C++20.
+
+ \sa QTimeZone
+
+ \sa toStdSysMilliseconds(), fromMSecsSinceEpoch()
+*/
+
+/*!
+ \fn std::chrono::sys_time<std::chrono::milliseconds> QDateTime::toStdSysMilliseconds() const
+ \since 6.4
+
+ Converts this datetime object to the equivalent time point expressed in
+ milliseconds, using \c{std::chrono::system_clock} as a clock.
+
+ \note This function requires C++20.
+
+ \sa fromStdTimePoint(), toMSecsSinceEpoch()
+*/
+
+/*!
+ \fn std::chrono::sys_seconds QDateTime::toStdSysSeconds() const
+ \since 6.4
+
+ Converts this datetime object to the equivalent time point expressed in
+ seconds, using \c{std::chrono::system_clock} as a clock.
+
+ \note This function requires C++20.
+
+ \sa fromStdTimePoint(), toSecsSinceEpoch()
+*/
+
#if defined(Q_OS_WIN)
static inline uint msecsFromDecomposed(int hour, int minute, int sec, int msec = 0)
{
- return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute + 1000 * sec + msec;
+ return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute + MSECS_PER_SEC * sec + msec;
}
QDate QDate::currentDate()
{
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
+ SYSTEMTIME st = {};
GetLocalTime(&st);
return QDate(st.wYear, st.wMonth, st.wDay);
}
@@ -4471,58 +5440,50 @@ QDate QDate::currentDate()
QTime QTime::currentTime()
{
QTime ct;
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
+ SYSTEMTIME st = {};
GetLocalTime(&st);
ct.setHMS(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
return ct;
}
-QDateTime QDateTime::currentDateTime()
-{
- QTime t;
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
- GetLocalTime(&st);
- QDate d(st.wYear, st.wMonth, st.wDay);
- t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
- return QDateTime(d, t);
-}
-
-QDateTime QDateTime::currentDateTimeUtc()
+QDateTime QDateTime::currentDateTime(const QTimeZone &zone)
{
- QTime t;
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
- GetSystemTime(&st);
+ // We can get local time or "system" time (which is UTC); otherwise, we must
+ // convert, which is most efficiently done from UTC.
+ const Qt::TimeSpec spec = zone.timeSpec();
+ SYSTEMTIME st = {};
+ // GetSystemTime()'s page links to its partner page for GetLocalTime().
+ // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime
+ (spec == Qt::LocalTime ? GetLocalTime : GetSystemTime)(&st);
QDate d(st.wYear, st.wMonth, st.wDay);
- t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
- return QDateTime(d, t, Qt::UTC);
+ QTime t(msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds));
+ if (spec == Qt::LocalTime)
+ return QDateTime(d, t);
+ QDateTime utc(d, t, QTimeZone::UTC);
+ return spec == Qt::UTC ? utc : utc.toTimeZone(zone);
}
qint64 QDateTime::currentMSecsSinceEpoch() noexcept
{
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
+ SYSTEMTIME st = {};
GetSystemTime(&st);
const qint64 daysAfterEpoch = QDate(1970, 1, 1).daysTo(QDate(st.wYear, st.wMonth, st.wDay));
return msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds) +
- daysAfterEpoch * Q_INT64_C(86400000);
+ daysAfterEpoch * MSECS_PER_DAY;
}
qint64 QDateTime::currentSecsSinceEpoch() noexcept
{
- SYSTEMTIME st;
- memset(&st, 0, sizeof(SYSTEMTIME));
+ SYSTEMTIME st = {};
GetSystemTime(&st);
const qint64 daysAfterEpoch = QDate(1970, 1, 1).daysTo(QDate(st.wYear, st.wMonth, st.wDay));
return st.wHour * SECS_PER_HOUR + st.wMinute * SECS_PER_MIN + st.wSecond +
- daysAfterEpoch * Q_INT64_C(86400);
+ daysAfterEpoch * SECS_PER_DAY;
}
-#elif defined(Q_OS_UNIX)
+#elif defined(Q_OS_UNIX) // Assume POSIX-compliant
QDate QDate::currentDate()
{
return QDateTime::currentDateTime().date();
@@ -4533,131 +5494,157 @@ QTime QTime::currentTime()
return QDateTime::currentDateTime().time();
}
-QDateTime QDateTime::currentDateTime()
+QDateTime QDateTime::currentDateTime(const QTimeZone &zone)
{
- return fromMSecsSinceEpoch(currentMSecsSinceEpoch(), Qt::LocalTime);
-}
-
-QDateTime QDateTime::currentDateTimeUtc()
-{
- return fromMSecsSinceEpoch(currentMSecsSinceEpoch(), Qt::UTC);
+ return fromMSecsSinceEpoch(currentMSecsSinceEpoch(), zone);
}
qint64 QDateTime::currentMSecsSinceEpoch() noexcept
{
- // posix compliant system
- // we have milliseconds
- struct timeval tv;
- gettimeofday(&tv, nullptr);
- return qint64(tv.tv_sec) * Q_INT64_C(1000) + tv.tv_usec / 1000;
+ struct timespec when;
+ if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed
+ return when.tv_sec * MSECS_PER_SEC + (when.tv_nsec + 500'000) / 1'000'000;
+ Q_UNREACHABLE_RETURN(0);
}
qint64 QDateTime::currentSecsSinceEpoch() noexcept
{
- struct timeval tv;
- gettimeofday(&tv, nullptr);
- return qint64(tv.tv_sec);
+ struct timespec when;
+ if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed
+ return when.tv_sec;
+ Q_UNREACHABLE_RETURN(0);
}
#else
#error "What system is this?"
#endif
+#if QT_DEPRECATED_SINCE(6, 9)
/*!
- Returns a datetime whose date and time are the number of milliseconds \a msecs
- that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
- Time (Qt::UTC) and converted to the given \a spec.
+ \since 5.2
+ \overload
+ \deprecated [6.9] Pass a \l QTimeZone instead, or omit \a spec and \a offsetSeconds.
+
+ Returns a datetime representing a moment the given number \a msecs of
+ milliseconds after the start, in UTC, of the year 1970, described as
+ specified by \a spec and \a offsetSeconds.
- Note that there are possible values for \a msecs that lie outside the valid
- range of QDateTime, both negative and positive. The behavior of this
- function is undefined for those values.
+ Note that there are possible values for \a msecs that lie outside the valid
+ range of QDateTime, both negative and positive. The behavior of this
+ function is undefined for those values.
- If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
- ignored. If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
- then the spec will be set to Qt::UTC, i.e. an offset of 0 seconds.
+ If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
+ ignored. If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
+ then Qt::UTC will be used as the \a spec, since UTC has zero offset.
- If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
- i.e. the current system time zone.
+ If \a spec is Qt::TimeZone then Qt::LocalTime will be used in its place,
+ equivalent to using the current system time zone (but differently
+ represented).
- \sa toMSecsSinceEpoch(), setMSecsSinceEpoch()
+ \sa fromSecsSinceEpoch(), toMSecsSinceEpoch(), setMSecsSinceEpoch()
*/
QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, Qt::TimeSpec spec, int offsetSeconds)
{
- QDateTime dt;
- QT_PREPEND_NAMESPACE(setTimeSpec(dt.d, spec, offsetSeconds));
- dt.setMSecsSinceEpoch(msecs);
- return dt;
+ return fromMSecsSinceEpoch(msecs,
+ asTimeZone(spec, offsetSeconds, "QDateTime::fromMSecsSinceEpoch"));
}
/*!
- \since 5.8
+ \since 5.8
+ \overload
+ \deprecated [6.9] Pass a \l QTimeZone instead, or omit \a spec and \a offsetSeconds.
- Returns a datetime whose date and time are the number of seconds \a secs
- that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
- Time (Qt::UTC) and converted to the given \a spec.
+ Returns a datetime representing a moment the given number \a secs of seconds
+ after the start, in UTC, of the year 1970, described as specified by \a spec
+ and \a offsetSeconds.
- Note that there are possible values for \a secs that lie outside the valid
- range of QDateTime, both negative and positive. The behavior of this
- function is undefined for those values.
+ Note that there are possible values for \a secs that lie outside the valid
+ range of QDateTime, both negative and positive. The behavior of this
+ function is undefined for those values.
- If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
- ignored. If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
- then the spec will be set to Qt::UTC, i.e. an offset of 0 seconds.
+ If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
+ ignored. If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
+ then Qt::UTC will be used as the \a spec, since UTC has zero offset.
- If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
- i.e. the current system time zone.
+ If \a spec is Qt::TimeZone then Qt::LocalTime will be used in its place,
+ equivalent to using the current system time zone (but differently
+ represented).
- \sa toSecsSinceEpoch(), setSecsSinceEpoch()
+ \sa fromMSecsSinceEpoch(), toSecsSinceEpoch(), setSecsSinceEpoch()
*/
QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, Qt::TimeSpec spec, int offsetSeconds)
{
- constexpr qint64 maxSeconds = std::numeric_limits<qint64>::max() / 1000;
- constexpr qint64 minSeconds = std::numeric_limits<qint64>::min() / 1000;
- if (secs > maxSeconds || secs < minSeconds)
- return QDateTime(); // Would {und,ov}erflow
- return fromMSecsSinceEpoch(secs * 1000, spec, offsetSeconds);
+ return fromSecsSinceEpoch(secs,
+ asTimeZone(spec, offsetSeconds, "QDateTime::fromSecsSinceEpoch"));
}
+#endif // 6.9 deprecations
-#if QT_CONFIG(timezone)
/*!
\since 5.2
- Returns a datetime whose date and time are the number of milliseconds \a msecs
- that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
- Time (Qt::UTC) and with the given \a timeZone.
+ Returns a datetime representing a moment the given number \a msecs of
+ milliseconds after the start, in UTC, of the year 1970, described as
+ specified by \a timeZone. The default time representation is local time.
+
+ Note that there are possible values for \a msecs that lie outside the valid
+ range of QDateTime, both negative and positive. The behavior of this
+ function is undefined for those values.
- \sa fromSecsSinceEpoch()
+ \sa fromSecsSinceEpoch(), toMSecsSinceEpoch(), setMSecsSinceEpoch()
*/
QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, const QTimeZone &timeZone)
{
QDateTime dt;
- dt.setTimeZone(timeZone);
+ reviseTimeZone(dt.d, timeZone, TransitionResolution::Reject);
if (timeZone.isValid())
dt.setMSecsSinceEpoch(msecs);
return dt;
}
/*!
+ \since 6.5
+ \overload
+*/
+QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs)
+{
+ return fromMSecsSinceEpoch(msecs, QTimeZone::LocalTime);
+}
+
+/*!
\since 5.8
- Returns a datetime whose date and time are the number of seconds \a secs
- that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
- Time (Qt::UTC) and with the given \a timeZone.
+ Returns a datetime representing a moment the given number \a secs of seconds
+ after the start, in UTC, of the year 1970, described as specified by \a
+ timeZone. The default time representation is local time.
+
+ Note that there are possible values for \a secs that lie outside the valid
+ range of QDateTime, both negative and positive. The behavior of this
+ function is undefined for those values.
- \sa fromMSecsSinceEpoch()
+ \sa fromMSecsSinceEpoch(), toSecsSinceEpoch(), setSecsSinceEpoch()
*/
QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, const QTimeZone &timeZone)
{
- constexpr qint64 maxSeconds = std::numeric_limits<qint64>::max() / 1000;
- constexpr qint64 minSeconds = std::numeric_limits<qint64>::min() / 1000;
- if (secs > maxSeconds || secs < minSeconds)
- return QDateTime(); // Would {und,ov}erflow
- return fromMSecsSinceEpoch(secs * 1000, timeZone);
+ QDateTime dt;
+ reviseTimeZone(dt.d, timeZone, TransitionResolution::Reject);
+ if (timeZone.isValid())
+ dt.setSecsSinceEpoch(secs);
+ return dt;
+}
+
+/*!
+ \since 6.5
+ \overload
+*/
+QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs)
+{
+ return fromSecsSinceEpoch(secs, QTimeZone::LocalTime);
}
-#endif
#if QT_CONFIG(datestring) // depends on, so implies, textdate
/*!
+ \fn 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 this is not possible.
@@ -4666,7 +5653,12 @@ QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, const QTimeZone &timeZone)
\sa toString(), QLocale::toDateTime()
*/
-QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
+
+/*!
+ \overload
+ \since 6.0
+*/
+QDateTime QDateTime::fromString(QStringView string, Qt::DateFormat format)
{
if (string.isEmpty())
return QDateTime();
@@ -4678,8 +5670,8 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
if (!rfc.date.isValid() || !rfc.time.isValid())
return QDateTime();
- QDateTime dateTime(rfc.date, rfc.time, Qt::UTC);
- dateTime.setOffsetFromUtc(rfc.utcOffset);
+ QDateTime dateTime(rfc.date, rfc.time, QTimeZone::UTC);
+ dateTime.setTimeZone(QTimeZone::fromSecondsAheadOfUtc(rfc.utcOffset));
return dateTime;
}
case Qt::ISODate:
@@ -4688,30 +5680,29 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
if (size < 10)
return QDateTime();
- QDate date = QDate::fromString(string.left(10), Qt::ISODate);
+ QDate date = QDate::fromString(string.first(10), Qt::ISODate);
if (!date.isValid())
return QDateTime();
if (size == 10)
return date.startOfDay();
- Qt::TimeSpec spec = Qt::LocalTime;
- QStringView isoString = QStringView(string).mid(10); // trim "yyyy-MM-dd"
+ QTimeZone zone = QTimeZone::LocalTime;
+ QStringView isoString = string.sliced(10); // trim "yyyy-MM-dd"
// Must be left with T (or space) and at least one digit for the hour:
if (isoString.size() < 2
- || !(isoString.startsWith(QLatin1Char('T'), Qt::CaseInsensitive)
+ || !(isoString.startsWith(u'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(' ')))) {
+ || isoString.startsWith(u' '))) {
return QDateTime();
}
- isoString = isoString.mid(1); // trim 'T' (or space)
+ isoString = isoString.sliced(1); // trim 'T' (or space)
- 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'), Qt::CaseInsensitive)) {
- spec = Qt::UTC;
+ // Check end of string for Time Zone definition, either Z for UTC or ±HH:mm for Offset
+ if (isoString.endsWith(u'Z', Qt::CaseInsensitive)) {
+ zone = QTimeZone::UTC;
isoString.chop(1); // trim 'Z'
} else {
// the loop below is faster but functionally equal to:
@@ -4719,22 +5710,18 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
int signIndex = isoString.size() - 1;
Q_ASSERT(signIndex >= 0);
bool found = false;
- {
- const QChar plus = QLatin1Char('+');
- const QChar minus = QLatin1Char('-');
- do {
- QChar character(isoString.at(signIndex));
- found = character == plus || character == minus;
- } while (!found && --signIndex >= 0);
- }
+ do {
+ QChar character(isoString[signIndex]);
+ found = character == u'+' || character == u'-';
+ } while (!found && --signIndex >= 0);
if (found) {
bool ok;
- offset = fromOffsetString(isoString.mid(signIndex), &ok);
+ int offset = fromOffsetString(isoString.sliced(signIndex), &ok);
if (!ok)
return QDateTime();
- isoString = isoString.left(signIndex);
- spec = Qt::OffsetFromUTC;
+ isoString = isoString.first(signIndex);
+ zone = QTimeZone::fromSecondsAheadOfUtc(offset);
}
}
@@ -4744,116 +5731,65 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
QTime time = fromIsoTimeString(isoString, format, &isMidnight24);
if (!time.isValid())
return QDateTime();
- if (isMidnight24)
- date = date.addDays(1);
- return QDateTime(date, time, spec, offset);
+ if (isMidnight24) // time is 0:0, but we want the start of next day:
+ return date.addDays(1).startOfDay(zone);
+ return QDateTime(date, time, zone);
}
case Qt::TextDate: {
- QList<QStringView> parts = QStringView { string }.split(QLatin1Char(' '), Qt::SkipEmptyParts);
+ QVarLengthArray<QStringView, 6> parts;
- if ((parts.count() < 5) || (parts.count() > 6))
- return QDateTime();
+ auto tokens = string.tokenize(u' ', Qt::SkipEmptyParts);
+ auto it = tokens.begin();
+ for (int i = 0; i < 6 && it != tokens.end(); ++i, ++it)
+ parts.emplace_back(*it);
- // Accept "Sun Dec 1 13:02:00 1974" and "Sun 1. Dec 13:02:00 1974"
+ // Documented as "ddd MMM d HH:mm:ss yyyy" with optional offset-suffix;
+ // and allow time either before or after year.
+ if (parts.size() < 5 || it != tokens.end())
+ return QDateTime();
// Year and time can be in either order.
// Guess which by looking for ':' in the time
int yearPart = 3;
int timePart = 3;
- if (parts.at(3).contains(QLatin1Char(':')))
+ if (parts.at(3).contains(u':'))
yearPart = 4;
- else if (parts.at(4).contains(QLatin1Char(':')))
+ else if (parts.at(4).contains(u':'))
timePart = 4;
else
return QDateTime();
- int month = 0;
- int day = 0;
bool ok = false;
-
- int year = parts.at(yearPart).toInt(&ok);
- if (!ok || year == 0)
+ int day = parts.at(2).toInt(&ok);
+ int year = ok ? parts.at(yearPart).toInt(&ok) : 0;
+ int month = fromShortMonthName(parts.at(1));
+ if (!ok || year == 0 || day == 0 || month < 1)
return QDateTime();
- // Next try month then day
- month = fromShortMonthName(parts.at(1));
- if (month)
- day = parts.at(2).toInt(&ok);
-
- // If failed, try day then month
- if (!ok || !month || !day) {
- month = fromShortMonthName(parts.at(2));
- if (month) {
- QStringView dayStr = parts.at(1);
- if (dayStr.endsWith(QLatin1Char('.'))) {
- dayStr = dayStr.left(dayStr.size() - 1);
- day = dayStr.toInt(&ok);
- }
- }
- }
-
- // If both failed, give up
- if (!ok || !month || !day)
- return QDateTime();
-
- QDate date(year, month, day);
+ const QDate date(year, month, day);
if (!date.isValid())
return QDateTime();
- // ### fixme, use QStringView::tokenize() when available
- QList<QStringView> timeParts = parts.at(timePart).split(QLatin1Char(':'));
- if (timeParts.count() < 2 || timeParts.count() > 3)
- return QDateTime();
-
- int hour = timeParts.at(0).toInt(&ok);
- if (!ok)
- return QDateTime();
-
- int minute = timeParts.at(1).toInt(&ok);
- if (!ok)
- return QDateTime();
-
- int second = 0;
- int millisecond = 0;
- if (timeParts.count() > 2) {
- // ### fixme, use QStringView::tokenize() when available
- const QList<QStringView> secondParts = timeParts.at(2).split(QLatin1Char('.'));
- if (secondParts.size() > 2) {
- return QDateTime();
- }
-
- second = secondParts.first().toInt(&ok);
- if (!ok) {
- return QDateTime();
- }
-
- if (secondParts.size() > 1) {
- millisecond = secondParts.last().toInt(&ok);
- if (!ok) {
- return QDateTime();
- }
- }
- }
-
- QTime time(hour, minute, second, millisecond);
+ const QTime time = fromIsoTimeString(parts.at(timePart), format, nullptr);
if (!time.isValid())
return QDateTime();
- if (parts.count() == 5)
- return QDateTime(date, time, Qt::LocalTime);
+ if (parts.size() == 5)
+ return QDateTime(date, time);
QStringView tz = parts.at(5);
- if (!tz.startsWith(QLatin1String("GMT"), Qt::CaseInsensitive))
- return QDateTime();
- tz = tz.mid(3);
- if (!tz.isEmpty()) {
+ if (tz.startsWith("UTC"_L1)
+ // GMT has long been deprecated as an alias for UTC.
+ || tz.startsWith("GMT"_L1, Qt::CaseInsensitive)) {
+ tz = tz.sliced(3);
+ if (tz.isEmpty())
+ return QDateTime(date, time, QTimeZone::UTC);
+
int offset = fromOffsetString(tz, &ok);
- if (!ok)
- return QDateTime();
- return QDateTime(date, time, Qt::OffsetFromUTC, offset);
- } else {
- return QDateTime(date, time, Qt::UTC);
+ return ok ? QDateTime(date, time, QTimeZone::fromSecondsAheadOfUtc(offset))
+ : QDateTime();
}
+ return QDateTime();
}
}
@@ -4861,29 +5797,55 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
}
/*!
+ \fn QDateTime QDateTime::fromString(const QString &string, const QString &format, int baseYear, QCalendar cal)
+
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.
+ \include qlocale.cpp base-year-for-two-digit
+
In addition to the expressions, recognized in the format string to represent
parts of the date and time, by QDate::fromString() and QTime::fromString(),
this method supports:
\table
\header \li Expression \li Output
- \row \li t \li the timezone (for example "CEST")
+ \row \li t
+ \li the timezone (offset, name, "Z" or offset with "UTC" prefix)
+ \row \li tt
+ \li the timezone in offset format with no colon between hours and
+ minutes (for example "+0200")
+ \row \li ttt
+ \li the timezone in offset format with a colon between hours and
+ minutes (for example "+02:00")
+ \row \li tttt
+ \li the timezone name (for example "Europe/Berlin"). The name
+ recognized are those known to \l QTimeZone, which may depend on the
+ operating system in use.
\endtable
+ If no 't' format specifier is present, the system's local time-zone is used.
+ For the defaults of all other fields, see QDate::fromString() and QTime::fromString().
+
+ For example:
+
+ \snippet code/src_corelib_time_qdatetime.cpp 14
+
All other input characters will be treated as text. Any non-empty sequence
of characters enclosed in single quotes will also be treated (stripped of
the quotes) as text and not be interpreted as expressions.
\snippet code/src_corelib_time_qdatetime.cpp 12
- If the format is not satisfied, an invalid QDateTime is returned.
+ If the format is not satisfied, an invalid QDateTime is returned. If the
+ format is satisfied but \a string represents an invalid datetime (e.g. in a
+ gap skipped by a time-zone transition), an valid QDateTime is returned, that
+ represents a near-by datetime that is valid.
+
The expressions that don't have leading zeroes (d, M, h, m, s, z) will be
- greedy. This means that they will use two digits even if this will
+ greedy. This means that they will use two digits (or three, for z) even if this will
put them outside the range and/or leave too few digits for other
sections.
@@ -4904,74 +5866,99 @@ QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
\snippet code/src_corelib_time_qdatetime.cpp 21
- For any field that is not represented in the format, the following
- defaults are used:
-
- \table
- \header \li Field \li Default value
- \row \li Year \li 1900
- \row \li Month \li 1 (January)
- \row \li Day \li 1
- \row \li Hour \li 0
- \row \li Minute \li 0
- \row \li Second \li 0
- \endtable
-
- For example:
-
- \snippet code/src_corelib_time_qdatetime.cpp 14
+ \note Day and month names as well as AM/PM indicators must be given in
+ English (C locale). If localized month and day names or localized forms of
+ AM/PM are to be recognized, use QLocale::system().toDateTime().
- \note If localized month and day names are used, please switch to using
- QLocale::system().toDateTime() as QDateTime methods shall change to only
- recognize English (C locale) names at Qt 6.
+ \note If a format character is repeated more times than the longest
+ expression in the table above using it, this part of the format will be read
+ as several expressions with no separator between them; the longest above,
+ possibly repeated as many times as there are copies of it, ending with a
+ residue that may be a shorter expression. Thus \c{'tttttt'} would match
+ \c{"Europe/BerlinEurope/Berlin"} and set the zone to Berlin time; if the
+ datetime string contained "Europe/BerlinZ" it would "match" but produce an
+ inconsistent result, leading to an invalid datetime.
\sa toString(), QDate::fromString(), QTime::fromString(),
QLocale::toDateTime()
*/
-QDateTime QDateTime::fromString(const QString &string, const QString &format, QCalendar cal)
+/*!
+ \fn QDateTime QDateTime::fromString(QStringView string, QStringView format, QCalendar cal)
+ \overload
+ \since 6.0
+*/
+
+/*!
+ \overload
+ \since 6.0
+*/
+QDateTime QDateTime::fromString(const QString &string, QStringView format, int baseYear,
+ QCalendar cal)
{
#if QT_CONFIG(datetimeparser)
QDateTime datetime;
QDateTimeParser dt(QMetaType::QDateTime, QDateTimeParser::FromString, cal);
dt.setDefaultLocale(QLocale::c());
- if (dt.parseFormat(format) && dt.fromString(string, &datetime))
+ if (dt.parseFormat(format) && (dt.fromString(string, &datetime, baseYear)
+ || !datetime.isValid())) {
return datetime;
+ }
#else
Q_UNUSED(string);
Q_UNUSED(format);
+ Q_UNUSED(baseYear);
Q_UNUSED(cal);
#endif
return QDateTime();
}
-#endif // datestring
/*!
- \fn QDateTime QDateTime::toLocalTime() const
+ \fn QDateTime QDateTime::fromString(const QString &string, const QString &format, QCalendar cal)
+ \overload
+ \since 5.14
+*/
- Returns a datetime containing the date and time information in
- this datetime, but specified using the Qt::LocalTime definition.
+/*!
+ \fn QDateTime QDateTime::fromString(const QString &string, QStringView format, QCalendar cal)
+ \overload
+ \since 6.0
+*/
- Example:
+/*!
+ \fn QDateTime QDateTime::fromString(QStringView string, QStringView format, int baseYear, QCalendar cal)
+ \overload
+ \since 6.7
+*/
- \snippet code/src_corelib_time_qdatetime.cpp 17
+/*!
+ \fn QDateTime QDateTime::fromString(QStringView string, QStringView format, int baseYear)
+ \overload
+ \since 6.7
- \sa toTimeSpec()
+ Uses a default-constructed QCalendar.
*/
/*!
- \fn QDateTime QDateTime::toUTC() const
-
- Returns a datetime containing the date and time information in
- this datetime, but specified using the Qt::UTC definition.
+ \overload
+ \since 6.7
- Example:
+ Uses a default-constructed QCalendar.
+*/
+QDateTime QDateTime::fromString(const QString &string, QStringView format, int baseYear)
+{
+ return fromString(string, format, baseYear, QCalendar());
+}
- \snippet code/src_corelib_time_qdatetime.cpp 18
+/*!
+ \fn QDateTime QDateTime::fromString(const QString &string, const QString &format, int baseYear)
+ \overload
+ \since 6.7
- \sa toTimeSpec()
+ Uses a default-constructed QCalendar.
*/
+#endif // datestring
/*****************************************************************************
Date/time stream functions
@@ -4991,7 +5978,7 @@ QDataStream &operator<<(QDataStream &out, QDate date)
if (out.version() < QDataStream::Qt_5_0)
return out << quint32(date.jd);
else
- return out << qint64(date.jd);
+ return out << date.jd;
}
/*!
@@ -5010,9 +5997,7 @@ QDataStream &operator>>(QDataStream &in, QDate &date)
// Older versions consider 0 an invalid jd.
date.jd = (jd != 0 ? jd : QDate::nullJd());
} else {
- qint64 jd;
- in >> jd;
- date.jd = jd;
+ in >> date.jd;
}
return in;
@@ -5066,11 +6051,12 @@ QDataStream &operator>>(QDataStream &in, QTime &time)
*/
QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
{
- QPair<QDate, QTime> dateAndTime;
+ std::pair<QDate, QTime> dateAndTime;
+ // TODO: new version, route spec and details via QTimeZone
if (out.version() >= QDataStream::Qt_5_2) {
- // In 5.2 we switched to using Qt::TimeSpec and added offset support
+ // In 5.2 we switched to using Qt::TimeSpec and added offset and zone support
dateAndTime = getDateTime(dateTime.d);
out << dateAndTime << qint8(dateTime.timeSpec());
if (dateTime.timeSpec() == Qt::OffsetFromUTC)
@@ -5133,67 +6119,61 @@ QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
QDate dt;
QTime tm;
qint8 ts = 0;
- Qt::TimeSpec spec = Qt::LocalTime;
- qint32 offset = 0;
-#if QT_CONFIG(timezone)
- QTimeZone tz;
-#endif // timezone
+ QTimeZone zone(QTimeZone::LocalTime);
if (in.version() >= QDataStream::Qt_5_2) {
- // In 5.2 we switched to using Qt::TimeSpec and added offset support
+ // In 5.2 we switched to using Qt::TimeSpec and added offset and zone support
in >> dt >> tm >> ts;
- spec = static_cast<Qt::TimeSpec>(ts);
- if (spec == Qt::OffsetFromUTC) {
+ switch (static_cast<Qt::TimeSpec>(ts)) {
+ case Qt::UTC:
+ zone = QTimeZone::UTC;
+ break;
+ case Qt::OffsetFromUTC: {
+ qint32 offset = 0;
in >> offset;
- dateTime = QDateTime(dt, tm, spec, offset);
-#if QT_CONFIG(timezone)
- } else if (spec == Qt::TimeZone) {
- in >> tz;
- dateTime = QDateTime(dt, tm, tz);
-#endif // timezone
- } else {
- dateTime = QDateTime(dt, tm, spec);
+ zone = QTimeZone::fromSecondsAheadOfUtc(offset);
+ break;
}
+ case Qt::LocalTime:
+ break;
+ case Qt::TimeZone:
+ in >> zone;
+ break;
+ }
+ // Note: no way to resolve transition ambiguity, when relevant; use default.
+ dateTime = QDateTime(dt, tm, zone);
} else if (in.version() == QDataStream::Qt_5_0) {
// In Qt 5.0 we incorrectly serialised all datetimes as UTC
in >> dt >> tm >> ts;
- spec = static_cast<Qt::TimeSpec>(ts);
- dateTime = QDateTime(dt, tm, Qt::UTC);
- dateTime = dateTime.toTimeSpec(spec);
+ dateTime = QDateTime(dt, tm, QTimeZone::UTC);
+ if (static_cast<Qt::TimeSpec>(ts) == Qt::LocalTime)
+ dateTime = dateTime.toTimeZone(zone);
} else if (in.version() >= QDataStream::Qt_4_0) {
// From 4.0 to 5.1 (except 5.0) we used QDateTimePrivate::Spec
in >> dt >> tm >> ts;
- switch ((QDateTimePrivate::Spec)ts) {
+ switch (static_cast<QDateTimePrivate::Spec>(ts)) {
+ case QDateTimePrivate::OffsetFromUTC: // No offset was stored, so treat as UTC.
case QDateTimePrivate::UTC:
- spec = Qt::UTC;
- break;
- case QDateTimePrivate::OffsetFromUTC:
- spec = Qt::OffsetFromUTC;
- break;
- case QDateTimePrivate::TimeZone:
- spec = Qt::TimeZone;
-#if QT_CONFIG(timezone)
- // FIXME: need to use a different constructor !
-#endif
+ zone = QTimeZone::UTC;
break;
+ case QDateTimePrivate::TimeZone: // No zone was stored, so treat as LocalTime:
case QDateTimePrivate::LocalUnknown:
case QDateTimePrivate::LocalStandard:
case QDateTimePrivate::LocalDST:
- spec = Qt::LocalTime;
break;
}
- dateTime = QDateTime(dt, tm, spec, offset);
+ dateTime = QDateTime(dt, tm, zone);
} else { // version < QDataStream::Qt_4_0
// Before 4.0 there was no TimeSpec, only Qt::LocalTime was supported
in >> dt >> tm;
- dateTime = QDateTime(dt, tm, spec, offset);
+ dateTime = QDateTime(dt, tm);
}
@@ -5211,7 +6191,11 @@ QDebug operator<<(QDebug dbg, QDate date)
QDebugStateSaver saver(dbg);
dbg.nospace() << "QDate(";
if (date.isValid())
- dbg.nospace() << date.toString(Qt::ISODate);
+ // QTBUG-91070, ISODate only supports years in the range 0-9999
+ if (int y = date.year(); y > 0 && y <= 9999)
+ dbg.nospace() << date.toString(Qt::ISODate);
+ else
+ dbg.nospace() << date.toString(Qt::TextDate);
else
dbg.nospace() << "Invalid";
dbg.nospace() << ')';