Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
QDateTime Class Reference

\inmodule QtCore\reentrant More...

#include <qdatetime.h>

+ Collaboration diagram for QDateTime:

Public Types

enum class  YearRange : qint32 { First = -292275056 , Last = +292278994 }
 

Public Member Functions

 QDateTime () noexcept
 Constructs a null datetime, nominally using local time.
 
 QDateTime (QDate date, QTime time, const QTimeZone &timeZone)
 
 QDateTime (QDate date, QTime time)
 
 QDateTime (const QDateTime &other) noexcept
 Constructs a copy of the other datetime.
 
 QDateTime (QDateTime &&other) noexcept
 
 ~QDateTime ()
 Destroys the datetime.
 
QDateTimeoperator= (const QDateTime &other) noexcept
 Copies the other datetime into this and returns this copy.
 
void swap (QDateTime &other) noexcept
 
bool isNull () const
 Returns true if both the date and the time are null; otherwise returns false.
 
bool isValid () const
 Returns true if this datetime represents a definite moment, otherwise false.
 
QDate date () const
 Returns the date part of the datetime.
 
QTime time () const
 Returns the time part of the datetime.
 
Qt::TimeSpec timeSpec () const
 Returns the time specification of the datetime.
 
int offsetFromUtc () const
 
QTimeZone timeRepresentation () const
 
QString timeZoneAbbreviation () const
 
bool isDaylightTime () const
 
qint64 toMSecsSinceEpoch () const
 
qint64 toSecsSinceEpoch () const
 
void setDate (QDate date)
 Sets the date part of this datetime to date.
 
void setTime (QTime time)
 Sets the time part of this datetime to time.
 
void setTimeZone (const QTimeZone &toZone)
 
void setMSecsSinceEpoch (qint64 msecs)
 
void setSecsSinceEpoch (qint64 secs)
 
QDateTime addDays (qint64 days) const
 Returns a QDateTime object containing a datetime ndays days later than the datetime of this object (or earlier if ndays is negative).
 
QDateTime addMonths (int months) const
 Returns a QDateTime object containing a datetime nmonths months later than the datetime of this object (or earlier if nmonths is negative).
 
QDateTime addYears (int years) const
 Returns a QDateTime object containing a datetime nyears years later than the datetime of this object (or earlier if nyears is negative).
 
QDateTime addSecs (qint64 secs) const
 Returns a QDateTime object containing a datetime s seconds later than the datetime of this object (or earlier if s is negative).
 
QDateTime addMSecs (qint64 msecs) const
 Returns a QDateTime object containing a datetime msecs milliseconds later than the datetime of this object (or earlier if msecs is negative).
 
QDateTime addDuration (std::chrono::milliseconds msecs) const
 
QDateTime toLocalTime () const
 Returns a copy of this datetime converted to local time.
 
QDateTime toUTC () const
 Returns a copy of this datetime converted to UTC.
 
QDateTime toOffsetFromUtc (int offsetSeconds) const
 
QDateTime toTimeZone (const QTimeZone &toZone) const
 
qint64 daysTo (const QDateTime &) const
 Returns the number of days from this datetime to the other datetime.
 
qint64 secsTo (const QDateTime &) const
 Returns the number of seconds from this datetime to the other datetime.
 
qint64 msecsTo (const QDateTime &) const
 Returns the number of milliseconds from this datetime to the other datetime.
 
QDateTimeoperator+= (std::chrono::milliseconds duration)
 
QDateTimeoperator-= (std::chrono::milliseconds duration)
 

Static Public Member Functions

static QDateTime currentDateTime (const QTimeZone &zone)
 
static QDateTime currentDateTime ()
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
static QDateTime currentDateTimeUtc ()
 
static QDateTime fromMSecsSinceEpoch (qint64 msecs, const QTimeZone &timeZone)
 
static QDateTime fromSecsSinceEpoch (qint64 secs, const QTimeZone &timeZone)
 
static QDateTime fromMSecsSinceEpoch (qint64 msecs)
 
static QDateTime fromSecsSinceEpoch (qint64 secs)
 
static qint64 currentMSecsSinceEpoch () noexcept
 
static qint64 currentSecsSinceEpoch () noexcept
 

Friends

class QDateTimePrivate
 
std::chrono::milliseconds operator- (const QDateTime &lhs, const QDateTime &rhs)
 
QDateTime operator+ (const QDateTime &dateTime, std::chrono::milliseconds duration)
 
QDateTime operator+ (std::chrono::milliseconds duration, const QDateTime &dateTime)
 
QDateTime operator- (const QDateTime &dateTime, std::chrono::milliseconds duration)
 
