QDateTime Class

  • Header: QDateTime

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS Core)

    target_link_libraries(mytarget PRIVATE Qt6::Core)

  • qmake: QT += core

  • Group: QDateTime is part of Implicitly Shared Classes

Detailed Description

<Unknown command>comparesweak

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 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 timeSpec() is Qt::TimeZone) to use that instead.

Remarks

QDateTime does not account for leap seconds.

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

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.

Using local time (the default) or a specified time zone implies a need to resolve any issues around transitions. As a result, operations on such QDateTime instances (notably including constructing them) may be more expensive than the equivalent when using UTC or a fixed offset from it.

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 equip QTimeZone with the same timezone database as is used on Unix.

Timezone transitions

QDateTime takes into account timezone transitions, both the transitions between Standard Time and Daylight-Saving Time (DST) and the transitions that arise when a zone changes its standard offset. For example, if the transition is at 2am and the clock goes forward to 3am, then there is a "missing" hour from 02:00:00 to 02:59:59.999. Such a transition is known as a "spring forward" and the times skipped over have no meaning. When a transition goes the other way, known as a "fall back", a time interval is repeated, first in the old zone (usually DST), then in the new zone (usually Standard Time), so times in this interval are ambiguous.

Some zones use "reversed" DST, using standard time in summer and daylight-saving time (with a lowered offset) in winter. For such zones, the spring forward still happens in spring and skips an hour, but is a transition out of daylight-saving time, while the fall back still repeats an autumn hour but is a transition to daylight-saving time.

When converting from a UTC time (or a time at fixed offset from UTC), there is always an unambiguous valid result in any timezone. However, when combining a date and time to make a datetime, expressed with respect to local time or a specific time-zone, the nominal result may fall in a transition, making it either invalid or ambiguous. Methods where this situation may arise take a resolve parameter: this is always ignored if the requested datetime is valid and unambiguous. See TransitionResolution for the options it lets you control. Prior to Qt 6.7, the equivalent of its LegacyBehavior was selected.

For a spring forward's skipped interval, interpreting the requested time with either offset yields an actual time at which the other offset was in use; so passing TransitionResolution::RelativeToBefore for resolve will actually result in a time after the transition, that would have had the requested representation had the transition not happened. Likewise, TransitionResolution::RelativeToAfter for resolve results in a time before the transition, that would have had the requested representation, had the transition happened earlier.

When QDateTime performs arithmetic, as with addDay() or addSecs(), it takes care to produce a valid result. For example, on a day when there is a spring forward from 02:00 to 03:00, adding one second to 01:59:59 will get 03:00:00. Adding one day to 02:30 on the preceding day will get 03:30 on the day of the transition, while subtracting one day, by calling addDay(-1), to 02:30 on the following day will get 01:30 on the day of the transition. While addSecs() will deliver a time offset by the given number of seconds, addDays() adjusts the date and only adjusts time if it would otherwise get an invalid result. Applying addDays(1) to 03:00 on the day before the spring-forward will simply get 03:00 on the day of the transition, even though the latter is only 23 hours after the former; but addSecs(24 * 60 * 60) will get 04:00 on the day of the transition, since that's 24 hours later. Typical transitions make some days 23 or 25 hours long.

For datetimes that the system 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 (potentially including some within the time_t range), QTimeZone::systemTimeZone() is used, if available, or a best effort is made to estimate. In any case, the offset information used depends on the system and may be incomplete or, for past times, historically inaccurate. Furthermore, for future dates, the local time zone's offsets and DST rules may change before that date comes around.

Whole day transitions

A small number of zones have skipped or repeated entire days as part of moving The International Date Line across themselves. For these, daysTo() will be unaware of the duplication or gap, simply using the difference in calendar date; in contrast, msecsTo() and secsTo() know the true time interval. Likewise, addMSecs() and addSecs() correspond directly to elapsed time, where addDays(), addMonths() and addYears() follow the nominal calendar, aside from where landing in a gap or duplication requires resolving an ambiguity or invalidity due to a duplication or omission.

Days "lost" during a change of calendar, such as from Julian to Gregorian, do not affect QDateTime. Although the two calendars describe dates differently, the successive days across the change are described by consecutive QDate instances, each one day later than the previous, as described by either calendar or by their toJulianDay() values. In contrast, a zone skipping or duplicating a day is changing its description of time, not date, for all that it does so by a whole 24 hours.

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. Historical time zones have a wider range and may have offsets including seconds; these last cannot be faithfully represented in strings.

See Also

Member Type Documentation

 

[since 6.7] enum QDateTime::TransitionResolution

This enumeration is used to resolve datetime combinations which fall in 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.

Constant

Value

Description

QDateTime::TransitionResolution::Reject

0

Treat any time in a transition as invalid. Either it really is, or it is ambiguous.

QDateTime::TransitionResolution::RelativeToBefore

1

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.

QDateTime::TransitionResolution::RelativeToAfter

2

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.

QDateTime::TransitionResolution::PreferBefore

3

Selects a time before the transition,

QDateTime::TransitionResolution::PreferAfter

4

Selects a time after the transition.

QDateTime::TransitionResolution::PreferStandard

5

Selects a time on the standard time side of the transition.

QDateTime::TransitionResolution::PreferDaylightSaving

6

Selects a time on the daylight-saving-time side of the transition.

QDateTime::TransitionResolution::LegacyBehavior

RelativeToBefore

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 addDays(), addMonths() or addYears(), the behavior is and (mostly) was to use RelativeToBefore if adding a positive adjustment and RelativeToAfter if adding a negative adjustment.

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:

Before

02:00–03:00

After

resolve

selected

LST

skip

LDT

RelativeToBefore

03:30 LDT

LST

skip

LDT

RelativeToAfter

01:30 LST

LST

skip

LDT

PreferBefore

01:30 LST

LST

skip

LDT

PreferAfter

03:30 LDT

LST

skip

LDT

PreferStandard

01:30 LST

LST

skip

LDT

PreferDaylightSaving

03:30 LDT

LDT

repeat

LST

RelativeToBefore

02:30 LDT

LDT

repeat

LST

RelativeToAfter

02:30 LST

LDT

repeat

LST

PreferBefore

02:30 LDT

LDT

repeat

LST

PreferAfter

02:30 LST

LDT

repeat

LST

PreferStandard

02:30 LST

LDT

repeat

LST

PreferDaylightSaving

02:30 LDT

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:

LDT

skip

LST

RelativeToBefore

03:30 LST

LDT

skip

LST

RelativeToAfter

01:30 LDT

LDT

skip

LST

PreferBefore