QDateTime Class

The QDateTime class provides date and time functions. More...

Header: #include <QDateTime>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

enum class YearRange { First, Last }

Public Functions

QDateTime()
QDateTime(QDate date, QTime time, const QTimeZone &timeZone)
QDateTime(QDate date, QTime time)
QDateTime(const QDateTime &other)
QDateTime(QDateTime &&other)
~QDateTime()
QDateTime addDays(qint64 ndays) const
QDateTime addDuration(std::chrono::milliseconds msecs) const
QDateTime addMSecs(qint64 msecs) const
QDateTime addMonths(int nmonths) const
QDateTime addSecs(qint64 s) const
QDateTime addYears(int nyears) const
QDate date() const
qint64 daysTo(const QDateTime &other) const
bool isDaylightTime() const
bool isNull() const
bool isValid() const
qint64 msecsTo(const QDateTime &other) const
int offsetFromUtc() const
qint64 secsTo(const QDateTime &other) const
void setDate(QDate date)
void setMSecsSinceEpoch(qint64 msecs)
void setSecsSinceEpoch(qint64 secs)
void setTime(QTime time)
void setTimeZone(const QTimeZone &toZone)
void swap(QDateTime &other)
QTime time() const
QTimeZone timeRepresentation() const
Qt::TimeSpec timeSpec() const
QTimeZone timeZone() const
QString timeZoneAbbreviation() const
CFDateRef toCFDate() const
QDateTime toLocalTime() const
qint64 toMSecsSinceEpoch() const
NSDate *toNSDate() const
QDateTime toOffsetFromUtc(int offsetSeconds) const
qint64 toSecsSinceEpoch() const
std::chrono::sys_time<std::chrono::milliseconds> toStdSysMilliseconds() const
std::chrono::sys_seconds toStdSysSeconds() const
QString toString(const QString &format, QCalendar cal = QCalendar()) const
QString toString(Qt::DateFormat format = Qt::TextDate) const
QString toString(QStringView format, QCalendar cal = QCalendar()) const
QDateTime toTimeZone(const QTimeZone &timeZone) const
QDateTime toUTC() const
QDateTime &operator+=(std::chrono::milliseconds duration)
QDateTime &operator-=(std::chrono::milliseconds duration)
QDateTime &operator=(const QDateTime &other)

Static Public Members

QDateTime currentDateTime(const QTimeZone &zone)
QDateTime currentDateTime()
QDateTime currentDateTimeUtc()
qint64 currentMSecsSinceEpoch()
qint64 currentSecsSinceEpoch()
QDateTime fromCFDate(CFDateRef date)
QDateTime fromMSecsSinceEpoch(qint64 msecs, const QTimeZone &timeZone)
QDateTime fromMSecsSinceEpoch(qint64 msecs)
QDateTime fromNSDate(const NSDate *date)
QDateTime fromSecsSinceEpoch(qint64 secs, const QTimeZone &timeZone)
QDateTime fromSecsSinceEpoch(qint64 secs)
QDateTime fromStdLocalTime(const std::chrono::local_time<std::chrono::milliseconds> &time)
QDateTime fromStdTimePoint(const std::chrono::time_point<Clock, Duration> &time)
QDateTime fromStdTimePoint(const std::chrono::local_time<std::chrono::milliseconds> &time)
QDateTime fromStdZonedTime(const int &time)
QDateTime fromString(const QString &string, Qt::DateFormat format = Qt::TextDate)
QDateTime fromString(QStringView string, Qt::DateFormat format = Qt::TextDate)
QDateTime fromString(QStringView string, QStringView format, QCalendar cal = QCalendar())
QDateTime fromString(const QString &string, QStringView format, QCalendar cal = QCalendar())
QDateTime fromString(const QString &string, const QString &format, QCalendar cal = QCalendar())
bool 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)
std::chrono::milliseconds operator-(const QDateTime &lhs, const QDateTime &rhs)
QDateTime operator-(const QDateTime &dateTime, std::chrono::milliseconds duration)
bool operator<(const QDateTime &lhs, const QDateTime &rhs)
QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
bool operator<=(const QDateTime &lhs, const QDateTime &rhs)
bool operator==(const QDateTime &lhs, const QDateTime &rhs)
bool operator>(const QDateTime &lhs, const QDateTime &rhs)
bool operator>=(const QDateTime &lhs, const QDateTime &rhs)
QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)

Detailed Description

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 local time, to UTC, to a specified offset from UTC or to a specified 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 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 timeSpec() is Qt::TimeZone) to use that instead.

Note: QDateTime does not account for leap seconds.

Remarks

Note: All conversion to and from string formats is done using the C locale. For localized conversions, see QLocale.

Note: There is no year 0 in the Gregorian calendar. Dates in that year are considered invalid. The year -1 is the year "1 before Christ" or "1 before common era." The day before 1 January 1 CE is 31 December 1 BCE.

Range of Valid Dates

The range of values that QDateTime can represent is dependent on the internal storage implementation. QDateTime is currently stored in a qint64 as a serial msecs value encoding the date and time. This restricts the date range to about +/- 292 million years, compared to the QDate range of +/- 2 billion years. Care must be taken when creating a QDateTime with extreme values that you do not overflow the storage. The exact range of supported values varies depending on the time representation used.

Use of Timezones

QDateTime uses the system's time zone information to determine the current local time zone and its offset from UTC. If the system is not configured correctly or not up-to-date, QDateTime will give wrong results.

QDateTime likewise uses system-provided information to determine the offsets of other timezones from UTC. If this information is incomplete or out of date, QDateTime will give wrong results. See the QTimeZone documentation for more details.

On modern Unix systems, this means QDateTime usually has accurate information about historical transitions (including DST, see below) whenever possible. On Windows, where the system doesn't support historical timezone data, historical accuracy is not maintained with respect to timezone transitions, notably including DST. However, building Qt with the ICU library will equipe QTimeZone with the same timezone database as is used on Unix.

Daylight-Saving Time (DST)

QDateTime takes into account transitions between Standard Time and Daylight-Saving Time. For example, if the transition is at 2am and the clock goes forward to 3am, then there is a "missing" hour from 02:00:00 to 02:59:59.999 which QDateTime considers to be invalid. Any date arithmetic performed will take this missing hour into account and return a valid result. For example, adding one second to 01:59:59 will get 03:00:00.

For datetimes that the system time_t can represent (from 1901-12-14 to 2038-01-18 on systems with 32-bit time_t; for the full range QDateTime can represent if the type is 64-bit), the standard system APIs are used to determine local time's offset from UTC. For datetimes not handled by these system APIs, QTimeZone::systemTimeZone() is used. In either case, the offset information used depends on the system and may be incomplete or, for past times, historically inaccurate. In any case, for future dates, the local time zone's offsets and DST rules may change before that date comes around.

Offsets From UTC

Offsets from UTC are measured in seconds east of Greenwich. The moment described by a particular date and time, such as noon on a particular day, depends on the time representation used. Those with a higher offset from UTC describe an earlier moment, and those with a lower offset a later moment, by any given combination of date and time.

There is no explicit size restriction on an offset from UTC, but there is an implicit limit imposed when using the toString() and fromString() methods which use a [+|-]hh:mm format, effectively limiting the range to +/- 99 hours and 59 minutes and whole minutes only. Note that currently no time zone has an offset outside the range of ±14 hours and all known offsets are multiples of five minutes.

See also QDate, QTime, QDateTimeEdit, and QTimeZone.

Member Type Documentation

enum class QDateTime::YearRange

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

ConstantValueDescription
QDateTime::YearRange::First-292275056The later parts of this year are representable
QDateTime::YearRange::Last+292278994The 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() and QDate.

Member Function Documentation

QString QDateTime::toString(QStringView format, QCalendar cal = QCalendar()) const

QString QDateTime::toString(const QString &format, QCalendar cal = QCalendar()) const

Returns the datetime as a string. The format parameter determines the format of the result string. If cal is supplied, it determines the calendar used to represent the date; it defaults to Gregorian. Prior to Qt 5.14, there was no cal parameter and the Gregorian calendar was always used. See QTime::toString() and QDate::toString() for the supported specifiers for time and date, respectively, in the format parameter.

Any sequence of characters enclosed in single quotes will be included verbatim in the output string (stripped of the quotes), even if it contains formatting characters. Two consecutive single quotes ("''") are replaced by a single quote in the output. All other characters in the format string are included verbatim in the output string.

Formats without separators (e.g. "ddMM") are supported but must be used with care, as the resulting strings aren't always reliably readable (e.g. if "dM" produces "212" it could mean either the 2nd of December or the 21st of February).

Example format strings (assumed that the QDateTime is 21 May 2001 14:13:09.120):

FormatResult
dd.MM.yyyy21.05.2001
ddd MMMM d yyTue May 21 01
hh:mm:ss.zzz14:13:09.120
hh:mm:ss.z14:13:09.12
h:m:s ap2:13:9 pm

If the datetime is invalid, an empty string will be returned.

Note: Day and month names as well as AM/PM indicators are given in English (C locale). To get localized month and day names and localized forms of AM/PM, use QLocale::system().toDateTime().

See also fromString(), QDate::toString(), QTime::toString(), and QLocale::toString().

QDateTime::QDateTime()

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(), and setTimeZone().

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

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.

[since 6.5] QDateTime::QDateTime(QDate date, QTime time)

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.

This function was introduced in Qt 6.5.

QDateTime::QDateTime(const QDateTime &other)

Constructs a copy of the other datetime.

QDateTime::QDateTime(QDateTime &&other)

Moves the content of the temporary other datetime to this object and leaves other in an unspecified (but proper) state.

QDateTime::~QDateTime()

Destroys the datetime.

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(), and addSecs().

[since 6.4] QDateTime QDateTime::addDuration(std::chrono::milliseconds 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.

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.

This function was introduced in Qt 6.4.

See also addMSecs(), msecsTo(), addDays(), addMonths(), and addYears().

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(), and addYears().

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(), and 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(), and 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(), and addSecs().

[static, since 6.5] QDateTime QDateTime::currentDateTime(const QTimeZone &zone)

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

This function was introduced in Qt 6.5.

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

[static] QDateTime QDateTime::currentDateTime()

This is an overloaded function.

[static] QDateTime QDateTime::currentDateTimeUtc()

Returns the system clock's current datetime, expressed in terms of UTC.

Equivalent to currentDateTime(QTimeZone::UTC).

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

[static] qint64 QDateTime::currentMSecsSinceEpoch()

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(), and toTimeSpec().

[static] qint64 QDateTime::currentSecsSinceEpoch()

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

QDate QDateTime::date() const

Returns the date part of the datetime.

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

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(), and msecsTo().

[static] QDateTime QDateTime::fromCFDate(CFDateRef date)

Constructs a new QDateTime containing a copy of the CFDate date.

See also toCFDate().

[static] QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, const QTimeZone &timeZone)

This is an overloaded function.

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(), and setMSecsSinceEpoch().

[static, since 6.5] QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs)

This is an overloaded function.

This function was introduced in Qt 6.5.

[static] QDateTime QDateTime::fromNSDate(const NSDate *date)

Constructs a new QDateTime containing a copy of the NSDate date.

See also toNSDate().

[static] QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, const QTimeZone &timeZone)

This is an overloaded function.

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(), and setSecsSinceEpoch().

[static, since 6.5] QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs)

This is an overloaded function.

This function was introduced in Qt 6.5.

[static, since 6.4] QDateTime QDateTime::fromStdLocalTime(const std::chrono::local_time<std::chrono::milliseconds> &time)

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.

This function was introduced in Qt 6.4.

See also toStdSysMilliseconds() and fromMSecsSinceEpoch().

[static, since 6.4] template <typename Clock, typename Duration> QDateTime QDateTime::fromStdTimePoint(const std::chrono::time_point<Clock, Duration> &time)

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

The clock of time must be compatible with std::chrono::system_clock, and the duration type must be convertible to std::chrono::milliseconds.

Note: This function requires C++20.

This function was introduced in Qt 6.4.

See also toStdSysMilliseconds() and fromMSecsSinceEpoch().

[static, since 6.4] QDateTime QDateTime::fromStdTimePoint(const std::chrono::local_time<std::chrono::milliseconds> &time)

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.

This function was introduced in Qt 6.4.

See also toStdSysMilliseconds() and fromMSecsSinceEpoch().

[static, since 6.4] QDateTime QDateTime::fromStdZonedTime(const int &time)

Constructs a datetime representing the same point in time as time. The result will be expressed in time's time zone.

Note: This function requires C++20.

This function was introduced in Qt 6.4.

See also QTimeZone, toStdSysMilliseconds(), and fromMSecsSinceEpoch().

[static] QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format = Qt::TextDate)

Returns the QDateTime represented by the string, using the format given, or an invalid datetime if this is not possible.

Note for Qt::TextDate: only English short month names (e.g. "Jan" in short form or "January" in long form) are recognized.

See also toString() and QLocale::toDateTime().

[static, since 6.0] QDateTime QDateTime::fromString(QStringView string, Qt::DateFormat format = Qt::TextDate)

This is an overloaded function.

This function was introduced in Qt 6.0.

[static, since 6.0] QDateTime QDateTime::fromString(QStringView string, QStringView format, QCalendar cal = QCalendar())

This is an overloaded function.

This function was introduced in Qt 6.0.

[static, since 6.0] QDateTime QDateTime::fromString(const QString &string, QStringView format, QCalendar cal = QCalendar())

This is an overloaded function.

This function was introduced in Qt 6.0.

[static] QDateTime QDateTime::fromString(const QString &string, const QString &format, QCalendar cal = QCalendar())

Returns the QDateTime represented by the string, using the format given, or an invalid datetime if the string cannot be parsed.

Uses the calendar cal if supplied, else Gregorian.

In addition to the expressions, recognized in the format string to represent parts of the date and time, by QDate::fromString() and QTime::fromString(), this method supports:

ExpressionOutput
tthe timezone (offset, name, "Z" or offset with "UTC" prefix)
ttthe timezone in offset format with no colon between hours and minutes (for example "+0200")
tttthe timezone in offset format with a colon between hours and minutes (for example "+02:00")
ttttthe timezone name (for example "Europe/Berlin"). The name recognized are those known to QTimeZone, which may depend on the operating system in use.

If no 't' format specifier is present, the system's local time-zone is used. For the defaults of all other fields, see QDate::fromString() and QTime::fromString().

For example:

QDateTime dateTime = QDateTime::fromString("1.30.1", "M.d.s");
// dateTime is January 30 in 1900 at 00:00:01.
dateTime = QDateTime::fromString("12", "yy");
// dateTime is January 1 in 1912 at 00:00:00.

All other input characters will be treated as text. Any non-empty sequence of characters enclosed in single quotes will also be treated (stripped of the quotes) as text and not be interpreted as expressions.

QTime time1 = QTime::fromString("131", "HHh");
// time1 is 13:00:00
QTime time1 = QTime::fromString("1apA", "1amAM");
// time1 is 01:00:00

QDateTime dateTime2 = QDateTime::fromString("M1d1y9800:01:02",
                                            "'M'M'd'd'y'yyhh:mm:ss");
// dateTime is 1 January 1998 00:01:02

If the format is not satisfied, an invalid QDateTime is returned. If the format is satisfied but string represents an invalid datetime (e.g. in a gap skipped by a time-zone transition), an invalid QDateTime is returned, whose toMSecsSinceEpoch() represents a near-by datetime that is valid. Passing that to fromMSecsSinceEpoch() will produce a valid datetime that isn't faithfully represented by the string parsed.

The expressions that don't have leading zeroes (d, M, h, m, s, z) will be greedy. This means that they will use two digits (or three, for z) even if this will put them outside the range and/or leave too few digits for other sections.

QDateTime dateTime = QDateTime::fromString("130", "Mm"); // invalid

This could have meant 1 January 00:30.00 but the M will grab two digits.

Incorrectly specified fields of the string will cause an invalid QDateTime to be returned. For example, consider the following code, where the two digit year 12 is read as 1912 (see the table below for all field defaults); the resulting datetime is invalid because 23 April 1912 was a Tuesday, not a Monday:

QString string = "Monday, 23 April 12 22:51:41";
QString format = "dddd, d MMMM yy hh:mm:ss";
QDateTime invalid = QDateTime::fromString(string, format);

The correct code is:

QString string = "Tuesday, 23 April 12 22:51:41";
QString format = "dddd, d MMMM yy hh:mm:ss";
QDateTime valid = QDateTime::fromString(string, format);

Note: Day and month names as well as AM/PM indicators must be given in English (C locale). If localized month and day names or localized forms of AM/PM are to be recognized, use QLocale::system().toDateTime().

Note: If a format character is repeated more times than the longest expression in the table above using it, this part of the format will be read as several expressions with no separator between them; the longest above, possibly repeated as many times as there are copies of it, ending with a residue that may be a shorter expression. Thus 'tttttt' would match "Europe/BerlinEurope/Berlin" and set the zone to Berlin time; if the datetime string contained "Europe/BerlinZ" it would "match" but produce an inconsistent result, leading to an invalid datetime.

See also toString(), QDate::fromString(), QTime::fromString(), and QLocale::toDateTime().

bool QDateTime::isDaylightTime() const

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

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(), and 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(), and QTime::isValid().

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(), and QTime::msecsTo().

int QDateTime::offsetFromUtc() const

Returns this datetime's Offset From UTC in seconds.

The result depends on timeSpec():

  • Qt::UTC The offset is 0.
  • Qt::OffsetFromUTC The offset is the value originally set.
  • Qt::LocalTime The local time's offset from UTC is returned.
  • Qt::TimeZone The offset used by the time-zone is returned.

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

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 now = QDateTime::currentDateTime();
QDateTime xmas(QDate(now.date().year(), 12, 25).startOfDay());
qDebug("There are %d seconds to Christmas", now.secsTo(xmas));

See also addSecs(), daysTo(), and QTime::secsTo().

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(), and setTimeZone().

void QDateTime::setMSecsSinceEpoch(qint64 msecs)

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(), and fromMSecsSinceEpoch().

void QDateTime::setSecsSinceEpoch(qint64 secs)

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(), and fromSecsSinceEpoch().

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:

QDateTime dt = QDateTime::currentDateTime();
dt.setTime(QTime());

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

void QDateTime::setTimeZone(const QTimeZone &toZone)

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(), and Qt::TimeSpec.

void QDateTime::swap(QDateTime &other)

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

QTime QDateTime::time() const

Returns the time part of the datetime.

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

[since 6.5] QTimeZone QDateTime::timeRepresentation() const

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.

This function was introduced in Qt 6.5.

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

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(), and time().

QTimeZone QDateTime::timeZone() const

Returns the time zone of the datetime.

The result is the same as timeRepresentation().asBackendZone(). In all cases, the result's timeSpec() is Qt::TimeZone.

When timeSpec() is Qt::LocalTime, the result will describe local time at the time this method was called. It will not reflect subsequent changes to the system time zone, even when the QDateTime from which it was obtained does.

See also timeRepresentation(), setTimeZone(), Qt::TimeSpec, and QTimeZone::asBackendZone().

QString QDateTime::timeZoneAbbreviation() const

Returns the Time Zone Abbreviation for this datetime.

The returned string depends on timeSpec():

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() and QTimeZone::abbreviation().

CFDateRef QDateTime::toCFDate() const

Creates a CFDate from a QDateTime.

The caller owns the CFDate object and is responsible for releasing it.

See also fromCFDate().

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 UTC(QDateTime::currentDateTimeUtc());
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(), and toOffsetFromUtc().

qint64 QDateTime::toMSecsSinceEpoch() const

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(), and fromMSecsSinceEpoch().

NSDate *QDateTime::toNSDate() const

Creates an NSDate from a QDateTime.

The NSDate object is autoreleased.

See also fromNSDate().

QDateTime QDateTime::toOffsetFromUtc(int offsetSeconds) const

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(), and toTimeZone().

qint64 QDateTime::toSecsSinceEpoch() const

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(), and setSecsSinceEpoch().

[since 6.4] std::chrono::sys_time<std::chrono::milliseconds> QDateTime::toStdSysMilliseconds() const

Converts this datetime object to the equivalent time point expressed in milliseconds, using std::chrono::system_clock as a clock.

Note: This function requires C++20.

This function was introduced in Qt 6.4.

See also fromStdTimePoint() and toMSecsSinceEpoch().

[since 6.4] std::chrono::sys_seconds QDateTime::toStdSysSeconds() const

Converts this datetime object to the equivalent time point expressed in seconds, using std::chrono::system_clock as a clock.

Note: This function requires C++20.

This function was introduced in Qt 6.4.

See also fromStdTimePoint() and toSecsSinceEpoch().

QString QDateTime::toString(Qt::DateFormat format = Qt::TextDate) const

This is an overloaded function.

Returns the datetime as a string in the format given.

If the format is Qt::TextDate, the string is formatted in the default way. The day and month names will be in English. An example of this formatting is "Wed May 20 03:40:13 1998". For localized formatting, see QLocale::toString().

If the format is Qt::ISODate, the string format corresponds to the ISO 8601 extended specification for representations of dates and times, taking the form yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm], depending on the timeSpec() of the QDateTime. If the timeSpec() is Qt::UTC, Z will be appended to the string; if the timeSpec() is Qt::OffsetFromUTC, the offset in hours and minutes from UTC will be appended to the string. To include milliseconds in the ISO 8601 date, use the format Qt::ISODateWithMs, which corresponds to yyyy-MM-ddTHH:mm:ss.zzz[Z|[+|-]HH:mm].

If the format is Qt::RFC2822Date, the string is formatted following RFC 2822.

If the datetime is invalid, an empty string will be returned.

Warning: The Qt::ISODate format is only valid for years in the range 0 to 9999.

See also fromString(), QDate::toString(), QTime::toString(), and QLocale::toString().

QDateTime QDateTime::toTimeZone(const QTimeZone &timeZone) const

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 local(QDateTime::currentDateTime());
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(), and toOffsetFromUtc().

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 local(QDateTime::currentDateTime());
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(), and toOffsetFromUtc().

[since 6.4] QDateTime &QDateTime::operator+=(std::chrono::milliseconds duration)

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.

This function was introduced in Qt 6.4.

See also addMSecs().

[since 6.4] QDateTime &QDateTime::operator-=(std::chrono::milliseconds duration)

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.

This function was introduced in Qt 6.4.

See also addMSecs.

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

Copies the other datetime into this and returns this copy.

Related Non-Members

[since 6.4] QDateTime operator+(const QDateTime &dateTime, std::chrono::milliseconds duration)

[since 6.4] QDateTime operator+(std::chrono::milliseconds duration, const QDateTime &dateTime)

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.

This function was introduced in Qt 6.4.

See also addMSecs().

bool operator!=(const QDateTime &lhs, const QDateTime &rhs)

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

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

See also operator==().

[since 6.4] std::chrono::milliseconds operator-(const QDateTime &lhs, const QDateTime &rhs)

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.

This function was introduced in Qt 6.4.

See also msecsTo().

[since 6.4] QDateTime operator-(const QDateTime &dateTime, std::chrono::milliseconds duration)

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.

This function was introduced in Qt 6.4.

See also addMSecs().

bool operator<(const QDateTime &lhs, const QDateTime &rhs)

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

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

See also operator==().

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

Writes dateTime to the out stream.

See also Serializing Qt Data Types.

bool operator<=(const QDateTime &lhs, const QDateTime &rhs)

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

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

See also operator==().

bool operator==(const QDateTime &lhs, const QDateTime &rhs)

Returns true if lhs represents the same moment in time as rhs; otherwise returns false.

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

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

bool operator>(const QDateTime &lhs, const QDateTime &rhs)

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

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

See also operator==().

bool operator>=(const QDateTime &lhs, const QDateTime &rhs)

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

Two datetimes using different time representations can have different offsets from UTC. In this case, they may compare equivalent even if their date() and time() differ, if that difference matches the difference in UTC offset. If their date() and time() coincide, the one with higher offset from UTC is less (earlier) than the one with lower offset. As a result, datetimes are only weakly ordered.

Since 5.14, all invalid datetimes are equivalent and less than all valid datetimes.

See also operator==().

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

Reads a datetime from the stream in into dateTime.

See also Serializing Qt Data Types.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.