1 /****************************************************************************
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qplatformdefs.h"
43 #include "private/qdatetime_p.h"
45 #include "qdatastream.h"
48 #include "qdatetime.h"
51 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
52 #include <qt_windows.h>
59 #if defined(Q_OS_WINCE)
60 #include "qfunctions_wince.h"
63 //#define QDATETIMEPARSER_DEBUG
64 #if defined (QDATETIMEPARSER_DEBUG) && !defined(QT_NO_DEBUG_STREAM)
65 # define QDTPDEBUG qDebug() << QString("%1:%2").arg(__FILE__).arg(__LINE__)
66 # define QDTPDEBUGN qDebug
68 # define QDTPDEBUG if (false) qDebug()
69 # define QDTPDEBUGN if (false) qDebug
73 #include <private/qcore_mac_p.h>
76 #if defined(Q_OS_SYMBIAN)
86 FIRST_DAY = 2, // ### Qt 5: make FIRST_DAY = 1, by support jd == 0 as valid
88 MSECS_PER_DAY = 86400000,
90 MSECS_PER_HOUR = 3600000,
92 MSECS_PER_MIN = 60000,
93 JULIAN_DAY_FOR_EPOCH = 2440588 // result of julianDayFromGregorianDate(1970, 1, 1)
96 static inline QDate fixedDate(int y, int m, int d)
98 QDate result(y, m, 1);
99 result.setDate(y, m, qMin(d, result.daysInMonth()));
103 static inline uint julianDayFromGregorianDate(int year, int month, int day)
105 // Gregorian calendar starting from October 15, 1582
106 // Algorithm from Henry F. Fliegel and Thomas C. Van Flandern
107 return (1461 * (year + 4800 + (month - 14) / 12)) / 4
108 + (367 * (month - 2 - 12 * ((month - 14) / 12))) / 12
109 - (3 * ((year + 4900 + (month - 14) / 12) / 100)) / 4
113 static uint julianDayFromDate(int year, int month, int day)
118 if (year > 1582 || (year == 1582 && (month > 10 || (month == 10 && day >= 15)))) {
119 return julianDayFromGregorianDate(year, month, day);
120 } else if (year < 1582 || (year == 1582 && (month < 10 || (month == 10 && day <= 4)))) {
121 // Julian calendar until October 4, 1582
122 // Algorithm from Frequently Asked Questions about Calendars by Claus Toendering
123 int a = (14 - month) / 12;
124 return (153 * (month + (12 * a) - 3) + 2) / 5
125 + (1461 * (year + 4800 - a)) / 4
128 // the day following October 4, 1582 is October 15, 1582
133 static void getDateFromJulianDay(uint julianDay, int *year, int *month, int *day)
137 if (julianDay >= 2299161) {
138 // Gregorian calendar starting from October 15, 1582
139 // This algorithm is from Henry F. Fliegel and Thomas C. Van Flandern
140 qulonglong ell, n, i, j;
141 ell = qulonglong(julianDay) + 68569;
142 n = (4 * ell) / 146097;
143 ell = ell - (146097 * n + 3) / 4;
144 i = (4000 * (ell + 1)) / 1461001;
145 ell = ell - (1461 * i) / 4 + 31;
146 j = (80 * ell) / 2447;
147 d = ell - (2447 * j) / 80;
149 m = j + 2 - (12 * ell);
150 y = 100 * (n - 49) + i + ell;
152 // Julian calendar until October 4, 1582
153 // Algorithm from Frequently Asked Questions about Calendars by Claus Toendering
155 int dd = (4 * julianDay + 3) / 1461;
156 int ee = julianDay - (1461 * dd) / 4;
157 int mm = ((5 * ee) + 2) / 153;
158 d = ee - (153 * mm + 2) / 5 + 1;
159 m = mm + 3 - 12 * (mm / 10);
160 y = dd - 4800 + (mm / 10);
173 static const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
175 #ifndef QT_NO_TEXTDATE
176 static const char * const qt_shortMonthNames[] = {
177 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
178 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
180 #ifndef QT_NO_DATESTRING
181 static QString fmtDateTime(const QString& f, const QTime* dt = 0, const QDate* dd = 0);
184 /*****************************************************************************
185 QDate member functions
186 *****************************************************************************/
191 \enum QDate::MonthNameType
193 This enum describes the types of the string representation used
196 \value DateFormat This type of name can be used for date-to-string formatting.
197 \value StandaloneFormat This type is used when you need to enumerate months or weekdays.
198 Usually standalone names are represented in singular forms with
199 capitalized first letter.
205 \brief The QDate class provides date functions.
208 A QDate object contains a calendar date, i.e. year, month, and day
209 numbers, in the Gregorian calendar. (see \l{QDate G and J} {Use of
210 Gregorian and Julian Calendars} for dates prior to 15 October
211 1582). It can read the current date from the system clock. It
212 provides functions for comparing dates, and for manipulating
213 dates. For example, it is possible to add and subtract days,
214 months, and years to dates.
216 A QDate object is typically created either by giving the year,
217 month, and day numbers explicitly. Note that QDate interprets two
218 digit years as is, i.e., years 0 - 99. A QDate can also be
219 constructed with the static function currentDate(), which creates
220 a QDate object containing the system clock's date. An explicit
221 date can also be set using setDate(). The fromString() function
222 returns a QDate given a string and a date format which is used to
223 interpret the date within the string.
225 The year(), month(), and day() functions provide access to the
226 year, month, and day numbers. Also, dayOfWeek() and dayOfYear()
227 functions are provided. The same information is provided in
228 textual format by the toString(), shortDayName(), longDayName(),
229 shortMonthName(), and longMonthName() functions.
231 QDate provides a full set of operators to compare two QDate
232 objects where smaller means earlier, and larger means later.
234 You can increment (or decrement) a date by a given number of days
235 using addDays(). Similarly you can use addMonths() and addYears().
236 The daysTo() function returns the number of days between two
239 The daysInMonth() and daysInYear() functions return how many days
240 there are in this date's month and year, respectively. The
241 isLeapYear() function indicates whether a date is in a leap year.
245 \target QDate G and J
246 \section2 Use of Gregorian and Julian Calendars
248 QDate uses the Gregorian calendar in all locales, beginning
249 on the date 15 October 1582. For dates up to and including 4
250 October 1582, the Julian calendar is used. This means there is a
251 10-day gap in the internal calendar between the 4th and the 15th
252 of October 1582. When you use QDateTime for dates in that epoch,
253 the day after 4 October 1582 is 15 October 1582, and the dates in
256 The Julian to Gregorian changeover date used here is the date when
257 the Gregorian calendar was first introduced, by Pope Gregory
258 XIII. That change was not universally accepted and some localities
259 only executed it at a later date (if at all). QDateTime
260 doesn't take any of these historical facts into account. If an
261 application must support a locale-specific dating system, it must
262 do so on its own, remembering to convert the dates using the
267 There is no year 0. Dates in that year are considered invalid. The
268 year -1 is the year "1 before Christ" or "1 before current era."
269 The day before 0001-01-01 is December 31st, 1 BCE.
271 \section2 Range of Valid Dates
273 The range of valid dates is from January 2nd, 4713 BCE, to
274 sometime in the year 11 million CE. The Julian Day returned by
275 QDate::toJulianDay() is a number in the contiguous range from 1 to
276 \e{overflow}, even across QDateTime's "date holes". It is suitable
277 for use in applications that must convert a QDateTime to a date in
278 another calendar system, e.g., Hebrew, Islamic or Chinese.
280 \sa QTime, QDateTime, QDateEdit, QDateTimeEdit, QCalendarWidget
286 Constructs a null date. Null dates are invalid.
288 \sa isNull(), isValid()
292 Constructs a date with year \a y, month \a m and day \a d.
294 If the specified date is invalid, the date is not set and
295 isValid() returns false. A date before 2 January 4713 B.C. is
298 \warning Years 0 to 99 are interpreted as is, i.e., years
304 QDate::QDate(int y, int m, int d)
311 \fn bool QDate::isNull() const
313 Returns true if the date is null; otherwise returns false. A null
316 \note The behavior of this function is equivalent to isValid().
323 Returns true if this date is valid; otherwise returns false.
328 bool QDate::isValid() const
335 Returns the year of this date. Negative numbers indicate years
336 before 1 A.D. = 1 C.E., such that year -44 is 44 B.C.
341 int QDate::year() const
344 getDateFromJulianDay(jd, &y, 0, 0);
349 Returns the number corresponding to the month of this date, using
350 the following convention:
370 int QDate::month() const
373 getDateFromJulianDay(jd, 0, &m, 0);
378 Returns the day of the month (1 to 31) of this date.
380 \sa year(), month(), dayOfWeek()
383 int QDate::day() const
386 getDateFromJulianDay(jd, 0, 0, &d);
391 Returns the weekday (1 = Monday to 7 = Sunday) for this date.
393 \sa day(), dayOfYear(), Qt::DayOfWeek
396 int QDate::dayOfWeek() const
402 Returns the day of the year (1 to 365 or 366 on leap years) for
405 \sa day(), dayOfWeek()
408 int QDate::dayOfYear() const
410 return jd - julianDayFromDate(year(), 1, 1) + 1;
414 Returns the number of days in the month (28 to 31) for this date.
416 \sa day(), daysInYear()
419 int QDate::daysInMonth() const
422 getDateFromJulianDay(jd, &y, &m, &d);
423 if (m == 2 && isLeapYear(y))
430 Returns the number of days in the year (365 or 366) for this date.
432 \sa day(), daysInMonth()
435 int QDate::daysInYear() const
438 getDateFromJulianDay(jd, &y, &m, &d);
439 return isLeapYear(y) ? 366 : 365;
443 Returns the week number (1 to 53), and stores the year in
444 *\a{yearNumber} unless \a yearNumber is null (the default).
446 Returns 0 if the date is invalid.
448 In accordance with ISO 8601, weeks start on Monday and the first
449 Thursday of a year is always in week 1 of that year. Most years
450 have 52 weeks, but some have 53.
452 *\a{yearNumber} is not always the same as year(). For example, 1
453 January 2000 has week number 52 in the year 1999, and 31 December
454 2002 has week number 1 in the year 2003.
459 int QDate::weekNumber(int *yearNumber) const
464 int year = QDate::year();
465 int yday = dayOfYear();
466 int wday = dayOfWeek();
468 int week = (yday - wday + 10) / 7;
471 // last week of previous year
473 week = (yday + 365 + (QDate::isLeapYear(year) ? 1 : 0) - wday + 10) / 7;
474 Q_ASSERT(week == 52 || week == 53);
475 } else if (week == 53) {
476 // maybe first week of next year
477 int w = (yday - 365 - (QDate::isLeapYear(year + 1) ? 1 : 0) - wday + 10) / 7;
482 Q_ASSERT(week == 53 || week == 1);
490 #ifndef QT_NO_TEXTDATE
494 Returns the short name of the \a month for the representation specified
497 The months are enumerated using the following convention:
514 The month names will be localized according to the system's default
517 \sa toString(), longMonthName(), shortDayName(), longDayName()
520 QString QDate::shortMonthName(int month, QDate::MonthNameType type)
522 if (month < 1 || month > 12) {
526 case QDate::DateFormat:
527 return QLocale::system().monthName(month, QLocale::ShortFormat);
528 case QDate::StandaloneFormat:
529 return QLocale::system().standaloneMonthName(month, QLocale::ShortFormat);
537 Returns the short version of the name of the \a month. The
538 returned name is in normal type which can be used for date formatting.
540 \sa toString(), longMonthName(), shortDayName(), longDayName()
543 QString QDate::shortMonthName(int month)
545 return shortMonthName(month, QDate::DateFormat);
551 Returns the long name of the \a month for the representation specified
554 The months are enumerated using the following convention:
571 The month names will be localized according to the system's default
574 \sa toString(), shortMonthName(), shortDayName(), longDayName()
577 QString QDate::longMonthName(int month, MonthNameType type)
579 if (month < 1 || month > 12) {
583 case QDate::DateFormat:
584 return QLocale::system().monthName(month, QLocale::LongFormat);
585 case QDate::StandaloneFormat:
586 return QLocale::system().standaloneMonthName(month, QLocale::LongFormat);
594 Returns the long version of the name of the \a month. The
595 returned name is in normal type which can be used for date formatting.
597 \sa toString(), shortMonthName(), shortDayName(), longDayName()
600 QString QDate::longMonthName(int month)
602 if (month < 1 || month > 12) {
605 return QLocale::system().monthName(month, QLocale::LongFormat);
611 Returns the short name of the \a weekday for the representation specified
614 The days are enumerated using the following convention:
626 The day names will be localized according to the system's default
629 \sa toString(), shortMonthName(), longMonthName(), longDayName()
632 QString QDate::shortDayName(int weekday, MonthNameType type)
634 if (weekday < 1 || weekday > 7) {
638 case QDate::DateFormat:
639 return QLocale::system().dayName(weekday, QLocale::ShortFormat);
640 case QDate::StandaloneFormat:
641 return QLocale::system().standaloneDayName(weekday, QLocale::ShortFormat);
649 Returns the short version of the name of the \a weekday. The
650 returned name is in normal type which can be used for date formatting.
652 \sa toString(), longDayName(), shortMonthName(), longMonthName()
655 QString QDate::shortDayName(int weekday)
657 if (weekday < 1 || weekday > 7) {
660 return QLocale::system().dayName(weekday, QLocale::ShortFormat);
666 Returns the long name of the \a weekday for the representation specified
669 The days are enumerated using the following convention:
681 The day names will be localized according to the system's default
684 \sa toString(), shortDayName(), shortMonthName(), longMonthName()
687 QString QDate::longDayName(int weekday, MonthNameType type)
689 if (weekday < 1 || weekday > 7) {
693 case QDate::DateFormat:
694 return QLocale::system().dayName(weekday, QLocale::LongFormat);
695 case QDate::StandaloneFormat:
696 return QLocale::system().standaloneDayName(weekday, QLocale::LongFormat);
700 return QLocale::system().dayName(weekday, QLocale::LongFormat);
704 Returns the long version of the name of the \a weekday. The
705 returned name is in normal type which can be used for date formatting.
707 \sa toString(), shortDayName(), shortMonthName(), longMonthName()
710 QString QDate::longDayName(int weekday)
712 if (weekday < 1 || weekday > 7) {
715 return QLocale::system().dayName(weekday, QLocale::LongFormat);
717 #endif //QT_NO_TEXTDATE
719 #ifndef QT_NO_DATESTRING
722 \fn QString QDate::toString(Qt::DateFormat format) const
726 Returns the date as a string. The \a format parameter determines
727 the format of the string.
729 If the \a format is Qt::TextDate, the string is formatted in
730 the default way. QDate::shortDayName() and QDate::shortMonthName()
731 are used to generate the string, so the day and month names will
732 be localized names using the default locale from the system. An
733 example of this formatting is "Sat May 20 1995".
735 If the \a format is Qt::ISODate, the string format corresponds
736 to the ISO 8601 extended specification for representations of
737 dates and times, taking the form YYYY-MM-DD, where YYYY is the
738 year, MM is the month of the year (between 01 and 12), and DD is
739 the day of the month between 01 and 31.
741 If the \a format is Qt::SystemLocaleShortDate or
742 Qt::SystemLocaleLongDate, the string format depends on the locale
743 settings of the system. Identical to calling
744 QLocale::system().toString(date, QLocale::ShortFormat) or
745 QLocale::system().toString(date, QLocale::LongFormat).
747 If the \a format is Qt::DefaultLocaleShortDate or
748 Qt::DefaultLocaleLongDate, the string format depends on the
749 default application locale. This is the locale set with
750 QLocale::setDefault(), or the system locale if no default locale
751 has been set. Identical to calling QLocale().toString(date,
752 QLocale::ShortFormat) or QLocale().toString(date,
753 QLocale::LongFormat).
755 If the date is invalid, an empty string will be returned.
757 \warning The Qt::ISODate format is only valid for years in the
758 range 0 to 9999. This restriction may apply to locale-aware
759 formats as well, depending on the locale settings.
761 \sa shortDayName(), shortMonthName()
763 QString QDate::toString(Qt::DateFormat f) const
768 getDateFromJulianDay(jd, &y, &m, &d);
770 case Qt::SystemLocaleDate:
771 case Qt::SystemLocaleShortDate:
772 case Qt::SystemLocaleLongDate:
773 return QLocale::system().toString(*this, f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
774 : QLocale::ShortFormat);
776 case Qt::DefaultLocaleShortDate:
777 case Qt::DefaultLocaleLongDate:
778 return QLocale().toString(*this, f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
779 : QLocale::ShortFormat);
781 #ifndef QT_NO_TEXTDATE
784 return QString::fromLatin1("%0 %1 %2 %3")
785 .arg(shortDayName(dayOfWeek()))
786 .arg(shortMonthName(m))
793 if (year() < 0 || year() > 9999)
795 QString month(QString::number(m).rightJustified(2, QLatin1Char('0')));
796 QString day(QString::number(d).rightJustified(2, QLatin1Char('0')));
797 return QString::number(y) + QLatin1Char('-') + month + QLatin1Char('-') + day;
803 Returns the date as a string. The \a format parameter determines
804 the format of the result string.
806 These expressions may be used:
809 \header \i Expression \i Output
810 \row \i d \i the day as number without a leading zero (1 to 31)
811 \row \i dd \i the day as number with a leading zero (01 to 31)
813 \i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
814 Uses QDate::shortDayName().
816 \i the long localized day name (e.g. 'Monday' to 'Sunday').
817 Uses QDate::longDayName().
818 \row \i M \i the month as number without a leading zero (1 to 12)
819 \row \i MM \i the month as number with a leading zero (01 to 12)
821 \i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
822 Uses QDate::shortMonthName().
824 \i the long localized month name (e.g. 'January' to 'December').
825 Uses QDate::longMonthName().
826 \row \i yy \i the year as two digit number (00 to 99)
827 \row \i yyyy \i the year as four digit number. If the year is negative,
828 a minus sign is prepended in addition.
831 All other input characters will be ignored. Any sequence of characters that
832 are enclosed in singlequotes will be treated as text and not be used as an
833 expression. Two consecutive singlequotes ("''") are replaced by a singlequote
836 Example format strings (assuming that the QDate is the 20 July
840 \header \o Format \o Result
841 \row \o dd.MM.yyyy \o 20.07.1969
842 \row \o ddd MMMM d yy \o Sun July 20 69
843 \row \o 'The day is' dddd \o The day is Sunday
846 If the datetime is invalid, an empty string will be returned.
848 \warning The Qt::ISODate format is only valid for years in the
849 range 0 to 9999. This restriction may apply to locale-aware
850 formats as well, depending on the locale settings.
852 \sa QDateTime::toString() QTime::toString()
855 QString QDate::toString(const QString& format) const
859 return fmtDateTime(format, 0, this);
861 #endif //QT_NO_DATESTRING
866 Sets the date's year \a y, month \a m, and day \a d.
868 If \a y is in the range 0 to 99, it is interpreted as 1900 to
871 Use setDate() instead.
874 bool QDate::setYMD(int y, int m, int d)
878 return setDate(y, m, d);
884 Sets the date's \a year, \a month, and \a day. Returns true if
885 the date is valid; otherwise returns false.
887 If the specified date is invalid, the QDate object is set to be
888 invalid. Any date before 2 January 4713 B.C. is considered
893 bool QDate::setDate(int year, int month, int day)
895 if (!isValid(year, month, day)) {
898 jd = julianDayFromDate(year, month, day);
906 Extracts the date's year, month, and day, and assigns them to
907 *\a year, *\a month, and *\a day. The pointers may be null.
909 \sa year(), month(), day(), isValid()
911 void QDate::getDate(int *year, int *month, int *day)
913 getDateFromJulianDay(jd, year, month, day);
917 Returns a QDate object containing a date \a ndays later than the
918 date of this object (or earlier if \a ndays is negative).
920 \sa addMonths() addYears() daysTo()
923 QDate QDate::addDays(int ndays) const
926 // this is basically "d.jd = jd + ndays" with checks for integer overflow
928 d.jd = (jd + ndays >= jd) ? jd + ndays : 0;
930 d.jd = (jd + ndays < jd) ? jd + ndays : 0;
935 Returns a QDate object containing a date \a nmonths later than the
936 date of this object (or earlier if \a nmonths is negative).
938 \note If the ending day/month combination does not exist in the
939 resulting month/year, this function will return a date that is the
942 \warning QDate has a date hole around the days introducing the
943 Gregorian calendar (the days 5 to 14 October 1582, inclusive, do
944 not exist). If the calculation ends in one of those days, QDate
945 will return either October 4 or October 15.
947 \sa addDays() addYears()
950 QDate QDate::addMonths(int nmonths) const
958 getDateFromJulianDay(jd, &y, &m, &d);
961 bool increasing = nmonths > 0;
963 while (nmonths != 0) {
964 if (nmonths < 0 && nmonths + 12 <= 0) {
967 } else if (nmonths < 0) {
974 } else if (nmonths - 12 >= 0) {
977 } else if (m == 12) {
990 // was there a sign change?
991 if ((old_y > 0 && y <= 0) ||
992 (old_y < 0 && y >= 0))
993 // yes, adjust the date by +1 or -1 years
994 y += increasing ? +1 : -1;
996 // did we end up in the Gregorian/Julian conversion hole?
997 if (y == 1582 && m == 10 && d > 4 && d < 15)
998 d = increasing ? 15 : 4;
1000 return fixedDate(y, m, d);
1004 Returns a QDate object containing a date \a nyears later than the
1005 date of this object (or earlier if \a nyears is negative).
1007 \note If the ending day/month combination does not exist in the
1008 resulting year (i.e., if the date was Feb 29 and the final year is
1009 not a leap year), this function will return a date that is the
1010 latest valid date (that is, Feb 28).
1012 \sa addDays(), addMonths()
1015 QDate QDate::addYears(int nyears) const
1021 getDateFromJulianDay(jd, &y, &m, &d);
1026 // was there a sign change?
1027 if ((old_y > 0 && y <= 0) ||
1028 (old_y < 0 && y >= 0))
1029 // yes, adjust the date by +1 or -1 years
1030 y += nyears > 0 ? +1 : -1;
1032 return fixedDate(y, m, d);
1036 Returns the number of days from this date to \a d (which is
1037 negative if \a d is earlier than this date).
1040 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 0
1045 int QDate::daysTo(const QDate &d) const
1052 \fn bool QDate::operator==(const QDate &d) const
1054 Returns true if this date is equal to \a d; otherwise returns
1060 \fn bool QDate::operator!=(const QDate &d) const
1062 Returns true if this date is different from \a d; otherwise
1067 \fn bool QDate::operator<(const QDate &d) const
1069 Returns true if this date is earlier than \a d; otherwise returns
1074 \fn bool QDate::operator<=(const QDate &d) const
1076 Returns true if this date is earlier than or equal to \a d;
1077 otherwise returns false.
1081 \fn bool QDate::operator>(const QDate &d) const
1083 Returns true if this date is later than \a d; otherwise returns
1088 \fn bool QDate::operator>=(const QDate &d) const
1090 Returns true if this date is later than or equal to \a d;
1091 otherwise returns false.
1095 \fn QDate::currentDate()
1096 Returns the current date, as reported by the system clock.
1098 \sa QTime::currentTime(), QDateTime::currentDateTime()
1101 #ifndef QT_NO_DATESTRING
1103 \fn QDate QDate::fromString(const QString &string, Qt::DateFormat format)
1105 Returns the QDate represented by the \a string, using the
1106 \a format given, or an invalid date if the string cannot be
1109 Note for Qt::TextDate: It is recommended that you use the
1110 English short month names (e.g. "Jan"). Although localized month
1111 names can also be used, they depend on the user's locale settings.
1113 QDate QDate::fromString(const QString& s, Qt::DateFormat f)
1121 int year(s.mid(0, 4).toInt());
1122 int month(s.mid(5, 2).toInt());
1123 int day(s.mid(8, 2).toInt());
1124 if (year && month && day)
1125 return QDate(year, month, day);
1128 case Qt::SystemLocaleDate:
1129 case Qt::SystemLocaleShortDate:
1130 case Qt::SystemLocaleLongDate:
1131 return fromString(s, QLocale::system().dateFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
1132 : QLocale::ShortFormat));
1133 case Qt::LocaleDate:
1134 case Qt::DefaultLocaleShortDate:
1135 case Qt::DefaultLocaleLongDate:
1136 return fromString(s, QLocale().dateFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
1137 : QLocale::ShortFormat));
1139 #ifndef QT_NO_TEXTDATE
1140 case Qt::TextDate: {
1141 QStringList parts = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
1143 if (parts.count() != 4) {
1147 QString monthName = parts.at(1);
1149 // Assume that English monthnames are the default
1150 for (int i = 0; i < 12; ++i) {
1151 if (monthName == QLatin1String(qt_shortMonthNames[i])) {
1156 // If English names can't be found, search the localized ones
1158 for (int i = 1; i <= 12; ++i) {
1159 if (monthName == QDate::shortMonthName(i)) {
1165 if (month < 1 || month > 12) {
1170 int day = parts.at(2).toInt(&ok);
1175 int year = parts.at(3).toInt(&ok);
1180 return QDate(year, month, day);
1190 \fn QDate::fromString(const QString &string, const QString &format)
1192 Returns the QDate represented by the \a string, using the \a
1193 format given, or an invalid date if the string cannot be parsed.
1195 These expressions may be used for the format:
1198 \header \i Expression \i Output
1199 \row \i d \i The day as a number without a leading zero (1 to 31)
1200 \row \i dd \i The day as a number with a leading zero (01 to 31)
1202 \i The abbreviated localized day name (e.g. 'Mon' to 'Sun').
1203 Uses QDate::shortDayName().
1205 \i The long localized day name (e.g. 'Monday' to 'Sunday').
1206 Uses QDate::longDayName().
1207 \row \i M \i The month as a number without a leading zero (1 to 12)
1208 \row \i MM \i The month as a number with a leading zero (01 to 12)
1210 \i The abbreviated localized month name (e.g. 'Jan' to 'Dec').
1211 Uses QDate::shortMonthName().
1213 \i The long localized month name (e.g. 'January' to 'December').
1214 Uses QDate::longMonthName().
1215 \row \i yy \i The year as two digit number (00 to 99)
1216 \row \i yyyy \i The year as four digit number. If the year is negative,
1217 a minus sign is prepended in addition.
1220 All other input characters will be treated as text. Any sequence
1221 of characters that are enclosed in single quotes will also be
1222 treated as text and will not be used as an expression. For example:
1224 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 1
1226 If the format is not satisfied, an invalid QDate is returned. The
1227 expressions that don't expect leading zeroes (d, M) will be
1228 greedy. This means that they will use two digits even if this
1229 will put them outside the accepted range of values and leaves too
1230 few digits for other sections. For example, the following format
1231 string could have meant January 30 but the M will grab two
1232 digits, resulting in an invalid date:
1234 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 2
1236 For any field that is not represented in the format the following
1240 \header \i Field \i Default value
1241 \row \i Year \i 1900
1246 The following examples demonstrate the default values:
1248 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 3
1250 \sa QDateTime::fromString(), QTime::fromString(), QDate::toString(),
1251 QDateTime::toString(), QTime::toString()
1254 QDate QDate::fromString(const QString &string, const QString &format)
1257 #ifndef QT_BOOTSTRAPPED
1258 QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString);
1259 if (dt.parseFormat(format))
1260 dt.fromString(string, &date, 0);
1267 #endif // QT_NO_DATESTRING
1272 Returns true if the specified date (\a year, \a month, and \a
1273 day) is valid; otherwise returns false.
1276 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 4
1278 \sa isNull(), setDate()
1281 bool QDate::isValid(int year, int month, int day)
1283 if (year < FIRST_YEAR
1284 || (year == FIRST_YEAR &&
1285 (month < FIRST_MONTH
1286 || (month == FIRST_MONTH && day < FIRST_DAY)))
1287 || year == 0) // there is no year 0 in the Julian calendar
1290 // passage from Julian to Gregorian calendar
1291 if (year == 1582 && month == 10 && day > 4 && day < 15)
1294 return (day > 0 && month > 0 && month <= 12) &&
1295 (day <= monthDays[month] || (day == 29 && month == 2 && isLeapYear(year)));
1299 \fn bool QDate::isLeapYear(int year)
1301 Returns true if the specified \a year is a leap year; otherwise
1305 bool QDate::isLeapYear(int y)
1308 if ( y < 1) { // No year 0 in Julian calendar, so -1, -5, -9 etc are leap years
1313 return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
1320 This function has a confusing name and shouldn't be part of the
1321 API anyway, since we have toJulian() and fromJulian().
1324 uint QDate::gregorianToJulian(int y, int m, int d)
1326 return julianDayFromDate(y, m, d);
1332 This function has a confusing name and shouldn't be part of the
1333 API anyway, since we have toJulian() and fromJulian().
1336 void QDate::julianToGregorian(uint jd, int &y, int &m, int &d)
1338 getDateFromJulianDay(jd, &y, &m, &d);
1341 /*! \fn static QDate QDate::fromJulianDay(int jd)
1343 Converts the Julian day \a jd to a QDate.
1348 /*! \fn int QDate::toJulianDay() const
1350 Converts the date to a Julian day.
1355 /*****************************************************************************
1356 QTime member functions
1357 *****************************************************************************/
1363 \brief The QTime class provides clock time functions.
1366 A QTime object contains a clock time, i.e. the number of hours,
1367 minutes, seconds, and milliseconds since midnight. It can read the
1368 current time from the system clock and measure a span of elapsed
1369 time. It provides functions for comparing times and for
1370 manipulating a time by adding a number of milliseconds.
1372 QTime uses the 24-hour clock format; it has no concept of AM/PM.
1373 Unlike QDateTime, QTime knows nothing about time zones or
1374 daylight savings time (DST).
1376 A QTime object is typically created either by giving the number
1377 of hours, minutes, seconds, and milliseconds explicitly, or by
1378 using the static function currentTime(), which creates a QTime
1379 object that contains the system's local time. Note that the
1380 accuracy depends on the accuracy of the underlying operating
1381 system; not all systems provide 1-millisecond accuracy.
1383 The hour(), minute(), second(), and msec() functions provide
1384 access to the number of hours, minutes, seconds, and milliseconds
1385 of the time. The same information is provided in textual format by
1386 the toString() function.
1388 QTime provides a full set of operators to compare two QTime
1389 objects. One time is considered smaller than another if it is
1390 earlier than the other.
1392 The time a given number of seconds or milliseconds later than a
1393 given time can be found using the addSecs() or addMSecs()
1394 functions. Correspondingly, the number of seconds or milliseconds
1395 between two times can be found using secsTo() or msecsTo().
1397 QTime can be used to measure a span of elapsed time using the
1398 start(), restart(), and elapsed() functions.
1400 \sa QDate, QDateTime
1406 Constructs a null time object. A null time can be a QTime(0, 0, 0, 0)
1407 (i.e., midnight) object, except that isNull() returns true and isValid()
1410 \sa isNull(), isValid()
1414 Constructs a time with hour \a h, minute \a m, seconds \a s and
1417 \a h must be in the range 0 to 23, \a m and \a s must be in the
1418 range 0 to 59, and \a ms must be in the range 0 to 999.
1423 QTime::QTime(int h, int m, int s, int ms)
1425 setHMS(h, m, s, ms);
1430 \fn bool QTime::isNull() const
1432 Returns true if the time is null (i.e., the QTime object was
1433 constructed using the default constructor); otherwise returns
1434 false. A null time is also an invalid time.
1440 Returns true if the time is valid; otherwise returns false. For example,
1441 the time 23:30:55.746 is valid, but 24:12:30 is invalid.
1446 bool QTime::isValid() const
1448 return mds > NullTime && mds < MSECS_PER_DAY;
1453 Returns the hour part (0 to 23) of the time.
1455 \sa minute(), second(), msec()
1458 int QTime::hour() const
1460 return ds() / MSECS_PER_HOUR;
1464 Returns the minute part (0 to 59) of the time.
1466 \sa hour(), second(), msec()
1469 int QTime::minute() const
1471 return (ds() % MSECS_PER_HOUR) / MSECS_PER_MIN;
1475 Returns the second part (0 to 59) of the time.
1477 \sa hour(), minute(), msec()
1480 int QTime::second() const
1482 return (ds() / 1000)%SECS_PER_MIN;
1486 Returns the millisecond part (0 to 999) of the time.
1488 \sa hour(), minute(), second()
1491 int QTime::msec() const
1496 #ifndef QT_NO_DATESTRING
1500 Returns the time as a string. Milliseconds are not included. The
1501 \a format parameter determines the format of the string.
1503 If \a format is Qt::TextDate, the string format is HH:mm:ss; e.g. 1
1504 second before midnight would be "23:59:59".
1506 If \a format is Qt::ISODate, the string format corresponds to the
1507 ISO 8601 extended specification for representations of dates,
1508 which is also HH:mm:ss. (However, contrary to ISO 8601, dates
1509 before 15 October 1582 are handled as Julian dates, not Gregorian
1510 dates. See \l{QDate G and J} {Use of Gregorian and Julian
1511 Calendars}. This might change in a future version of Qt.)
1513 If the \a format is Qt::SystemLocaleShortDate or
1514 Qt::SystemLocaleLongDate, the string format depends on the locale
1515 settings of the system. Identical to calling
1516 QLocale::system().toString(time, QLocale::ShortFormat) or
1517 QLocale::system().toString(time, QLocale::LongFormat).
1519 If the \a format is Qt::DefaultLocaleShortDate or
1520 Qt::DefaultLocaleLongDate, the string format depends on the
1521 default application locale. This is the locale set with
1522 QLocale::setDefault(), or the system locale if no default locale
1523 has been set. Identical to calling QLocale().toString(time,
1524 QLocale::ShortFormat) or QLocale().toString(time,
1525 QLocale::LongFormat).
1527 If the time is invalid, an empty string will be returned.
1530 QString QTime::toString(Qt::DateFormat format) const
1536 case Qt::SystemLocaleDate:
1537 case Qt::SystemLocaleShortDate:
1538 case Qt::SystemLocaleLongDate:
1539 return QLocale::system().toString(*this, format == Qt::SystemLocaleLongDate ? QLocale::LongFormat
1540 : QLocale::ShortFormat);
1541 case Qt::LocaleDate:
1542 case Qt::DefaultLocaleShortDate:
1543 case Qt::DefaultLocaleLongDate:
1544 return QLocale().toString(*this, format == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
1545 : QLocale::ShortFormat);
1550 return QString::fromLatin1("%1:%2:%3")
1551 .arg(hour(), 2, 10, QLatin1Char('0'))
1552 .arg(minute(), 2, 10, QLatin1Char('0'))
1553 .arg(second(), 2, 10, QLatin1Char('0'));
1558 Returns the time as a string. The \a format parameter determines
1559 the format of the result string.
1561 These expressions may be used:
1564 \header \i Expression \i Output
1566 \i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
1568 \i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
1570 \i the hour without a leading zero (0 to 23, even with AM/PM display)
1572 \i the hour with a leading zero (00 to 23, even with AM/PM display)
1573 \row \i m \i the minute without a leading zero (0 to 59)
1574 \row \i mm \i the minute with a leading zero (00 to 59)
1575 \row \i s \i the second without a leading zero (0 to 59)
1576 \row \i ss \i the second with a leading zero (00 to 59)
1577 \row \i z \i the milliseconds without leading zeroes (0 to 999)
1578 \row \i zzz \i the milliseconds with leading zeroes (000 to 999)
1580 \i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
1582 \i use am/pm display. \e ap will be replaced by either "am" or "pm".
1583 \row \i t \i the timezone (for example "CEST")
1586 All other input characters will be ignored. Any sequence of characters that
1587 are enclosed in singlequotes will be treated as text and not be used as an
1588 expression. Two consecutive singlequotes ("''") are replaced by a singlequote
1591 Example format strings (assuming that the QTime is 14:13:09.042)
1594 \header \i Format \i Result
1595 \row \i hh:mm:ss.zzz \i 14:13:09.042
1596 \row \i h:m:s ap \i 2:13:9 pm
1597 \row \i H:m:s a \i 14:13:9 pm
1600 If the datetime is invalid, an empty string will be returned.
1601 If \a format is empty, the default format "hh:mm:ss" is used.
1603 \sa QDate::toString() QDateTime::toString()
1605 QString QTime::toString(const QString& format) const
1607 return fmtDateTime(format, this, 0);
1609 #endif //QT_NO_DATESTRING
1611 Sets the time to hour \a h, minute \a m, seconds \a s and
1614 \a h must be in the range 0 to 23, \a m and \a s must be in the
1615 range 0 to 59, and \a ms must be in the range 0 to 999.
1616 Returns true if the set time is valid; otherwise returns false.
1621 bool QTime::setHMS(int h, int m, int s, int ms)
1623 #if defined(Q_OS_WINCE)
1624 startTick = NullTime;
1626 if (!isValid(h,m,s,ms)) {
1627 mds = NullTime; // make this invalid
1630 mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
1635 Returns a QTime object containing a time \a s seconds later
1636 than the time of this object (or earlier if \a s is negative).
1638 Note that the time will wrap if it passes midnight.
1642 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 5
1644 \sa addMSecs(), secsTo(), QDateTime::addSecs()
1647 QTime QTime::addSecs(int s) const
1649 return addMSecs(s * 1000);
1653 Returns the number of seconds from this time to \a t.
1654 If \a t is earlier than this time, the number of seconds returned
1657 Because QTime measures time within a day and there are 86400
1658 seconds in a day, the result is always between -86400 and 86400.
1660 secsTo() does not take into account any milliseconds.
1662 \sa addSecs(), QDateTime::secsTo()
1665 int QTime::secsTo(const QTime &t) const
1667 return (t.ds() - ds()) / 1000;
1671 Returns a QTime object containing a time \a ms milliseconds later
1672 than the time of this object (or earlier if \a ms is negative).
1674 Note that the time will wrap if it passes midnight. See addSecs()
1677 \sa addSecs(), msecsTo(), QDateTime::addMSecs()
1680 QTime QTime::addMSecs(int ms) const
1684 // % not well-defined for -ve, but / is.
1685 int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
1686 t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
1688 t.mds = (ds() + ms) % MSECS_PER_DAY;
1690 #if defined(Q_OS_WINCE)
1691 if (startTick > NullTime)
1692 t.startTick = (startTick + ms) % MSECS_PER_DAY;
1698 Returns the number of milliseconds from this time to \a t.
1699 If \a t is earlier than this time, the number of milliseconds returned
1702 Because QTime measures time within a day and there are 86400
1703 seconds in a day, the result is always between -86400000 and
1706 \sa secsTo(), addMSecs(), QDateTime::msecsTo()
1709 int QTime::msecsTo(const QTime &t) const
1711 #if defined(Q_OS_WINCE)
1712 // GetLocalTime() for Windows CE has no milliseconds resolution
1713 if (t.startTick > NullTime && startTick > NullTime)
1714 return t.startTick - startTick;
1717 return t.ds() - ds();
1722 \fn bool QTime::operator==(const QTime &t) const
1724 Returns true if this time is equal to \a t; otherwise returns false.
1728 \fn bool QTime::operator!=(const QTime &t) const
1730 Returns true if this time is different from \a t; otherwise returns false.
1734 \fn bool QTime::operator<(const QTime &t) const
1736 Returns true if this time is earlier than \a t; otherwise returns false.
1740 \fn bool QTime::operator<=(const QTime &t) const
1742 Returns true if this time is earlier than or equal to \a t;
1743 otherwise returns false.
1747 \fn bool QTime::operator>(const QTime &t) const
1749 Returns true if this time is later than \a t; otherwise returns false.
1753 \fn bool QTime::operator>=(const QTime &t) const
1755 Returns true if this time is later than or equal to \a t;
1756 otherwise returns false.
1760 \fn QTime::currentTime()
1762 Returns the current time as reported by the system clock.
1764 Note that the accuracy depends on the accuracy of the underlying
1765 operating system; not all systems provide 1-millisecond accuracy.
1768 #ifndef QT_NO_DATESTRING
1770 \fn QTime QTime::fromString(const QString &string, Qt::DateFormat format)
1772 Returns the time represented in the \a string as a QTime using the
1773 \a format given, or an invalid time if this is not possible.
1775 Note that fromString() uses a "C" locale encoded string to convert
1776 milliseconds to a float value. If the default locale is not "C",
1777 this may result in two conversion attempts (if the conversion
1778 fails for the default locale). This should be considered an
1779 implementation detail.
1781 QTime QTime::fromString(const QString& s, Qt::DateFormat f)
1790 case Qt::SystemLocaleDate:
1791 case Qt::SystemLocaleShortDate:
1792 case Qt::SystemLocaleLongDate:
1793 return fromString(s, QLocale::system().timeFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
1794 : QLocale::ShortFormat));
1795 case Qt::LocaleDate:
1796 case Qt::DefaultLocaleShortDate:
1797 case Qt::DefaultLocaleLongDate:
1798 return fromString(s, QLocale().timeFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
1799 : QLocale::ShortFormat));
1803 const int hour(s.mid(0, 2).toInt(&ok));
1806 const int minute(s.mid(3, 2).toInt(&ok));
1809 const int second(s.mid(6, 2).toInt(&ok));
1812 const QString msec_s(QLatin1String("0.") + s.mid(9, 4));
1813 const float msec(msec_s.toFloat(&ok));
1815 return QTime(hour, minute, second, 0);
1816 return QTime(hour, minute, second, qMin(qRound(msec * 1000.0), 999));
1822 \fn QTime::fromString(const QString &string, const QString &format)
1824 Returns the QTime represented by the \a string, using the \a
1825 format given, or an invalid time if the string cannot be parsed.
1827 These expressions may be used for the format:
1830 \header \i Expression \i Output
1832 \i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
1834 \i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
1835 \row \i m \i the minute without a leading zero (0 to 59)
1836 \row \i mm \i the minute with a leading zero (00 to 59)
1837 \row \i s \i the second without a leading zero (0 to 59)
1838 \row \i ss \i the second with a leading zero (00 to 59)
1839 \row \i z \i the milliseconds without leading zeroes (0 to 999)
1840 \row \i zzz \i the milliseconds with leading zeroes (000 to 999)
1842 \i interpret as an AM/PM time. \e AP must be either "AM" or "PM".
1844 \i Interpret as an AM/PM time. \e ap must be either "am" or "pm".
1847 All other input characters will be treated as text. Any sequence
1848 of characters that are enclosed in single quotes will also be
1849 treated as text and not be used as an expression.
1851 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 6
1853 If the format is not satisfied an invalid QTime is returned.
1854 Expressions that do not expect leading zeroes to be given (h, m, s
1855 and z) are greedy. This means that they will use two digits even if
1856 this puts them outside the range of accepted values and leaves too
1857 few digits for other sections. For example, the following string
1858 could have meant 00:07:10, but the m will grab two digits, resulting
1861 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 7
1863 Any field that is not represented in the format will be set to zero.
1866 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 8
1868 \sa QDateTime::fromString() QDate::fromString() QDate::toString()
1869 QDateTime::toString() QTime::toString()
1872 QTime QTime::fromString(const QString &string, const QString &format)
1875 #ifndef QT_BOOTSTRAPPED
1876 QDateTimeParser dt(QVariant::Time, QDateTimeParser::FromString);
1877 if (dt.parseFormat(format))
1878 dt.fromString(string, 0, &time);
1886 #endif // QT_NO_DATESTRING
1892 Returns true if the specified time is valid; otherwise returns
1895 The time is valid if \a h is in the range 0 to 23, \a m and
1896 \a s are in the range 0 to 59, and \a ms is in the range 0 to 999.
1900 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 9
1903 bool QTime::isValid(int h, int m, int s, int ms)
1905 return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
1910 Sets this time to the current time. This is practical for timing:
1912 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 10
1914 \sa restart(), elapsed(), currentTime()
1919 *this = currentTime();
1923 Sets this time to the current time and returns the number of
1924 milliseconds that have elapsed since the last time start() or
1925 restart() was called.
1927 This function is guaranteed to be atomic and is thus very handy
1928 for repeated measurements. Call start() to start the first
1929 measurement, and restart() for each later measurement.
1931 Note that the counter wraps to zero 24 hours after the last call
1932 to start() or restart().
1934 \warning If the system's clock setting has been changed since the
1935 last time start() or restart() was called, the result is
1936 undefined. This can happen when daylight savings time is turned on
1939 \sa start(), elapsed(), currentTime()
1942 int QTime::restart()
1944 QTime t = currentTime();
1946 if (n < 0) // passed midnight
1953 Returns the number of milliseconds that have elapsed since the
1954 last time start() or restart() was called.
1956 Note that the counter wraps to zero 24 hours after the last call
1957 to start() or restart.
1959 Note that the accuracy depends on the accuracy of the underlying
1960 operating system; not all systems provide 1-millisecond accuracy.
1962 \warning If the system's clock setting has been changed since the
1963 last time start() or restart() was called, the result is
1964 undefined. This can happen when daylight savings time is turned on
1967 \sa start(), restart()
1970 int QTime::elapsed() const
1972 int n = msecsTo(currentTime());
1973 if (n < 0) // passed midnight
1979 /*****************************************************************************
1980 QDateTime member functions
1981 *****************************************************************************/
1986 \brief The QDateTime class provides date and time functions.
1989 A QDateTime object contains a calendar date and a clock time (a
1990 "datetime"). It is a combination of the QDate and QTime classes.
1991 It can read the current datetime from the system clock. It
1992 provides functions for comparing datetimes and for manipulating a
1993 datetime by adding a number of seconds, days, months, or years.
1995 A QDateTime object is typically created either by giving a date
1996 and time explicitly in the constructor, or by using the static
1997 function currentDateTime() that returns a QDateTime object set
1998 to the system clock's time. The date and time can be changed with
1999 setDate() and setTime(). A datetime can also be set using the
2000 setTime_t() function that takes a POSIX-standard "number of
2001 seconds since 00:00:00 on January 1, 1970" value. The fromString()
2002 function returns a QDateTime, given a string and a date format
2003 used to interpret the date within the string.
2005 The date() and time() functions provide access to the date and
2006 time parts of the datetime. The same information is provided in
2007 textual format by the toString() function.
2009 QDateTime provides a full set of operators to compare two
2010 QDateTime objects where smaller means earlier and larger means
2013 You can increment (or decrement) a datetime by a given number of
2014 milliseconds using addMSecs(), seconds using addSecs(), or days
2015 using addDays(). Similarly you can use addMonths() and addYears().
2016 The daysTo() function returns the number of days between two datetimes,
2017 secsTo() returns the number of seconds between two datetimes, and
2018 msecsTo() returns the number of milliseconds between two datetimes.
2020 QDateTime can store datetimes as \l{Qt::LocalTime}{local time} or
2021 as \l{Qt::UTC}{UTC}. QDateTime::currentDateTime() returns a
2022 QDateTime expressed as local time; use toUTC() to convert it to
2023 UTC. You can also use timeSpec() to find out if a QDateTime
2024 object stores a UTC time or a local time. Operations such as
2025 addSecs() and secsTo() are aware of daylight saving time (DST).
2027 \note QDateTime does not account for leap seconds.
2031 \target QDateTime G and J
2032 \section2 Use of Gregorian and Julian Calendars
2034 QDate uses the Gregorian calendar in all locales, beginning
2035 on the date 15 October 1582. For dates up to and including 4
2036 October 1582, the Julian calendar is used. This means there is a
2037 10-day gap in the internal calendar between the 4th and the 15th
2038 of October 1582. When you use QDateTime for dates in that epoch,
2039 the day after 4 October 1582 is 15 October 1582, and the dates in
2040 the gap are invalid.
2042 The Julian to Gregorian changeover date used here is the date when
2043 the Gregorian calendar was first introduced, by Pope Gregory
2044 XIII. That change was not universally accepted and some localities
2045 only executed it at a later date (if at all). QDateTime
2046 doesn't take any of these historical facts into account. If an
2047 application must support a locale-specific dating system, it must
2048 do so on its own, remembering to convert the dates using the
2053 There is no year 0. Dates in that year are considered invalid. The
2054 year -1 is the year "1 before Christ" or "1 before current era."
2055 The day before 0001-01-01 is December 31st, 1 BCE.
2057 \section2 Range of Valid Dates
2059 The range of valid dates is from January 2nd, 4713 BCE, to
2060 sometime in the year 11 million CE. The Julian Day returned by
2061 QDate::toJulianDay() is a number in the contiguous range from 1 to
2062 \e{overflow}, even across QDateTime's "date holes". It is suitable
2063 for use in applications that must convert a QDateTime to a date in
2064 another calendar system, e.g., Hebrew, Islamic or Chinese.
2066 The Gregorian calendar was introduced in different places around
2067 the world on different dates. QDateTime uses QDate to store the
2068 date, so it uses the Gregorian calendar for all locales, beginning
2069 on the date 15 October 1582. For dates up to and including 4
2070 October 1582, QDateTime uses the Julian calendar. This means
2071 there is a 10-day gap in the QDateTime calendar between the 4th
2072 and the 15th of October 1582. When you use QDateTime for dates in
2073 that epoch, the day after 4 October 1582 is 15 October 1582, and
2074 the dates in the gap are invalid.
2077 Use of System Timezone
2079 QDateTime uses the system's time zone information to determine the
2080 offset of local time from UTC. If the system is not configured
2081 correctly or not up-to-date, QDateTime will give wrong results as
2084 \section2 Daylight Savings Time (DST)
2086 QDateTime takes into account the system's time zone information
2087 when dealing with DST. On modern Unix systems, this means it
2088 applies the correct historical DST data whenever possible. On
2089 Windows and Windows CE, where the system doesn't support
2090 historical DST data, historical accuracy is not maintained with
2093 The range of valid dates taking DST into account is 1970-01-01 to
2094 the present, and rules are in place for handling DST correctly
2095 until 2037-12-31, but these could change. For dates falling
2096 outside that range, QDateTime makes a \e{best guess} using the
2097 rules for year 1970 or 2037, but we can't guarantee accuracy. This
2098 means QDateTime doesn't take into account changes in a locale's
2099 time zone before 1970, even if the system's time zone database
2100 supports that information.
2102 \sa QDate QTime QDateTimeEdit
2106 Constructs a null datetime (i.e. null date and null time). A null
2107 datetime is invalid, since the date is invalid.
2111 QDateTime::QDateTime()
2112 : d(new QDateTimePrivate)
2118 Constructs a datetime with the given \a date, a valid
2119 time(00:00:00.000), and sets the timeSpec() to Qt::LocalTime.
2122 QDateTime::QDateTime(const QDate &date)
2123 : d(new QDateTimePrivate)
2126 d->time = QTime(0, 0, 0);
2130 Constructs a datetime with the given \a date and \a time, using
2131 the time specification defined by \a spec.
2133 If \a date is valid and \a time is not, the time will be set to midnight.
2136 QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec)
2137 : d(new QDateTimePrivate)
2140 d->time = date.isValid() && !time.isValid() ? QTime(0, 0, 0) : time;
2141 d->spec = (spec == Qt::UTC) ? QDateTimePrivate::UTC : QDateTimePrivate::LocalUnknown;
2145 Constructs a copy of the \a other datetime.
2148 QDateTime::QDateTime(const QDateTime &other)
2154 Destroys the datetime.
2156 QDateTime::~QDateTime()
2161 Makes a copy of the \a other datetime and returns a reference to the
2165 QDateTime &QDateTime::operator=(const QDateTime &other)
2172 Returns true if both the date and the time are null; otherwise
2173 returns false. A null datetime is invalid.
2175 \sa QDate::isNull(), QTime::isNull(), isValid()
2178 bool QDateTime::isNull() const
2180 return d->date.isNull() && d->time.isNull();
2184 Returns true if both the date and the time are valid; otherwise
2187 \sa QDate::isValid(), QTime::isValid()
2190 bool QDateTime::isValid() const
2192 return d->date.isValid() && d->time.isValid();
2196 Returns the date part of the datetime.
2198 \sa setDate(), time(), timeSpec()
2201 QDate QDateTime::date() const
2207 Returns the time part of the datetime.
2209 \sa setTime(), date(), timeSpec()
2212 QTime QDateTime::time() const
2218 Returns the time specification of the datetime.
2220 \sa setTimeSpec(), date(), time(), Qt::TimeSpec
2223 Qt::TimeSpec QDateTime::timeSpec() const
2227 case QDateTimePrivate::UTC:
2229 case QDateTimePrivate::OffsetFromUTC:
2230 return Qt::OffsetFromUTC;
2232 return Qt::LocalTime;
2237 Sets the date part of this datetime to \a date.
2238 If no time is set, it is set to midnight.
2240 \sa date(), setTime(), setTimeSpec()
2243 void QDateTime::setDate(const QDate &date)
2247 if (d->spec == QDateTimePrivate::LocalStandard
2248 || d->spec == QDateTimePrivate::LocalDST)
2249 d->spec = QDateTimePrivate::LocalUnknown;
2250 if (date.isValid() && !d->time.isValid())
2251 d->time = QTime(0, 0, 0);
2255 Sets the time part of this datetime to \a time.
2257 \sa time(), setDate(), setTimeSpec()
2260 void QDateTime::setTime(const QTime &time)
2263 if (d->spec == QDateTimePrivate::LocalStandard
2264 || d->spec == QDateTimePrivate::LocalDST)
2265 d->spec = QDateTimePrivate::LocalUnknown;
2270 Sets the time specification used in this datetime to \a spec.
2272 \sa timeSpec(), setDate(), setTime(), Qt::TimeSpec
2275 void QDateTime::setTimeSpec(Qt::TimeSpec spec)
2282 d->spec = QDateTimePrivate::UTC;
2284 case Qt::OffsetFromUTC:
2285 d->spec = QDateTimePrivate::OffsetFromUTC;
2288 d->spec = QDateTimePrivate::LocalUnknown;
2293 qint64 toMSecsSinceEpoch_helper(qint64 jd, int msecs)
2295 qint64 days = jd - JULIAN_DAY_FOR_EPOCH;
2296 qint64 retval = (days * MSECS_PER_DAY) + msecs;
2303 Returns the datetime as the number of milliseconds that have passed
2304 since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
2306 On systems that do not support time zones, this function will
2307 behave as if local time were Qt::UTC.
2309 The behavior for this function is undefined if the datetime stored in
2310 this object is not valid. However, for all valid dates, this function
2311 returns a unique value.
2313 \sa toTime_t(), setMSecsSinceEpoch()
2315 qint64 QDateTime::toMSecsSinceEpoch() const
2319 d->getUTC(utcDate, utcTime);
2321 return toMSecsSinceEpoch_helper(utcDate.jd, utcTime.ds());
2325 Returns the datetime as the number of seconds that have passed
2326 since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).
2328 On systems that do not support time zones, this function will
2329 behave as if local time were Qt::UTC.
2331 \note This function returns a 32-bit unsigned integer, so it does not
2332 support dates before 1970, but it does support dates after
2333 2038-01-19T03:14:06, which may not be valid time_t values. Be careful
2334 when passing those time_t values to system functions, which could
2335 interpret them as negative dates.
2337 If the date is outside the range 1970-01-01T00:00:00 to
2338 2106-02-07T06:28:14, this function returns -1 cast to an unsigned integer
2341 To get an extended range, use toMSecsSinceEpoch().
2343 \sa toMSecsSinceEpoch(), setTime_t()
2346 uint QDateTime::toTime_t() const
2348 qint64 retval = toMSecsSinceEpoch() / 1000;
2349 if (quint64(retval) >= Q_UINT64_C(0xFFFFFFFF))
2351 return uint(retval);
2357 Sets the date and time given the number of milliseconds,\a msecs, that have
2358 passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
2359 (Qt::UTC). On systems that do not support time zones this function
2360 will behave as if local time were Qt::UTC.
2362 Note that there are possible values for \a msecs that lie outside the
2363 valid range of QDateTime, both negative and positive. The behavior of
2364 this function is undefined for those values.
2366 \sa toMSecsSinceEpoch(), setTime_t()
2368 void QDateTime::setMSecsSinceEpoch(qint64 msecs)
2372 QDateTimePrivate::Spec oldSpec = d->spec;
2374 int ddays = msecs / MSECS_PER_DAY;
2375 msecs %= MSECS_PER_DAY;
2379 msecs += MSECS_PER_DAY;
2382 d->date = QDate(1970, 1, 1).addDays(ddays);
2383 d->time = QTime().addMSecs(msecs);
2384 d->spec = QDateTimePrivate::UTC;
2386 if (oldSpec != QDateTimePrivate::UTC)
2387 d->spec = d->getLocal(d->date, d->time);
2391 \fn void QDateTime::setTime_t(uint seconds)
2393 Sets the date and time given the number of \a seconds that have
2394 passed since 1970-01-01T00:00:00, Coordinated Universal Time
2395 (Qt::UTC). On systems that do not support time zones this function
2396 will behave as if local time were Qt::UTC.
2401 void QDateTime::setTime_t(uint secsSince1Jan1970UTC)
2405 QDateTimePrivate::Spec oldSpec = d->spec;
2407 d->date = QDate(1970, 1, 1).addDays(secsSince1Jan1970UTC / SECS_PER_DAY);
2408 d->time = QTime().addSecs(secsSince1Jan1970UTC % SECS_PER_DAY);
2409 d->spec = QDateTimePrivate::UTC;
2411 if (oldSpec != QDateTimePrivate::UTC)
2412 d->spec = d->getLocal(d->date, d->time);
2415 #ifndef QT_NO_DATESTRING
2417 \fn QString QDateTime::toString(Qt::DateFormat format) const
2421 Returns the datetime as a string in the \a format given.
2423 If the \a format is Qt::TextDate, the string is formatted in
2424 the default way. QDate::shortDayName(), QDate::shortMonthName(),
2425 and QTime::toString() are used to generate the string, so the
2426 day and month names will be localized names. An example of this
2427 formatting is "Wed May 20 03:40:13 1998".
2429 If the \a format is Qt::ISODate, the string format corresponds
2430 to the ISO 8601 extended specification for representations of
2431 dates and times, taking the form YYYY-MM-DDTHH:mm:ss[Z|[+|-]HH:mm],
2432 depending on the timeSpec() of the QDateTime. If the timeSpec()
2433 is Qt::UTC, Z will be appended to the string; if the timeSpec() is
2434 Qt::OffsetFromUTC the offset in hours and minutes from UTC will
2435 be appended to the string.
2437 If the \a format is Qt::SystemLocaleShortDate or
2438 Qt::SystemLocaleLongDate, the string format depends on the locale
2439 settings of the system. Identical to calling
2440 QLocale::system().toString(datetime, QLocale::ShortFormat) or
2441 QLocale::system().toString(datetime, QLocale::LongFormat).
2443 If the \a format is Qt::DefaultLocaleShortDate or
2444 Qt::DefaultLocaleLongDate, the string format depends on the
2445 default application locale. This is the locale set with
2446 QLocale::setDefault(), or the system locale if no default locale
2447 has been set. Identical to calling QLocale().toString(datetime,
2448 QLocale::ShortFormat) or QLocale().toString(datetime,
2449 QLocale::LongFormat).
2451 If the datetime is invalid, an empty string will be returned.
2453 \warning The Qt::ISODate format is only valid for years in the
2454 range 0 to 9999. This restriction may apply to locale-aware
2455 formats as well, depending on the locale settings.
2457 \sa QDate::toString() QTime::toString() Qt::DateFormat
2460 QString QDateTime::toString(Qt::DateFormat f) const
2466 if (f == Qt::ISODate) {
2467 buf = d->date.toString(Qt::ISODate);
2469 return QString(); // failed to convert
2470 buf += QLatin1Char('T');
2471 buf += d->time.toString(Qt::ISODate);
2473 case QDateTimePrivate::UTC:
2474 buf += QLatin1Char('Z');
2476 case QDateTimePrivate::OffsetFromUTC: {
2477 int sign = d->utcOffset >= 0 ? 1: -1;
2478 buf += QString::fromLatin1("%1%2:%3").
2479 arg(sign == 1 ? QLatin1Char('+') : QLatin1Char('-')).
2480 arg(d->utcOffset * sign / SECS_PER_HOUR, 2, 10, QLatin1Char('0')).
2481 arg((d->utcOffset / 60) % 60, 2, 10, QLatin1Char('0'));
2488 #ifndef QT_NO_TEXTDATE
2489 else if (f == Qt::TextDate) {
2491 buf = d->date.shortDayName(d->date.dayOfWeek());
2492 buf += QLatin1Char(' ');
2493 buf += d->date.shortMonthName(d->date.month());
2494 buf += QLatin1Char(' ');
2495 buf += QString::number(d->date.day());
2498 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ILDATE, out, 255);
2499 QString winstr = QString::fromWCharArray(out);
2500 switch (winstr.toInt()) {
2502 buf = d->date.shortDayName(d->date.dayOfWeek());
2503 buf += QLatin1Char(' ');
2504 buf += QString::number(d->date.day());
2505 buf += QLatin1String(". ");
2506 buf += d->date.shortMonthName(d->date.month());
2509 buf = d->date.shortDayName(d->date.dayOfWeek());
2510 buf += QLatin1Char(' ');
2511 buf += d->date.shortMonthName(d->date.month());
2512 buf += QLatin1Char(' ');
2513 buf += QString::number(d->date.day());
2516 buf += QLatin1Char(' ');
2517 buf += d->time.toString();
2518 buf += QLatin1Char(' ');
2519 buf += QString::number(d->date.year());
2523 buf = d->date.toString(f);
2525 return QString(); // failed to convert
2526 buf += QLatin1Char(' ');
2527 buf += d->time.toString(f);
2534 Returns the datetime as a string. The \a format parameter
2535 determines the format of the result string.
2537 These expressions may be used for the date:
2540 \header \i Expression \i Output
2541 \row \i d \i the day as number without a leading zero (1 to 31)
2542 \row \i dd \i the day as number with a leading zero (01 to 31)
2544 \i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
2545 Uses QDate::shortDayName().
2547 \i the long localized day name (e.g. 'Monday' to 'Qt::Sunday').
2548 Uses QDate::longDayName().
2549 \row \i M \i the month as number without a leading zero (1-12)
2550 \row \i MM \i the month as number with a leading zero (01-12)
2552 \i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
2553 Uses QDate::shortMonthName().
2555 \i the long localized month name (e.g. 'January' to 'December').
2556 Uses QDate::longMonthName().
2557 \row \i yy \i the year as two digit number (00-99)
2558 \row \i yyyy \i the year as four digit number
2561 These expressions may be used for the time:
2564 \header \i Expression \i Output
2566 \i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
2568 \i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
2569 \row \i m \i the minute without a leading zero (0 to 59)
2570 \row \i mm \i the minute with a leading zero (00 to 59)
2571 \row \i s \i the second without a leading zero (0 to 59)
2572 \row \i ss \i the second with a leading zero (00 to 59)
2573 \row \i z \i the milliseconds without leading zeroes (0 to 999)
2574 \row \i zzz \i the milliseconds with leading zeroes (000 to 999)
2576 \i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
2578 \i use am/pm display. \e ap will be replaced by either "am" or "pm".
2581 All other input characters will be ignored. Any sequence of characters that
2582 are enclosed in singlequotes will be treated as text and not be used as an
2583 expression. Two consecutive singlequotes ("''") are replaced by a singlequote
2586 Example format strings (assumed that the QDateTime is 21 May 2001
2590 \header \i Format \i Result
2591 \row \i dd.MM.yyyy \i 21.05.2001
2592 \row \i ddd MMMM d yy \i Tue May 21 01
2593 \row \i hh:mm:ss.zzz \i 14:13:09.042
2594 \row \i h:m:s ap \i 2:13:9 pm
2597 If the datetime is invalid, an empty string will be returned.
2599 \sa QDate::toString() QTime::toString()
2601 QString QDateTime::toString(const QString& format) const
2603 return fmtDateTime(format, &d->time, &d->date);
2605 #endif //QT_NO_DATESTRING
2608 Returns a QDateTime object containing a datetime \a ndays days
2609 later than the datetime of this object (or earlier if \a ndays is
2612 \sa daysTo(), addMonths(), addYears(), addSecs()
2615 QDateTime QDateTime::addDays(int ndays) const
2617 return QDateTime(d->date.addDays(ndays), d->time, timeSpec());
2621 Returns a QDateTime object containing a datetime \a nmonths months
2622 later than the datetime of this object (or earlier if \a nmonths
2625 \sa daysTo(), addDays(), addYears(), addSecs()
2628 QDateTime QDateTime::addMonths(int nmonths) const
2630 return QDateTime(d->date.addMonths(nmonths), d->time, timeSpec());
2634 Returns a QDateTime object containing a datetime \a nyears years
2635 later than the datetime of this object (or earlier if \a nyears is
2638 \sa daysTo(), addDays(), addMonths(), addSecs()
2641 QDateTime QDateTime::addYears(int nyears) const
2643 return QDateTime(d->date.addYears(nyears), d->time, timeSpec());
2646 QDateTime QDateTimePrivate::addMSecs(const QDateTime &dt, qint64 msecs)
2650 dt.d->getUTC(utcDate, utcTime);
2652 addMSecs(utcDate, utcTime, msecs);
2654 return QDateTime(utcDate, utcTime, Qt::UTC).toTimeSpec(dt.timeSpec());
2658 Adds \a msecs to utcDate and \a utcTime as appropriate. It is assumed that
2659 utcDate and utcTime are adjusted to UTC.
2664 void QDateTimePrivate::addMSecs(QDate &utcDate, QTime &utcTime, qint64 msecs)
2666 uint dd = utcDate.jd;
2667 int tt = utcTime.ds();
2673 if (msecs >= int(MSECS_PER_DAY)) {
2674 dd += sign * (msecs / MSECS_PER_DAY);
2675 msecs %= MSECS_PER_DAY;
2680 tt = MSECS_PER_DAY - tt - 1;
2681 dd -= tt / MSECS_PER_DAY;
2682 tt = tt % MSECS_PER_DAY;
2683 tt = MSECS_PER_DAY - tt - 1;
2684 } else if (tt >= int(MSECS_PER_DAY)) {
2685 dd += tt / MSECS_PER_DAY;
2686 tt = tt % MSECS_PER_DAY;
2694 Returns a QDateTime object containing a datetime \a s seconds
2695 later than the datetime of this object (or earlier if \a s is
2698 \sa addMSecs(), secsTo(), addDays(), addMonths(), addYears()
2701 QDateTime QDateTime::addSecs(int s) const
2703 return d->addMSecs(*this, qint64(s) * 1000);
2707 Returns a QDateTime object containing a datetime \a msecs miliseconds
2708 later than the datetime of this object (or earlier if \a msecs is
2711 \sa addSecs(), msecsTo(), addDays(), addMonths(), addYears()
2713 QDateTime QDateTime::addMSecs(qint64 msecs) const
2715 return d->addMSecs(*this, msecs);
2719 Returns the number of days from this datetime to the \a other
2720 datetime. If the \a other datetime is earlier than this datetime,
2721 the value returned is negative.
2723 \sa addDays(), secsTo(), msecsTo()
2726 int QDateTime::daysTo(const QDateTime &other) const
2728 return d->date.daysTo(other.d->date);
2732 Returns the number of seconds from this datetime to the \a other
2733 datetime. If the \a other datetime is earlier than this datetime,
2734 the value returned is negative.
2736 Before performing the comparison, the two datetimes are converted
2737 to Qt::UTC to ensure that the result is correct if one of the two
2738 datetimes has daylight saving time (DST) and the other doesn't.
2741 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 11
2743 \sa addSecs(), daysTo(), QTime::secsTo()
2746 int QDateTime::secsTo(const QDateTime &other) const
2751 d->getUTC(date1, time1);
2752 other.d->getUTC(date2, time2);
2754 return (date1.daysTo(date2) * SECS_PER_DAY) + time1.secsTo(time2);
2760 Returns the number of milliseconds from this datetime to the \a other
2761 datetime. If the \a other datetime is earlier than this datetime,
2762 the value returned is negative.
2764 Before performing the comparison, the two datetimes are converted
2765 to Qt::UTC to ensure that the result is correct if one of the two
2766 datetimes has daylight saving time (DST) and the other doesn't.
2768 \sa addMSecs(), daysTo(), QTime::msecsTo()
2771 qint64 QDateTime::msecsTo(const QDateTime &other) const
2778 d->getUTC(selfDate, selfTime);
2779 other.d->getUTC(otherDate, otherTime);
2781 return (static_cast<qint64>(selfDate.daysTo(otherDate)) * static_cast<qint64>(MSECS_PER_DAY))
2782 + static_cast<qint64>(selfTime.msecsTo(otherTime));
2787 \fn QDateTime QDateTime::toTimeSpec(Qt::TimeSpec specification) const
2789 Returns a copy of this datetime configured to use the given time
2792 \sa timeSpec(), toUTC(), toLocalTime()
2795 QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const
2797 if ((d->spec == QDateTimePrivate::UTC) == (spec == Qt::UTC))
2801 if (spec == Qt::UTC) {
2802 d->getUTC(ret.d->date, ret.d->time);
2803 ret.d->spec = QDateTimePrivate::UTC;
2805 ret.d->spec = d->getLocal(ret.d->date, ret.d->time);
2811 Returns true if this datetime is equal to the \a other datetime;
2812 otherwise returns false.
2817 bool QDateTime::operator==(const QDateTime &other) const
2819 if (d->spec == other.d->spec && d->utcOffset == other.d->utcOffset)
2820 return d->time == other.d->time && d->date == other.d->date;
2825 d->getUTC(date1, time1);
2826 other.d->getUTC(date2, time2);
2827 return time1 == time2 && date1 == date2;
2832 \fn bool QDateTime::operator!=(const QDateTime &other) const
2834 Returns true if this datetime is different from the \a other
2835 datetime; otherwise returns false.
2837 Two datetimes are different if either the date, the time, or the
2838 time zone components are different.
2844 Returns true if this datetime is earlier than the \a other
2845 datetime; otherwise returns false.
2848 bool QDateTime::operator<(const QDateTime &other) const
2850 if (d->spec == other.d->spec && d->spec != QDateTimePrivate::OffsetFromUTC) {
2851 if (d->date != other.d->date)
2852 return d->date < other.d->date;
2853 return d->time < other.d->time;
2857 d->getUTC(date1, time1);
2858 other.d->getUTC(date2, time2);
2860 return date1 < date2;
2861 return time1 < time2;
2866 \fn bool QDateTime::operator<=(const QDateTime &other) const
2868 Returns true if this datetime is earlier than or equal to the
2869 \a other datetime; otherwise returns false.
2873 \fn bool QDateTime::operator>(const QDateTime &other) const
2875 Returns true if this datetime is later than the \a other datetime;
2876 otherwise returns false.
2880 \fn bool QDateTime::operator>=(const QDateTime &other) const
2882 Returns true if this datetime is later than or equal to the
2883 \a other datetime; otherwise returns false.
2887 \fn QDateTime QDateTime::currentDateTime()
2888 Returns the current datetime, as reported by the system clock, in
2889 the local time zone.
2891 \sa currentDateTimeUtc(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
2895 \fn QDateTime QDateTime::currentDateTimeUtc()
2897 Returns the current datetime, as reported by the system clock, in
2900 \sa currentDateTime(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
2904 \fn qint64 QDateTime::currentMSecsSinceEpoch()
2907 Returns the number of milliseconds since 1970-01-01T00:00:00 Universal
2908 Coordinated Time. This number is like the POSIX time_t variable, but
2909 expressed in milliseconds instead.
2911 \sa currentDateTime(), currentDateTimeUtc(), toTime_t(), toTimeSpec()
2914 static inline uint msecsFromDecomposed(int hour, int minute, int sec, int msec = 0)
2916 return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute + 1000 * sec + msec;
2919 #if defined(Q_OS_WIN)
2920 QDate QDate::currentDate()
2924 memset(&st, 0, sizeof(SYSTEMTIME));
2926 d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
2930 QTime QTime::currentTime()
2934 memset(&st, 0, sizeof(SYSTEMTIME));
2936 ct.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
2937 #if defined(Q_OS_WINCE)
2938 ct.startTick = GetTickCount() % MSECS_PER_DAY;
2943 QDateTime QDateTime::currentDateTime()
2948 memset(&st, 0, sizeof(SYSTEMTIME));
2950 d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
2951 t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
2952 return QDateTime(d, t);
2955 QDateTime QDateTime::currentDateTimeUtc()
2960 memset(&st, 0, sizeof(SYSTEMTIME));
2962 d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
2963 t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
2964 return QDateTime(d, t, Qt::UTC);
2967 qint64 QDateTime::currentMSecsSinceEpoch()
2972 memset(&st, 0, sizeof(SYSTEMTIME));
2975 return msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds) +
2976 qint64(julianDayFromGregorianDate(st.wYear, st.wMonth, st.wDay)
2977 - julianDayFromGregorianDate(1970, 1, 1)) * Q_INT64_C(86400000);
2980 #elif defined(Q_OS_SYMBIAN)
2981 QDate QDate::currentDate()
2985 localTime.HomeTime();
2986 TDateTime localDateTime = localTime.DateTime();
2987 // months and days are zero indexed
2988 d.jd = julianDayFromDate(localDateTime.Year(), localDateTime.Month() + 1, localDateTime.Day() + 1 );
2992 QTime QTime::currentTime()
2996 localTime.HomeTime();
2997 TDateTime localDateTime = localTime.DateTime();
2998 ct.mds = msecsFromDecomposed(localDateTime.Hour(), localDateTime.Minute(),
2999 localDateTime.Second(), localDateTime.MicroSecond() / 1000);
3003 QDateTime QDateTime::currentDateTime()
3008 localTime.HomeTime();
3009 TDateTime localDateTime = localTime.DateTime();
3010 // months and days are zero indexed
3011 d.jd = julianDayFromDate(localDateTime.Year(), localDateTime.Month() + 1, localDateTime.Day() + 1);
3012 ct.mds = msecsFromDecomposed(localDateTime.Hour(), localDateTime.Minute(),
3013 localDateTime.Second(), localDateTime.MicroSecond() / 1000);
3014 return QDateTime(d, ct);
3017 QDateTime QDateTime::currentDateTimeUtc()
3022 gmTime.UniversalTime();
3023 TDateTime gmtDateTime = gmTime.DateTime();
3024 // months and days are zero indexed
3025 d.jd = julianDayFromDate(gmtDateTime.Year(), gmtDateTime.Month() + 1, gmtDateTime.Day() + 1);
3026 ct.mds = msecsFromDecomposed(gmtDateTime.Hour(), gmtDateTime.Minute(),
3027 gmtDateTime.Second(), gmtDateTime.MicroSecond() / 1000);
3028 return QDateTime(d, ct, Qt::UTC);
3031 qint64 QDateTime::currentMSecsSinceEpoch()
3036 gmTime.UniversalTime();
3037 TDateTime gmtDateTime = gmTime.DateTime();
3039 // according to the documentation, the value is:
3040 // "a date and time as a number of microseconds since midnight, January 1st, 0 AD nominal Gregorian"
3041 qint64 value = gmTime.Int64();
3043 // whereas 1970-01-01T00:00:00 is (in the same representation):
3044 // ((1970 * 365) + (1970 / 4) - (1970 / 100) + (1970 / 400) - 13) * 86400 * 1000000
3045 static const qint64 unixEpoch = Q_INT64_C(0xdcddb30f2f8000);
3047 return (value - unixEpoch) / 1000;
3050 #elif defined(Q_OS_UNIX)
3051 QDate QDate::currentDate()
3054 // posix compliant system
3059 #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3060 // use the reentrant version of localtime() where available
3063 t = localtime_r(<ime, &res);
3065 t = localtime(<ime);
3066 #endif // !QT_NO_THREAD && _POSIX_THREAD_SAFE_FUNCTIONS
3068 d.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
3072 QTime QTime::currentTime()
3075 // posix compliant system
3077 gettimeofday(&tv, 0);
3078 time_t ltime = tv.tv_sec;
3081 #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3082 // use the reentrant version of localtime() where available
3085 t = localtime_r(<ime, &res);
3087 t = localtime(<ime);
3091 ct.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
3095 QDateTime QDateTime::currentDateTime()
3097 // posix compliant system
3098 // we have milliseconds
3100 gettimeofday(&tv, 0);
3101 time_t ltime = tv.tv_sec;
3104 #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3105 // use the reentrant version of localtime() where available
3108 t = localtime_r(<ime, &res);
3110 t = localtime(<ime);
3114 dt.d->time.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
3116 dt.d->date.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
3117 dt.d->spec = t->tm_isdst > 0 ? QDateTimePrivate::LocalDST :
3118 t->tm_isdst == 0 ? QDateTimePrivate::LocalStandard :
3119 QDateTimePrivate::LocalUnknown;
3123 QDateTime QDateTime::currentDateTimeUtc()
3125 // posix compliant system
3126 // we have milliseconds
3128 gettimeofday(&tv, 0);
3129 time_t ltime = tv.tv_sec;
3132 #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3133 // use the reentrant version of localtime() where available
3135 t = gmtime_r(<ime, &res);
3141 dt.d->time.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
3143 dt.d->date.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
3144 dt.d->spec = QDateTimePrivate::UTC;
3148 qint64 QDateTime::currentMSecsSinceEpoch()
3150 // posix compliant system
3151 // we have milliseconds
3153 gettimeofday(&tv, 0);
3154 return qint64(tv.tv_sec) * Q_INT64_C(1000) + tv.tv_usec / 1000;
3158 #error "What system is this?"
3164 Returns a datetime whose date and time are the number of \a seconds
3165 that have passed since 1970-01-01T00:00:00, Coordinated Universal
3166 Time (Qt::UTC). On systems that do not support time zones, the time
3167 will be set as if local time were Qt::UTC.
3169 \sa toTime_t(), setTime_t()
3171 QDateTime QDateTime::fromTime_t(uint seconds)
3174 d.setTime_t(seconds);
3181 Returns a datetime whose date and time are the number of milliseconds, \a msecs,
3182 that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
3183 Time (Qt::UTC). On systems that do not support time zones, the time
3184 will be set as if local time were Qt::UTC.
3186 Note that there are possible values for \a msecs that lie outside the valid
3187 range of QDateTime, both negative and positive. The behavior of this
3188 function is undefined for those values.
3190 \sa toTime_t(), setTime_t()
3192 QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs)
3195 d.setMSecsSinceEpoch(msecs);
3203 Sets the offset from UTC to \a seconds, and also sets timeSpec() to
3206 The maximum and minimum offset is 14 positive or negative hours. If
3207 \a seconds is larger or smaller than that, the result is undefined.
3209 0 as offset is identical to UTC. Therefore, if \a seconds is 0, the
3210 timeSpec() will be set to Qt::UTC. Hence the UTC offset always
3211 relates to UTC, and can never relate to local time.
3213 \sa isValid(), utcOffset()
3215 void QDateTime::setUtcOffset(int seconds)
3219 /* The motivation to also setting d->spec is to ensure that the QDateTime
3220 * instance stay in well-defined states all the time, instead of that
3221 * we instruct the user to ensure it. */
3223 d->spec = QDateTimePrivate::UTC;
3225 d->spec = QDateTimePrivate::OffsetFromUTC;
3227 /* Even if seconds is 0 we assign it to utcOffset. */
3228 d->utcOffset = seconds;
3235 Returns the UTC offset in seconds. If the timeSpec() isn't
3236 Qt::OffsetFromUTC, 0 is returned. However, since 0 is a valid UTC
3237 offset the return value of this function cannot be used to determine
3238 whether a utcOffset() is used or is valid, timeSpec() must be
3241 Likewise, if this QDateTime() is invalid or if timeSpec() isn't
3242 Qt::OffsetFromUTC, 0 is returned.
3244 The UTC offset only applies if the timeSpec() is Qt::OffsetFromUTC.
3246 \sa isValid(), setUtcOffset()
3248 int QDateTime::utcOffset() const
3250 if(isValid() && d->spec == QDateTimePrivate::OffsetFromUTC)
3251 return d->utcOffset;
3256 #ifndef QT_NO_DATESTRING
3258 static int fromShortMonthName(const QString &monthName)
3260 // Assume that English monthnames are the default
3261 for (int i = 0; i < 12; ++i) {
3262 if (monthName == QLatin1String(qt_shortMonthNames[i]))
3265 // If English names can't be found, search the localized ones
3266 for (int i = 1; i <= 12; ++i) {
3267 if (monthName == QDate::shortMonthName(i))
3274 \fn QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
3276 Returns the QDateTime represented by the \a string, using the
3277 \a format given, or an invalid datetime if this is not possible.
3279 Note for Qt::TextDate: It is recommended that you use the
3280 English short month names (e.g. "Jan"). Although localized month
3281 names can also be used, they depend on the user's locale settings.
3283 QDateTime QDateTime::fromString(const QString& s, Qt::DateFormat f)
3292 Qt::TimeSpec ts = Qt::LocalTime;
3293 const QDate date = QDate::fromString(tmp.left(10), Qt::ISODate);
3294 if (tmp.size() == 10)
3295 return QDateTime(date);
3299 // Recognize UTC specifications
3300 if (tmp.endsWith(QLatin1Char('Z'))) {
3305 // Recognize timezone specifications
3306 QRegExp rx(QLatin1String("[+-]"));
3307 if (tmp.contains(rx)) {
3308 int idx = tmp.indexOf(rx);
3309 QString tmp2 = tmp.mid(idx);
3310 tmp = tmp.left(idx);
3314 if ( tmp2.indexOf(QLatin1Char(':')) == 3 )
3316 const int tzhour(tmp2.mid(ntzhour, 2).toInt(&ok));
3317 const int tzminute(tmp2.mid(ntzminute, 2).toInt(&ok));
3318 QTime tzt(tzhour, tzminute);
3319 int utcOffset = (tzt.hour() * 60 + tzt.minute()) * 60;
3320 if ( utcOffset != 0 ) {
3321 ts = Qt::OffsetFromUTC;
3322 QDateTime dt(date, QTime::fromString(tmp, Qt::ISODate), ts);
3323 dt.setUtcOffset( utcOffset * (tmp2.startsWith(QLatin1Char('-')) ? -1 : 1) );
3327 return QDateTime(date, QTime::fromString(tmp, Qt::ISODate), ts);
3329 case Qt::SystemLocaleDate:
3330 case Qt::SystemLocaleShortDate:
3331 case Qt::SystemLocaleLongDate:
3332 return fromString(s, QLocale::system().dateTimeFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
3333 : QLocale::ShortFormat));
3334 case Qt::LocaleDate:
3335 case Qt::DefaultLocaleShortDate:
3336 case Qt::DefaultLocaleLongDate:
3337 return fromString(s, QLocale().dateTimeFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
3338 : QLocale::ShortFormat));
3339 #if !defined(QT_NO_TEXTDATE)
3340 case Qt::TextDate: {
3341 QStringList parts = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
3343 if ((parts.count() < 5) || (parts.count() > 6)) {
3347 // Accept "Sun Dec 1 13:02:00 1974" and "Sun 1. Dec 13:02:00 1974"
3348 int month = -1, day = -1;
3351 month = fromShortMonthName(parts.at(1));
3353 day = parts.at(2).toInt(&ok);
3358 if (month == -1 || day == -1) {
3359 // first variant failed, lets try the other
3360 month = fromShortMonthName(parts.at(2));
3362 QString dayStr = parts.at(1);
3363 if (dayStr.endsWith(QLatin1Char('.'))) {
3365 day = dayStr.toInt(&ok);
3374 if (month == -1 || day == -1) {
3375 // both variants failed, give up
3380 QStringList timeParts = parts.at(3).split(QLatin1Char(':'));
3381 if ((timeParts.count() == 3) || (timeParts.count() == 2)) {
3382 year = parts.at(4).toInt(&ok);
3386 timeParts = parts.at(4).split(QLatin1Char(':'));
3387 if ((timeParts.count() != 3) && (timeParts.count() != 2))
3389 year = parts.at(3).toInt(&ok);
3394 int hour = timeParts.at(0).toInt(&ok);
3399 int minute = timeParts.at(1).toInt(&ok);
3404 int second = (timeParts.count() > 2) ? timeParts.at(2).toInt(&ok) : 0;
3409 QDate date(year, month, day);
3410 QTime time(hour, minute, second);
3412 if (parts.count() == 5)
3413 return QDateTime(date, time, Qt::LocalTime);
3415 QString tz = parts.at(5);
3416 if (!tz.startsWith(QLatin1String("GMT"), Qt::CaseInsensitive))
3418 QDateTime dt(date, time, Qt::UTC);
3419 if (tz.length() > 3) {
3421 QChar sign = tz.at(3);
3422 if ((sign != QLatin1Char('+'))
3423 && (sign != QLatin1Char('-'))) {
3426 int tzhour = tz.mid(4, 2).toInt(&ok);
3429 int tzminute = tz.mid(6).toInt(&ok);
3432 tzoffset = (tzhour*60 + tzminute) * 60;
3433 if (sign == QLatin1Char('-'))
3434 tzoffset = -tzoffset;
3435 dt.setUtcOffset(tzoffset);
3437 return dt.toLocalTime();
3439 #endif //QT_NO_TEXTDATE
3446 \fn QDateTime::fromString(const QString &string, const QString &format)
3448 Returns the QDateTime represented by the \a string, using the \a
3449 format given, or an invalid datetime if the string cannot be parsed.
3451 These expressions may be used for the date part of the format string:
3454 \header \i Expression \i Output
3455 \row \i d \i the day as number without a leading zero (1 to 31)
3456 \row \i dd \i the day as number with a leading zero (01 to 31)
3458 \i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
3459 Uses QDate::shortDayName().
3461 \i the long localized day name (e.g. 'Monday' to 'Sunday').
3462 Uses QDate::longDayName().
3463 \row \i M \i the month as number without a leading zero (1-12)
3464 \row \i MM \i the month as number with a leading zero (01-12)
3466 \i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
3467 Uses QDate::shortMonthName().
3469 \i the long localized month name (e.g. 'January' to 'December').
3470 Uses QDate::longMonthName().
3471 \row \i yy \i the year as two digit number (00-99)
3472 \row \i yyyy \i the year as four digit number
3475 \note Unlike the other version of this function, day and month names must
3476 be given in the user's local language. It is only possible to use the English
3477 names if the user's language is English.
3479 These expressions may be used for the time part of the format string:
3482 \header \i Expression \i Output
3484 \i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
3486 \i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
3488 \i the hour without a leading zero (0 to 23, even with AM/PM display)
3490 \i the hour with a leading zero (00 to 23, even with AM/PM display)
3491 \row \i m \i the minute without a leading zero (0 to 59)
3492 \row \i mm \i the minute with a leading zero (00 to 59)
3493 \row \i s \i the second without a leading zero (0 to 59)
3494 \row \i ss \i the second with a leading zero (00 to 59)
3495 \row \i z \i the milliseconds without leading zeroes (0 to 999)
3496 \row \i zzz \i the milliseconds with leading zeroes (000 to 999)
3498 \i interpret as an AM/PM time. \e AP must be either "AM" or "PM".
3500 \i Interpret as an AM/PM time. \e ap must be either "am" or "pm".
3503 All other input characters will be treated as text. Any sequence
3504 of characters that are enclosed in singlequotes will also be
3505 treated as text and not be used as an expression.
3507 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 12
3509 If the format is not satisfied an invalid QDateTime is returned.
3510 The expressions that don't have leading zeroes (d, M, h, m, s, z) will be
3511 greedy. This means that they will use two digits even if this will
3512 put them outside the range and/or leave too few digits for other
3515 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 13
3517 This could have meant 1 January 00:30.00 but the M will grab
3520 For any field that is not represented in the format the following
3524 \header \i Field \i Default value
3525 \row \i Year \i 1900
3526 \row \i Month \i 1 (January)
3535 \snippet doc/src/snippets/code/src_corelib_tools_qdatetime.cpp 14
3537 \sa QDate::fromString() QTime::fromString() QDate::toString()
3538 QDateTime::toString() QTime::toString()
3541 QDateTime QDateTime::fromString(const QString &string, const QString &format)
3543 #ifndef QT_BOOTSTRAPPED
3547 QDateTimeParser dt(QVariant::DateTime, QDateTimeParser::FromString);
3548 if (dt.parseFormat(format) && dt.fromString(string, &date, &time))
3549 return QDateTime(date, time);
3554 return QDateTime(QDate(), QTime(-1, -1, -1));
3557 #endif // QT_NO_DATESTRING
3559 \fn QDateTime QDateTime::toLocalTime() const
3561 Returns a datetime containing the date and time information in
3562 this datetime, but specified using the Qt::LocalTime definition.
3568 \fn QDateTime QDateTime::toUTC() const
3570 Returns a datetime containing the date and time information in
3571 this datetime, but specified using the Qt::UTC definition.
3578 void QDateTime::detach()
3583 /*****************************************************************************
3584 Date/time stream functions
3585 *****************************************************************************/
3587 #ifndef QT_NO_DATASTREAM
3591 Writes the \a date to stream \a out.
3593 \sa {Serializing Qt Data Types}
3596 QDataStream &operator<<(QDataStream &out, const QDate &date)
3598 return out << (quint32)(date.jd);
3604 Reads a date from stream \a in into the \a date.
3606 \sa {Serializing Qt Data Types}
3609 QDataStream &operator>>(QDataStream &in, QDate &date)
3620 Writes \a time to stream \a out.
3622 \sa {Serializing Qt Data Types}
3625 QDataStream &operator<<(QDataStream &out, const QTime &time)
3627 return out << quint32(time.mds);
3633 Reads a time from stream \a in into the given \a time.
3635 \sa {Serializing Qt Data Types}
3638 QDataStream &operator>>(QDataStream &in, QTime &time)
3649 Writes \a dateTime to the \a out stream.
3651 \sa {Serializing Qt Data Types}
3653 QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
3655 out << dateTime.d->date << dateTime.d->time;
3656 if (out.version() >= 7)
3657 out << (qint8)dateTime.d->spec;
3664 Reads a datetime from the stream \a in into \a dateTime.
3666 \sa {Serializing Qt Data Types}
3669 QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
3673 qint8 ts = (qint8)QDateTimePrivate::LocalUnknown;
3674 in >> dateTime.d->date >> dateTime.d->time;