bool operator== (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is the same as rhs; otherwise returns false.
 
bool operator!= (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is different from rhs; otherwise returns false.
 
bool operator< (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is earlier than rhs; otherwise returns false.
 
bool operator<= (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is earlier than or equal to rhs; otherwise returns false.
 
bool operator> (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is later than rhs; otherwise returns false.
 
bool operator>= (const QDateTime &lhs, const QDateTime &rhs)
 Returns true if lhs is later than or equal to rhs; otherwise returns false.
 
Q_CORE_EXPORT QDataStreamoperator<< (QDataStream &, const QDateTime &)
 Writes dateTime to the out stream.
 
Q_CORE_EXPORT QDataStreamoperator>> (QDataStream &, QDateTime &)
 Reads a datetime from the stream in into dateTime.
 

Related Symbols

(Note that these are not member symbols.)

QDataStreamoperator<< (QDataStream &out, const QDateTime &dateTime)
 Writes dateTime to the out stream.
 
QDataStreamoperator>> (QDataStream &in, QDateTime &dateTime)
 Reads a datetime from the stream in into dateTime.
 

Detailed Description

\inmodule QtCore

\reentrant

The QDateTime class provides date and time functions.

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}. 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 {Daylight-Saving Time (DST)}{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 representation 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 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 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 {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 textual format by the toString() function.

QDateTime provides a full set of operators to compare two QDateTime objects, where smaller means earlier and larger means later.

You can increment (or decrement) a datetime by a given number of milliseconds using addMSecs(), seconds using addSecs(), or days using addDays(). Similarly, you can use addMonths() and addYears(). The daysTo() function returns the number of days between two datetimes, secsTo() returns the number of seconds between two datetimes, and msecsTo() returns the number of milliseconds between two datetimes. These operations are aware of daylight-saving time (DST) and other time-zone transitions, where applicable.

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 {Qt::TimeZone}) to use that instead.

Note
QDateTime does not account for leap seconds.

Definition at line 256 of file qdatetime.h.

Member Enumeration Documentation

◆ YearRange

enum class QDateTime::YearRange : qint32
strong
Since
5.14

This enumerated type describes the range of years (in the Gregorian calendar) representable by QDateTime:

\value First The later parts of this year are representable \value Last The earlier parts of this year are representable

All dates strictly between these two years are also representable. Note, however, that the Gregorian Calendar has no year zero.

Note
QDate can describe dates in a wider range of years. For most purposes, this makes little difference, as the range of years that QDateTime can support reaches 292 million years either side of 1970.
See also
isValid(), QDate
Enumerator
First 
Last 

Definition at line 517 of file qdatetime.h.

Constructor & Destructor Documentation

◆ QDateTime() [1/5]

QDateTime::QDateTime ( )
noexcept

Constructs a null datetime, nominally using local time.

A null datetime is invalid, since its date and time are invalid.

See also
isValid(), setMSecsSinceEpoch(), setDate(), setTime(), setTimeZone()

Definition at line 3473 of file qdatetime.cpp.

References Data.

Referenced by addDays(), addMonths(), addMSecs(), addSecs(), and addYears().

+ Here is the caller graph for this function:

◆ QDateTime() [2/5]

QDateTime::QDateTime ( QDate  date,
QTime  time,
const QTimeZone timeZone 
)
Since
5.2

Constructs a datetime with the given date and time, using the time representation described by timeZone.

If date is valid and time is not, the time will be set to midnight. If timeZone is invalid then the datetime will be invalid.

Definition at line 3519 of file qdatetime.cpp.

◆ QDateTime() [3/5]

QDateTime::QDateTime ( QDate  date,
QTime  time 
)
Since
6.5

Constructs a datetime with the given date and time, using local time.

If date is valid and time is not, midnight will be used as the time.

Definition at line 3532 of file qdatetime.cpp.

◆ QDateTime() [4/5]

QDateTime::QDateTime ( const QDateTime other)
noexcept

Constructs a copy of the other datetime.

Definition at line 3540 of file qdatetime.cpp.

◆ QDateTime() [5/5]

QDateTime::QDateTime ( QDateTime &&  other)
noexcept
Since
5.8 Moves the content of the temporary other datetime to this object and leaves other in an unspecified (but proper) state.

Definition at line 3550 of file qdatetime.cpp.

◆ ~QDateTime()

QDateTime::~QDateTime ( )

Destroys the datetime.

Definition at line 3558 of file qdatetime.cpp.

Member Function Documentation

◆ addDays()

QDateTime QDateTime::addDays ( qint64  ndays) const

Returns a QDateTime object containing a datetime ndays days later than the datetime of this object (or earlier if ndays is negative).

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 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.

See also
daysTo(), addMonths(), addYears(), addSecs()

Definition at line 4273 of file qdatetime.cpp.

References QDateTime(), getDateTime(), isNull(), and massageAdjustedDateTime().

Referenced by jobHoldToString().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ addDuration()

QDateTime QDateTime::addDuration ( std::chrono::milliseconds  msecs) const
inline
Since
6.4

Returns a QDateTime object containing a datetime msecs milliseconds later than the datetime of this object (or earlier if msecs is negative).

If this datetime is invalid, an invalid datetime will be returned.

Note
Adding durations expressed in {std::chrono::months} or {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.
See also
addMSecs(), msecsTo(), addDays(), addMonths(), addYears()

Definition at line 368 of file qdatetime.h.

◆ addMonths()

QDateTime QDateTime::addMonths ( int  nmonths) const

Returns a QDateTime object containing a datetime nmonths months later than the datetime of this object (or earlier if nmonths is negative).

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 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.

See also
daysTo(), addDays(), addYears(), addSecs()

Definition at line 4298 of file qdatetime.cpp.

References QDateTime(), getDateTime(), isNull(), and massageAdjustedDateTime().

Referenced by QDateTimeParser::parse().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ addMSecs()

QDateTime QDateTime::addMSecs ( qint64  msecs) const

Returns a QDateTime object containing a datetime msecs milliseconds later than the datetime of this object (or earlier if msecs is negative).

If this datetime is invalid, an invalid datetime will be returned.

See also
addSecs(), msecsTo(), addDays(), addMonths(), addYears()

Definition at line 4361 of file qdatetime.cpp.

References QDateTime(), getMSecs(), getSpec(), isValid(), Qt::LocalTime, msecsCanBeSmall(), Qt::OffsetFromUTC, qAddOverflow(), setMSecsSinceEpoch(), Qt::TimeZone, toMSecsSinceEpoch(), Qt::UTC, and QDateTimePrivate::ValidityMask.

Referenced by addSecs(), and QQmlJS::Dom::DomEnvironment::finishLoadingDependencies().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ addSecs()

QDateTime QDateTime::addSecs ( qint64  s) const

Returns a QDateTime object containing a datetime s seconds later than the datetime of this object (or earlier if s is negative).

If this datetime is invalid, an invalid datetime will be returned.

See also
addMSecs(), secsTo(), addDays(), addMonths(), addYears()

Definition at line 4344 of file qdatetime.cpp.

References QDateTime(), addMSecs(), and qMulOverflow().

Referenced by QNetworkReplyHttpImplPrivate::fetchCacheMetaData(), QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(), QHstsHeaderParser::parse(), QDateTimeParser::parse(), and parseDateString().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ addYears()

QDateTime QDateTime::addYears ( int  nyears) const

Returns a QDateTime object containing a datetime nyears years later than the datetime of this object (or earlier if nyears is negative).

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 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.

See also
daysTo(), addDays(), addMonths(), addSecs()

Definition at line 4323 of file qdatetime.cpp.

References QDateTime(), getDateTime(), isNull(), and massageAdjustedDateTime().

+ Here is the call graph for this function:

◆ currentDateTime() [1/2]

QDateTime QDateTime::currentDateTime ( )
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Since
0.90

Definition at line 4788 of file qdatetime.cpp.

References currentDateTime(), and QTimeZone::LocalTime.

Referenced by QCtfLibImpl::QCtfLibImpl(), QZipWriterPrivate::addEntry(), currentDateTime(), currentDateTimeUtc(), QCalendarBackend::dateTimeToString(), QmlLsp::QmlLintSuggestions::diagnose(), QQmlPreviewFileEngine::fileTime(), ApplicationData::getCurrentDateTime(), jobHoldToString(), main(), QGstreamerImageCapture::probeBuffer(), QGeoAreaMonitorPolling::requestUpdate(), QJUnitTestLogger::startLogging(), and QGeoAreaMonitorPolling::startMonitoring().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ currentDateTime() [2/2]

QDateTime QDateTime::currentDateTime ( const QTimeZone zone)
static
Since
6.5

Returns the system clock's current datetime, using the time representation described by zone. If zone is omitted, local time is used.

See also
currentDateTimeUtc(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()

◆ currentDateTimeUtc()

QDateTime QDateTime::currentDateTimeUtc ( )
static

◆ currentMSecsSinceEpoch()

qint64 QDateTime::currentMSecsSinceEpoch ( )
staticnoexcept
Since
4.7

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.

See also
currentDateTime(), currentDateTimeUtc(), toTimeSpec()

Referenced by QSvgTinyDocument::currentElapsed(), QSvgTinyDocument::draw(), QSvgTinyDocument::draw(), QGeoPositionInfoSourceAndroid::processPositionUpdate(), QSvgTinyDocument::restartAnimation(), QDBusPlatformMenu::showPopup(), QGeoPositionInfoSourceAndroid::startUpdates(), and QQuickCanvasItem::updatePolish().

+ Here is the caller graph for this function:

◆ currentSecsSinceEpoch()

qint64 QDateTime::currentSecsSinceEpoch ( )
staticnoexcept
Since
5.8

Returns the number of seconds since the start, in UTC, of the year 1970.

This number is like the POSIX time_t variable.

See also
currentMSecsSinceEpoch()

Referenced by QQuickMouseArea::itemChange(), and qEncodeNtlmv2Response().

+ Here is the caller graph for this function:

◆ date()

◆ daysTo()

qint64 QDateTime::daysTo ( const QDateTime other) const

Returns the number of days from this datetime to the other datetime.

The number of days is counted as the number of times midnight is reached between this datetime to the other datetime. This means that a 10 minute difference from 23:55 to 0:05 the next day counts as one day.

If the other datetime is earlier than this datetime, the value returned is negative.

Example:

QDateTime startDate(QDate(2012, 7, 6), QTime(8, 30, 0));
QDateTime endDate(QDate(2012, 7, 7), QTime(16, 30, 0));
qDebug() << "Days from startDate to endDate: " << startDate.daysTo(endDate);
startDate = QDateTime(QDate(2012, 7, 6), QTime(23, 55, 0));
endDate = QDateTime(QDate(2012, 7, 7), QTime(0, 5, 0));
qDebug() << "Days from startDate to endDate: " << startDate.daysTo(endDate);
qSwap(startDate, endDate); // Make endDate before startDate.
qDebug() << "Days from startDate to endDate: " << startDate.daysTo(endDate);
\inmodule QtCore\reentrant
Definition qdatetime.h:257
QDateTime() noexcept
Constructs a null datetime, nominally using local time.
qint64 daysTo(const QDateTime &) const
Returns the number of days from this datetime to the other datetime.
\inmodule QtCore \reentrant
Definition qdatetime.h:27
\inmodule QtCore \reentrant
Definition qdatetime.h:189
qSwap(pi, e)
#define qDebug
[1]
Definition qlogging.h:160
QDateTime startDate(QDate(2012, 7, 6), QTime(8, 30, 0))
[14]
QDateTime endDate(QDate(2012, 7, 7), QTime(16, 30, 0))
See also
addDays(), secsTo(), msecsTo()

Definition at line 4443 of file qdatetime.cpp.

References date(), QDate::daysTo(), and other().

Referenced by QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(), and QDateTimeParser::parse().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fromMSecsSinceEpoch() [1/2]

QDateTime QDateTime::fromMSecsSinceEpoch ( qint64  msecs)
static
Since
6.5 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 5091 of file qdatetime.cpp.

References fromMSecsSinceEpoch(), and QTimeZone::LocalTime.

+ Here is the call graph for this function:

◆ fromMSecsSinceEpoch() [2/2]

QDateTime QDateTime::fromMSecsSinceEpoch ( qint64  msecs,
const QTimeZone timeZone 
)
static
Since
5.2 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns a datetime representing a moment the given number msecs of milliseconds after the start, in UTC, of the year 1970, described as specified by timeZone. The default time representation is local time.

Note that there are possible values for msecs that lie outside the valid range of QDateTime, both negative and positive. The behavior of this function is undefined for those values.

See also
fromSecsSinceEpoch(), toMSecsSinceEpoch(), setMSecsSinceEpoch()

Definition at line 5078 of file qdatetime.cpp.

References QTimeZone::isValid(), reviseTimeZone(), and setMSecsSinceEpoch().

Referenced by convertToExtendedType(), QDateTimeEditPrivate::dateTimeValue(), QQmlJS::Dom::DomUniverse::execQueue(), QDateTimeEdit::fixup(), fromMSecsSinceEpoch(), QResource::lastModified(), DocumentFile::lastModified(), operator>>(), AndroidPositioning::positionInfoFromJavaLocation(), QDateTimeEditPrivate::stepBy(), QQmlJS::Dom::ParsingTask::toCbor(), ToDateTime(), QTimeZonePrivate::toOffsetData(), and toTimeZone().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fromSecsSinceEpoch() [1/2]

QDateTime QDateTime::fromSecsSinceEpoch ( qint64  secs)
static
Since
6.5 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 5123 of file qdatetime.cpp.

References fromSecsSinceEpoch(), and QTimeZone::LocalTime.

+ Here is the call graph for this function:

◆ fromSecsSinceEpoch() [2/2]

QDateTime QDateTime::fromSecsSinceEpoch ( qint64  secs,
const QTimeZone timeZone 
)
static
Since
5.8 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns a datetime representing a moment the given number secs of seconds after the start, in UTC, of the year 1970, described as specified by timeZone. The default time representation is local time.

Note that there are possible values for secs that lie outside the valid range of QDateTime, both negative and positive. The behavior of this function is undefined for those values.

See also
fromMSecsSinceEpoch(), toSecsSinceEpoch(), setSecsSinceEpoch()

Definition at line 5110 of file qdatetime.cpp.

References QTimeZone::isValid(), reviseTimeZone(), and setSecsSinceEpoch().

Referenced by fromSecsSinceEpoch(), and QNetworkCookiePrivate::parseSetCookieHeaderLine().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isDaylightTime()

bool QDateTime::isDaylightTime ( ) const
Since
5.2

Returns if this datetime falls in Daylight-Saving Time.

If the Qt::TimeSpec is not Qt::LocalTime or Qt::TimeZone then will always return false.

See also
timeSpec()

Definition at line 3786 of file qdatetime.cpp.

References QDateTimePrivate::DaylightTime, QDateTimePrivate::ZoneState::dst, extractDaylightStatus(), getMSecs(), getSpec(), getStatus(), isValid(), QDateTimePrivate::localStateAtMillis(), Qt::LocalTime, Qt::OffsetFromUTC, Q_ASSERT, Qt::TimeZone, toMSecsSinceEpoch(), QDateTimePrivate::UnknownDaylightTime, and Qt::UTC.

+ Here is the call graph for this function:

◆ isNull()

bool QDateTime::isNull ( ) const

Returns true if both the date and the time are null; otherwise returns false.

A null datetime is invalid.

See also
QDate::isNull(), QTime::isNull(), isValid()

Definition at line 3586 of file qdatetime.cpp.

References getStatus(), and QDateTimePrivate::ValidityMask.

Referenced by addDays(), addMonths(), addYears(), and QDateTimeEditPrivate::validateAndInterpret().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isValid()

bool QDateTime::isValid ( ) const

Returns true if this datetime represents a definite moment, otherwise false.

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.

See also
QDateTime::YearRange, QDate::isValid(), QTime::isValid()

Definition at line 3606 of file qdatetime.cpp.

References getStatus(), and QDateTimePrivate::ValidDateTime.

Referenced by QDateTimeEdit::QDateTimeEdit(), QOCIDateTime::QOCIDateTime(), QDateTimeParser::absoluteMax(), addMSecs(), QmlLsp::QQmlCodeModel::buildPathsForFileUrl(), convertToExtendedType(), dateFromString(), dateTimeFromString(), QV4::DateObject::dateTimeToString(), QCalendarBackend::dateTimeToString(), QDateTimeEditPrivate::dateTimeValue(), QDate::endOfDay(), QNetworkDiskCache::expire(), QDB2Driver::formatValue(), QIBaseDriver::formatValue(), QOCIDriver::formatValue(), QODBCDriver::formatValue(), QPSQLDriver::formatValue(), QSqlDriver::formatValue(), QNetworkHeadersPrivate::fromHttpDate(), QDateTimeParser::fromString(), isDaylightTime(), QHstsPolicy::isExpired(), QNetworkCookie::isSessionCookie(), QGeoPositionInfo::isValid(), QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(), msecsTo(), offsetFromUtc(), QTlsPrivate::X509CertificateGeneric::parse(), QDateTimeParser::parse(), parseDateString(), parseHttpDate(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), ParseString(), QGeoAreaMonitorPolling::requestUpdate(), QDateTimeEdit::setDate(), QDateTimeEdit::setDateTime(), QFileSystemEngine::setFileTime(), QDateTimeEdit::setMaximumDateTime(), QDateTimeEdit::setMinimumDateTime(), QGeoAreaMonitorPolling::startMonitoring(), QDate::startOfDay(), timeFromString(), timeZoneAbbreviation(), toEarliest(), toLatest(), QLocale::toString(), QLocale::toString(), toTimeZone(), QDateTimeEditPrivate::validateAndInterpret(), QV4::ExecutableCompilationUnit::verifyHeader(), RCCFileInfo::writeDataInfo(), and writeMSDosDate().

+ Here is the call graph for this function:

◆ msecsTo()

qint64 QDateTime::msecsTo ( const QDateTime other) const

Returns the number of milliseconds from this datetime to the other datetime.

If the other datetime is earlier than this datetime, the value returned is negative.

Before performing the comparison, the two datetimes are converted to Qt::UTC to ensure that the result is correct if daylight-saving (DST) applies to one of the two datetimes and but not the other.

Returns 0 if either datetime is invalid.

See also
addMSecs(), daysTo(), QTime::msecsTo()

Definition at line 4484 of file qdatetime.cpp.

References isValid(), other(), and toMSecsSinceEpoch().

Referenced by QQmlJS::Dom::DomEnvironment::finishLoadingDependencies(), QLockFilePrivate::isApparentlyStale(), msecsTo(), QDirSortItemComparator::operator()(), and secsTo().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ offsetFromUtc()

int QDateTime::offsetFromUtc ( ) const
Since
5.2

Returns this datetime's Offset From UTC in seconds.

The result depends on timeSpec(): \list

For the last two, the offset at this date and time will be returned, taking 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).

See also
setOffsetFromUtc()

Definition at line 3712 of file qdatetime.cpp.

References getMSecs(), getSpec(), isValid(), Qt::LocalTime, QtPrivate::DateTimeConstants::MSECS_PER_SEC, Q_ASSERT, toMSecsSinceEpoch(), and Qt::UTC.

Referenced by QCalendarBackend::dateTimeToString().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ operator+=()

QDateTime & QDateTime::operator+= ( std::chrono::milliseconds  duration)
inline
Since
6.4

Modifies this datetime object by adding the given duration. The updated object will be later if 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.

See also
addMSecs()

Definition at line 498 of file qdatetime.h.

◆ operator-=()

QDateTime & QDateTime::operator-= ( std::chrono::milliseconds  duration)
inline
Since
6.4

Modifies this datetime object by subtracting the given duration. The updated object will be earlier if 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.

See also
addMSecs

Definition at line 509 of file qdatetime.h.

◆ operator=()

QDateTime & QDateTime::operator= ( const QDateTime other)
noexcept

Copies the other datetime into this and returns this copy.

Definition at line 3566 of file qdatetime.cpp.

References d, and other().

+ Here is the call graph for this function:

◆ secsTo()

qint64 QDateTime::secsTo ( const QDateTime other) const

Returns the number of seconds from this datetime to the other datetime.

If the other datetime is earlier than this datetime, the value returned is negative.

Before performing the comparison, the two datetimes are converted to Qt::UTC to ensure that the result is correct if daylight-saving (DST) applies to one of the two datetimes but not the other.

Returns 0 if either datetime is invalid.

Example:

QDateTime xmas(QDate(now.date().year(), 12, 25).startOfDay());
qDebug("There are %d seconds to Christmas", now.secsTo(xmas));
static QDateTime currentDateTime()
This is an overloaded member function, provided for convenience. It differs from the above function o...
QDateTime startOfDay(const QTimeZone &zone) const
QDateTime xmas(QDate(now.date().year(), 12, 25).startOfDay())
See also
addSecs(), daysTo(), QTime::secsTo()

Definition at line 4465 of file qdatetime.cpp.

References QtPrivate::DateTimeConstants::MSECS_PER_SEC, msecsTo(), and other().

Referenced by QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setDate()

void QDateTime::setDate ( QDate  date)

Sets the date part of this datetime to date.

If no time is set yet, it is set to midnight. If date is invalid, this QDateTime becomes invalid.

See also
date(), setTime(), setTimeZone()

Definition at line 3823 of file qdatetime.cpp.

References checkValidDateTime(), date(), setDateTime(), and time().

+ Here is the call graph for this function:

◆ setMSecsSinceEpoch()

void QDateTime::setMSecsSinceEpoch ( qint64  msecs)
Since
4.7

Sets the datetime to represent a moment a given number, 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 qint64 ({std::numeric_limits<qint64>::min()}) to msecs will result in undefined behavior.

See also
setSecsSinceEpoch(), toMSecsSinceEpoch(), fromMSecsSinceEpoch()

Definition at line 4000 of file qdatetime.cpp.

References QDateTimePrivate::DaylightTime, QDateTimePrivate::expressUtcAsLocal(), extractSpec(), getStatus(), QTimeZonePrivate::invalidSeconds(), QTimeZone::isUtcOrFixedOffset(), Qt::LocalTime, mergeDaylightStatus(), QtPrivate::DateTimeConstants::MSECS_PER_SEC, msecsCanBeSmall(), Qt::OffsetFromUTC, Q_ASSERT, Q_LIKELY, Q_UNLIKELY, qAddOverflow(), QtPrivate::DateTimeConstants::SECS_PER_DAY, specCanBeSmall(), QDateTimePrivate::StandardTime, state, Qt::TimeZone, QDateTimePrivate::ValidDateTime, and QDateTimePrivate::ValidityMask.

Referenced by addMSecs(), fromMSecsSinceEpoch(), and setSecsSinceEpoch().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setSecsSinceEpoch()

void QDateTime::setSecsSinceEpoch ( qint64  secs)
Since
5.8

Sets the datetime to represent a moment a given number, secs, 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.

See also
setMSecsSinceEpoch(), toSecsSinceEpoch(), fromSecsSinceEpoch()

Definition at line 4062 of file qdatetime.cpp.

References qMulOverflow(), setMSecsSinceEpoch(), and QDateTimePrivate::ValidityMask.

Referenced by fromSecsSinceEpoch().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setTime()

void QDateTime::setTime ( QTime  time)

Sets the time part of this datetime to time.

If time is not valid, this function sets it to midnight. Therefore, it's possible to clear any set time in a QDateTime by setting it to a default QTime:

dt.setTime(QTime());
void setTime(QTime time)
Sets the time part of this datetime to time.
See also
time(), setDate(), setTimeZone()

Definition at line 3842 of file qdatetime.cpp.

References checkValidDateTime(), date(), setDateTime(), and time().

Referenced by jobHoldToString(), operator-(), and QCUPSSupport::parseJobHoldUntil().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setTimeZone()

void QDateTime::setTimeZone ( const QTimeZone toZone)
Since
5.2

Sets the time zone used in this datetime to toZone.

The datetime may refer to a different point in time. It uses the time representation of toZone, which may change the meaning of its unchanged date() and time().

If toZone is invalid then the datetime will be invalid. Otherwise, this datetime's timeSpec() after the call will match {toZone.timeSpec()}.

See also
timeRepresentation(), timeZone(), Qt::TimeSpec

Definition at line 3909 of file qdatetime.cpp.

References reviseTimeZone().

Referenced by QNetworkHeadersPrivate::fromHttpDate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ swap()

void QDateTime::swap ( QDateTime other)
inlinenoexcept
Since
5.0

Swaps this datetime with other. This operation is very fast and never fails.

Definition at line 326 of file qdatetime.h.

References d, and other().

+ Here is the call graph for this function:

◆ time()

◆ timeRepresentation()

QTimeZone QDateTime::timeRepresentation ( ) const
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.

See also
timeZone(), setTimeZone(), QTimeZone::asBackendZone()

Definition at line 3663 of file qdatetime.cpp.

Referenced by QDateTimeEdit::setDateTime(), and toTimeZone().

+ Here is the caller graph for this function:

◆ timeSpec()

Qt::TimeSpec QDateTime::timeSpec ( ) const

Returns the time specification of the datetime.

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 {timeRepresentation().timeSpec()}.

See also
setTimeSpec(), timeRepresentation(), date(), time()

Definition at line 3644 of file qdatetime.cpp.

References getSpec().

Referenced by macValue(), operator<<(), and QDateTimeParser::skipToNextSection().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ timeZoneAbbreviation()

QString QDateTime::timeZoneAbbreviation ( ) const
Since
5.2

Returns the Time Zone Abbreviation for this datetime.

The returned string depends on timeSpec():

\list

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.
See also
timeSpec(), QTimeZone::abbreviation()

Definition at line 3751 of file qdatetime.cpp.

References extractDaylightStatus(), getMSecs(), getSpec(), getStatus(), Qt::ISODate, isValid(), QDateTimePrivate::localNameAtMillis(), Qt::LocalTime, Qt::OffsetFromUTC, Q_ASSERT, Qt::TimeZone, toOffsetString(), and Qt::UTC.

Referenced by QCalendarBackend::dateTimeToString().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toLocalTime()

QDateTime QDateTime::toLocalTime ( ) const

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:

QDateTime local(UTC.toLocalTime());
qDebug() << "UTC time is:" << UTC;
qDebug() << "Local time is:" << local;
qDebug() << "No difference between times:" << UTC.secsTo(local);
static QDateTime currentDateTimeUtc()
static double UTC(double t, double localTZA)
See also
toTimeZone(), toUTC(), toOffsetFromUtc()

Definition at line 4617 of file qdatetime.cpp.

References QTimeZone::LocalTime, and toTimeZone().

Referenced by dateTimeToTime(), operator<<(), and QCUPSSupport::parseJobHoldUntil().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toMSecsSinceEpoch()

qint64 QDateTime::toMSecsSinceEpoch ( ) const
Since
4.7

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.

The behavior for this function is undefined if the datetime stored in this object is not valid. However, for all valid dates, this function returns a unique value.

See also
toSecsSinceEpoch(), setMSecsSinceEpoch(), fromMSecsSinceEpoch()

Definition at line 3929 of file qdatetime.cpp.

References extractDaylightStatus(), getMSecs(), getSpec(), getStatus(), QDateTimePrivate::localStateAtMillis(), Qt::LocalTime, QtPrivate::DateTimeConstants::MSECS_PER_SEC, Qt::OffsetFromUTC, Q_ASSERT, state, Qt::TimeZone, and Qt::UTC.

Referenced by addMSecs(), currentTime(), QV4::DateObject::dateTimeToString(), QDateTimeEditPrivate::dateTimeValue(), QNetworkDiskCache::expire(), isDaylightTime(), msecsTo(), offsetFromUtc(), ParseString(), QFileSystemEngine::setFileTime(), toSecsSinceEpoch(), toTimeZone(), QV4::ExecutableCompilationUnit::verifyHeader(), and RCCFileInfo::writeDataInfo().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toOffsetFromUtc()

QDateTime QDateTime::toOffsetFromUtc ( int  offsetSeconds) const
Since
5.2

Returns a copy of this datetime converted to a spec of Qt::OffsetFromUTC with the given offsetSeconds. Equivalent to {toTimeZone(QTimeZone::fromSecondsAheadOfUtc(offsetSeconds))}.

If the 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.

See also
setOffsetFromUtc(), offsetFromUtc(), toTimeZone()

Definition at line 4601 of file qdatetime.cpp.

References QTimeZone::fromSecondsAheadOfUtc(), and toTimeZone().

Referenced by QCalendarBackend::dateTimeToString().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toSecsSinceEpoch()

qint64 QDateTime::toSecsSinceEpoch ( ) const
Since
5.8

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.

The behavior for this function is undefined if the datetime stored in this object is not valid. However, for all valid dates, this function returns a unique value.

See also
toMSecsSinceEpoch(), fromSecsSinceEpoch(), setSecsSinceEpoch()

Definition at line 3980 of file qdatetime.cpp.

References QtPrivate::DateTimeConstants::MSECS_PER_SEC, and toMSecsSinceEpoch().

Referenced by QPixmap::load(), and QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toTimeZone()

QDateTime QDateTime::toTimeZone ( const QTimeZone timeZone) const
Since
5.2

Returns a copy of this datetime converted to the given timeZone.

The result represents the same moment in time as, and is equal to, this datetime.

The result describes the moment in time in terms of timeZone's time representation. For example:

QDateTime UTC(local.toTimeSpec(QTimeZone::UTC));
qDebug() << "Local time is:" << local;
qDebug() << "UTC time is:" << UTC;
qDebug() << "No difference between times represented:" << local.secsTo(UTC);

If timeZone is invalid then the datetime will be invalid. Otherwise the returned datetime's timeSpec() will match {timeZone.timeSpec()}.

See also
timeRepresentation(), toLocalTime(), toUTC(), toOffsetFromUtc()

Definition at line 4656 of file qdatetime.cpp.

References fromMSecsSinceEpoch(), isValid(), ret, timeRepresentation(), and toMSecsSinceEpoch().

Referenced by QDateTimeEditPrivate::convertTimeZone(), QFileInfo::fileTime(), QDateTimeEdit::setDateTimeRange(), QDateTimeEdit::setMaximumDateTime(), QDateTimeEdit::setMinimumDateTime(), QDateTimeEditPrivate::stepBy(), ToDateTime(), toLocalTime(), toOffsetFromUtc(), toUTC(), QDateTimeEditPrivate::updateTimeZone(), and QDateTimeEditPrivate::validateAndInterpret().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toUTC()

QDateTime QDateTime::toUTC ( ) const

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:

QDateTime UTC(local.toUTC());
qDebug() << "Local time is:" << local;
qDebug() << "UTC time is:" << UTC;
qDebug() << "No difference between times:" << local.secsTo(UTC);
See also
toTimeZone(), toLocalTime(), toOffsetFromUtc()

Definition at line 4633 of file qdatetime.cpp.

References toTimeZone(), and QTimeZone::UTC.

Referenced by QCtfLibImpl::QCtfLibImpl(), QV4::DateObject::dateTimeToDate(), QPSQLDriver::formatValue(), jobHoldToString(), operator<<(), QNetworkCookie::operator==(), QNetworkHeadersPrivate::toHttpDate(), and QNetworkCookie::toRawForm().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Friends And Related Symbol Documentation

◆ operator!=

bool QDateTime::operator!= ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is different from rhs; otherwise returns false.

Two datetimes are different if either the date, the time, or the time zone components are different. Since 5.14, all invalid datetime are equal (and less than all valid datetimes).

See also
operator==()

Definition at line 527 of file qdatetime.h.

◆ operator+ [1/2]

QDateTime QDateTime::operator+ ( const QDateTime dateTime,
std::chrono::milliseconds  duration 
)
friend

Definition at line 488 of file qdatetime.h.

◆ operator+ [2/2]

QDateTime QDateTime::operator+ ( std::chrono::milliseconds  duration,
const QDateTime dateTime 
)
friend
Since
6.4

Returns a QDateTime object containing a datetime duration milliseconds later than dateTime (or earlier if duration is negative).

If dateTime is invalid, an invalid datetime will be returned.

See also
addMSecs()

Definition at line 493 of file qdatetime.h.

◆ operator- [1/2]

QDateTime QDateTime::operator- ( const QDateTime dateTime,
std::chrono::milliseconds  duration 
)
friend
Since
6.4

Returns a QDateTime object containing a datetime duration milliseconds earlier than dateTime (or later if duration is negative).

If dateTime is invalid, an invalid datetime will be returned.

See also
addMSecs()

Definition at line 504 of file qdatetime.h.

◆ operator- [2/2]

std::chrono::milliseconds QDateTime::operator- ( const QDateTime lhs,
const QDateTime rhs 
)
friend
Since
6.4

Returns the number of milliseconds between lhs and rhs. If lhs is earlier than rhs, the result will be negative.

Returns 0 if either datetime is invalid.

See also
msecsTo()

Definition at line 483 of file qdatetime.h.

◆ operator<

bool QDateTime::operator< ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is earlier than rhs; otherwise returns false.

See also
operator==()

Definition at line 528 of file qdatetime.h.

◆ operator<< [1/2]

QDataStream & operator<< ( QDataStream out,
const QDateTime dateTime 
)
friend

Writes dateTime to the out stream.

See also
{Serializing Qt Data Types}

Definition at line 5489 of file qdatetime.cpp.

◆ operator<<() [2/2]

QDataStream & operator<< ( QDataStream out,
const QDateTime dateTime 
)
related

Writes dateTime to the out stream.

See also
{Serializing Qt Data Types}

Definition at line 5489 of file qdatetime.cpp.

◆ operator<=

bool QDateTime::operator<= ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is earlier than or equal to rhs; otherwise returns false.

See also
operator==()

Definition at line 529 of file qdatetime.h.

◆ operator==

bool QDateTime::operator== ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is the same as rhs; otherwise returns false.

Two datetimes are different if either the date, the time, or the time zone components are different. Since 5.14, all invalid datetime are equal (and less than all valid datetimes).

See also
operator!=(), operator<(), operator<=(), operator>(), operator>=()

Definition at line 526 of file qdatetime.h.

◆ operator>

bool QDateTime::operator> ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is later than rhs; otherwise returns false.

See also
operator==()

Definition at line 530 of file qdatetime.h.

◆ operator>=

bool QDateTime::operator>= ( const QDateTime lhs,
const QDateTime rhs 
)
friend

Returns true if lhs is later than or equal to rhs; otherwise returns false.

See also
operator==()

Definition at line 531 of file qdatetime.h.

◆ operator>> [1/2]

QDataStream & operator>> ( QDataStream in,
QDateTime dateTime 
)
friend

Reads a datetime from the stream in into dateTime.

See also
{Serializing Qt Data Types}

Definition at line 5554 of file qdatetime.cpp.

◆ operator>>() [2/2]

QDataStream & operator>> ( QDataStream in,
QDateTime dateTime 
)
related

Reads a datetime from the stream in into dateTime.

See also
{Serializing Qt Data Types}

Definition at line 5554 of file qdatetime.cpp.

◆ QDateTimePrivate

friend class QDateTimePrivate
friend

Definition at line 522 of file qdatetime.h.


The documentation for this class was generated from the following files: