Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
QDateTime Class Reference

\inmodule QtCore\reentrant More...

#include <qdatetime.h>

+ Collaboration diagram for QDateTime:

Public Types

enum class  TransitionResolution {
  Reject = 0 , RelativeToBefore , RelativeToAfter , PreferBefore ,
  PreferAfter , PreferStandard , PreferDaylightSaving , LegacyBehavior = RelativeToBefore
}
 
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, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
 
 QDateTime (QDate date, QTime time, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
 
 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, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
 Sets the date part of this datetime to date.
 
void setTime (QTime time, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
 Sets the time part of this datetime to time.
 
void setTimeZone (const QTimeZone &toZone, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
 
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)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
static QDateTime fromSecsSinceEpoch (qint64 secs)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
static qint64 currentMSecsSinceEpoch () noexcept
 
static qint64 currentSecsSinceEpoch () noexcept
 
static QDateTime fromStdTimePoint (std::chrono::time_point< std::chrono::system_clock, std::chrono::milliseconds > time)
 

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 comparesEqual (const QDateTime &lhs, const QDateTime &rhs)
 
Q_CORE_EXPORT Qt::weak_ordering compareThreeWay (const QDateTime &lhs, const QDateTime &rhs)
 
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.
 

Detailed Description

\inmodule QtCore

\reentrant

The QDateTime class provides date and time functions.

\compares weak

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

Definition at line 289 of file qdatetime.h.

Member Enumeration Documentation

◆ TransitionResolution

Since
6.7

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 RelativeToBefore if adding a positive adjustment and 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 resolve determine which actual time on the given date is selected. First, the common case of positive daylight-saving, where:

\table \header

  • Before
  • 02:00–03:00
  • After
  • resolve
  • selected \row
  • LST
  • skip
  • LDT
  • RelativeToBefore
  • 03:30 LDT \row
  • LST
  • skip
  • LDT
  • RelativeToAfter
  • 01:30 LST \row
  • LST
  • skip
  • LDT
  • PreferBefore
  • 01:30 LST \row
  • LST
  • skip
  • LDT
  • PreferAfter
  • 03:30 LDT \row
  • LST
  • skip
  • LDT
  • PreferStandard
  • 01:30 LST \row
  • LST
  • skip
  • LDT
  • PreferDaylightSaving
  • 03:30 LDT \row
  • LDT
  • repeat
  • LST
  • RelativeToBefore
  • 02:30 LDT \row
  • LDT
  • repeat
  • LST
  • RelativeToAfter
  • 02:30 LST \row
  • LDT
  • repeat
  • LST
  • PreferBefore
  • 02:30 LDT \row
  • LDT
  • repeat
  • LST
  • PreferAfter
  • 02:30 LST \row
  • LDT
  • repeat
  • LST
  • PreferStandard
  • 02:30 LST \row
  • LDT
  • repeat
  • LST
  • PreferDaylightSaving
  • 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

  • LDT
  • skip
  • LST
  • RelativeToBefore
  • 03:30 LST \row
  • LDT
  • skip
  • LST
  • RelativeToAfter
  • 01:30 LDT \row
  • LDT
  • skip
  • LST
  • PreferBefore
  • 01:30 LDT \row
  • LDT
  • skip
  • LST
  • PreferAfter
  • 03:30 LST \row
  • LDT
  • skip
  • LST
  • PreferStandard
  • 03:30 LST \row
  • LDT
  • skip
  • LST
  • PreferDaylightSaving
  • 01:30 LDT \row
  • LST
  • repeat
  • LDT
  • RelativeToBefore
  • 02:30 LST \row
  • LST
  • repeat
  • LDT
  • RelativeToAfter
  • 02:30 LDT \row
  • LST
  • repeat
  • LDT
  • PreferBefore
  • 02:30 LST \row
  • LST
  • repeat
  • LDT
  • PreferAfter
  • 02:30 LDT \row
  • LST
  • repeat
  • LDT
  • PreferStandard
  • 02:30 LST \row
  • LST
  • repeat
  • LDT
  • PreferDaylightSaving
  • 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.
Enumerator
Reject 
RelativeToBefore 
RelativeToAfter 
PreferBefore 
PreferAfter 
PreferStandard 
PreferDaylightSaving 
LegacyBehavior 

Definition at line 348 of file qdatetime.h.

◆ 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 623 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 3950 of file qdatetime.cpp.

◆ QDateTime() [2/5]

QDateTime::QDateTime ( QDate date,
QTime time,
const QTimeZone & timeZone,
TransitionResolution resolve = TransitionResolution::LegacyBehavior )
\since 5.2

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

! [pre-resolve-note]

Note
Prior to Qt 6.7, the version of this function lacked the resolve parameter so had no way to resolve the ambiguities related to transitions. ! [pre-resolve-note]

Definition at line 4004 of file qdatetime.cpp.

◆ QDateTime() [3/5]

QDateTime::QDateTime ( QDate date,
QTime time,
TransitionResolution resolve = TransitionResolution::LegacyBehavior )
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.

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. If date and time describe a moment close to a transition for local time, resolve controls how that situation is resolved.

pre-resolve-note

Definition at line 4022 of file qdatetime.cpp.

◆ QDateTime() [4/5]

QDateTime::QDateTime ( const QDateTime & other)
noexcept

Constructs a copy of the other datetime.

Definition at line 4030 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 4040 of file qdatetime.cpp.

◆ ~QDateTime()

QDateTime::~QDateTime ( )

Destroys the datetime.

Definition at line 4048 of file qdatetime.cpp.

Member Function Documentation

◆ addDays()

QDateTime QDateTime::addDays ( qint64 ndays) const
nodiscard

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 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 {ndays < 0}) or after 3am (otherwise).

See also
daysTo(), addMonths(), addYears(), addSecs(), {Timezone transitions}

Definition at line 4806 of file qdatetime.cpp.

◆ addDuration()

QDateTime QDateTime::addDuration ( std::chrono::milliseconds msecs) const
inlinenodiscard
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 432 of file qdatetime.h.

◆ addMonths()

QDateTime QDateTime::addMonths ( int nmonths) const
nodiscard

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 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 {nmonths < 0}) or after 3am (otherwise).

See also
daysTo(), addDays(), addYears(), addSecs(), {Timezone transitions}

Definition at line 4832 of file qdatetime.cpp.

◆ addMSecs()

QDateTime QDateTime::addMSecs ( qint64 msecs) const
nodiscard

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 4896 of file qdatetime.cpp.

◆ addSecs()

QDateTime QDateTime::addSecs ( qint64 s) const
nodiscard

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 4879 of file qdatetime.cpp.

◆ addYears()

QDateTime QDateTime::addYears ( int nyears) const
nodiscard

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 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 {nyears < 0}) or after 3am (otherwise).

See also
daysTo(), addDays(), addMonths(), addSecs(), {Timezone transitions}

Definition at line 4858 of file qdatetime.cpp.

◆ 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 5316 of file qdatetime.cpp.

◆ currentDateTime() [2/2]

static 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
Since
4.7 Returns the system clock's current datetime, expressed in terms of UTC.

Equivalent to {currentDateTime(QTimeZone::UTC)}.

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

Definition at line 5331 of file qdatetime.cpp.

◆ currentMSecsSinceEpoch()

static 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()

◆ currentSecsSinceEpoch()

static 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()

◆ date()

QDate QDateTime::date ( ) const

Returns the date part of the datetime.

See also
setDate(), time(), timeRepresentation()

Definition at line 4105 of file qdatetime.cpp.

◆ 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);
See also
addDays(), secsTo(), msecsTo()

Definition at line 4963 of file qdatetime.cpp.

◆ fromMSecsSinceEpoch() [1/2]

QDateTime QDateTime::fromMSecsSinceEpoch ( qint64 msecs)
static

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 5642 of file qdatetime.cpp.

◆ fromMSecsSinceEpoch() [2/2]

QDateTime QDateTime::fromMSecsSinceEpoch ( qint64 msecs,
const QTimeZone & timeZone )
static
Since
5.2

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 5630 of file qdatetime.cpp.

◆ fromSecsSinceEpoch() [1/2]

QDateTime QDateTime::fromSecsSinceEpoch ( qint64 secs)
static

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 5672 of file qdatetime.cpp.

◆ fromSecsSinceEpoch() [2/2]

QDateTime QDateTime::fromSecsSinceEpoch ( qint64 secs,
const QTimeZone & timeZone )
static
Since
5.8

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 5660 of file qdatetime.cpp.

◆ fromStdTimePoint()

QDateTime QDateTime::fromStdTimePoint ( std::chrono::time_point< std::chrono::system_clock, std::chrono::milliseconds > time)
static
Since
6.4

Constructs a datetime representing the same point in time as time, using Qt::UTC as its time representation.

The clock of time must be compatible with {std::chrono::system_clock}; in particular, a conversion supported by {std::chrono::clock_cast} must exist. After the conversion, the duration type of the result must be convertible to {std::chrono::milliseconds}.

If this is not the case, the caller must perform the necessary clock conversion towards {std::chrono::system_clock} and the necessary conversion of the duration type (cast/round/floor/ceil/...) so that the input to this function satisfies the constraints above.

Note
This function requires C++20.
See also
toStdSysMilliseconds(), fromMSecsSinceEpoch()
Since
6.4 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Constructs a datetime representing the same point in time as time, using Qt::UTC as its time representation.

Since
6.4

Constructs a datetime whose date and time are the number of milliseconds represented by time, counted since 1970-01-01T00:00:00.000 in local time (Qt::LocalTime).

Note
This function requires C++20.
See also
toStdSysMilliseconds(), fromMSecsSinceEpoch()

Definition at line 5390 of file qdatetime.cpp.

◆ 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 4282 of file qdatetime.cpp.

◆ 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 4074 of file qdatetime.cpp.

◆ 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 4094 of file qdatetime.cpp.

◆ 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 5004 of file qdatetime.cpp.

◆ 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 4200 of file qdatetime.cpp.

◆ 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 604 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 615 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 4056 of file qdatetime.cpp.

◆ 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));
See also
addSecs(), daysTo(), QTime::secsTo()

Definition at line 4985 of file qdatetime.cpp.

◆ setDate()

void QDateTime::setDate ( QDate date,
TransitionResolution resolve = TransitionResolution::LegacyBehavior )

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.

If date and time() describe a moment close to a transition for this datetime's time representation, resolve controls how that situation is resolved.

pre-resolve-note

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

Definition at line 4329 of file qdatetime.cpp.

◆ 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 4524 of file qdatetime.cpp.

◆ 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 4586 of file qdatetime.cpp.

◆ setTime()

void QDateTime::setTime ( QTime time,
TransitionResolution resolve = TransitionResolution::LegacyBehavior )

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());
\inmodule QtCore\reentrant
Definition qdatetime.h:290
static QDateTime currentDateTime()
This is an overloaded member function, provided for convenience. It differs from the above function o...
void setTime(QTime time, TransitionResolution resolve=TransitionResolution::LegacyBehavior)
Sets the time part of this datetime to time.
\inmodule QtCore \reentrant
Definition qdatetime.h:222

If date() and time describe a moment close to a transition for this datetime's time representation, resolve controls how that situation is resolved.

pre-resolve-note

See also
time(), setDate(), setTimeZone()

Definition at line 4354 of file qdatetime.cpp.

◆ setTimeZone()

void QDateTime::setTimeZone ( const QTimeZone & toZone,
TransitionResolution resolve = TransitionResolution::LegacyBehavior )
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()}.

If date() and time() describe a moment close to a transition for toZone, resolve controls how that situation is resolved.

pre-resolve-note

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

Definition at line 4428 of file qdatetime.cpp.

◆ swap()

void QDateTime::swap ( QDateTime & other)
inlinenoexcept
Since
5.0 \memberswap{datetime}

Definition at line 379 of file qdatetime.h.

◆ time()

QTime QDateTime::time ( ) const

Returns the time part of the datetime.

See also
setTime(), date(), timeRepresentation()

Definition at line 4116 of file qdatetime.cpp.

◆ 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 4151 of file qdatetime.cpp.

◆ 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 4132 of file qdatetime.cpp.

◆ 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 4241 of file qdatetime.cpp.

◆ 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);
See also
toTimeZone(), toUTC(), toOffsetFromUtc()

Definition at line 5137 of file qdatetime.cpp.

◆ 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 4448 of file qdatetime.cpp.

◆ 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 5121 of file qdatetime.cpp.

◆ 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 4504 of file qdatetime.cpp.

◆ 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);
\inmodule QtCore\reentrant
Definition qdatetime.h:290
static QDateTime currentDateTime()
This is an overloaded member function, provided for convenience. It differs from the above function o...
static QDateTime currentDateTimeUtc()
qint64 daysTo(const QDateTime &) const
Returns the number of days from this datetime to the other datetime.
qint64 daysTo(QDate d) const
Returns the number of days from this date to d (which is negative if d is earlier than this date).
QDateTime startOfDay(const QTimeZone &zone) const
constexpr bool isValid() const
Returns true if this date is valid; otherwise returns false.
Definition qdatetime.h:72
\inmodule QtCore \reentrant
Definition qdatetime.h:222
bool isValid() const
Returns true if the time is valid; otherwise returns false.
QTime addSecs(int secs) const
Returns a QTime object containing a time s seconds later than the time of this object (or earlier if ...
QDate date
[1]
@ UTC
@ Monday
QT_BEGIN_NAMESPACE constexpr void qSwap(T &value1, T &value2) noexcept(std::is_nothrow_swappable_v< T >)
Definition qswap.h:20
static double UTC(double t, double localTZA)
QDateTime dateTime
[12]
QDateTime startDate(QDate(2012, 7, 6), QTime(8, 30, 0))
[14]
QDateTime dateTime2
QDate d1(1995, 5, 17)
[0]
QDate d2(1995, 5, 20)
QDateTime endDate(QDate(2012, 7, 7), QTime(16, 30, 0))
QTime time1
[11]
QDateTime xmas(QDate(now.date().year(), 12, 25).startOfDay())

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 5176 of file qdatetime.cpp.

◆ 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 5153 of file qdatetime.cpp.

Friends And Related Symbol Documentation

◆ comparesEqual

bool comparesEqual ( const QDateTime & lhs,
const QDateTime & rhs )
friend

Definition at line 634 of file qdatetime.h.

◆ compareThreeWay

Q_CORE_EXPORT Qt::weak_ordering compareThreeWay ( const QDateTime & lhs,
const QDateTime & rhs )
friend

Definition at line 5244 of file qdatetime.cpp.

◆ operator+ [1/2]

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

Definition at line 594 of file qdatetime.h.

◆ operator+ [2/2]

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 599 of file qdatetime.h.

◆ operator- [1/2]

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 610 of file qdatetime.h.

◆ operator- [2/2]

std::chrono::milliseconds 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 589 of file qdatetime.h.

◆ operator<<

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

Writes dateTime to the out stream.

See also
{Serializing Qt Data Types}

Definition at line 6081 of file qdatetime.cpp.

◆ operator>>

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 6146 of file qdatetime.cpp.

◆ QDateTimePrivate

friend class QDateTimePrivate
friend

Definition at line 630 of file qdatetime.h.


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