1
/****************************************************************************
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
5
** This file is part of the core module of the Qt Toolkit.
7
** This file may be distributed under the terms of the Q Public License
8
** as defined by Trolltech AS of Norway and appearing in the file
9
** LICENSE.QPL included in the packaging of this file.
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 as published by the Free Software
13
** Foundation and appearing in the file LICENSE.GPL included in the
14
** packaging of this file.
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
17
** information about Qt Commercial License Agreements.
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
21
** Contact info@trolltech.com if any conditions of this licensing are
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27
****************************************************************************/
29
#include "qplatformdefs.h"
30
#include "private/qdatetime_p.h"
32
#include "qdatastream.h"
33
#include "qdatetime.h"
35
#ifndef QT_NO_DEBUG_STREAM
38
#if defined(Q_OS_WIN32)
47
#include <private/qcore_mac_p.h>
48
extern QString qt_mac_from_pascal_string(const Str255); // qglobal.cpp
52
FIRST_DAY = 2361222, // Julian day for 1752-09-14
55
MSECS_PER_DAY = 86400000,
57
MSECS_PER_HOUR = 3600000,
62
static const short monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
64
static const char * const qt_shortMonthNames[] = {
65
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
66
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
67
static const char * const qt_longMonthNames[] = {
68
"January", "February", "Mars", "April", "May", "June",
69
"July", "August", "September", "October", "November", "December" };
70
static const char * const qt_shortDayNames[] = {
71
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
72
static const char * const qt_longDayNames[] = {
73
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
75
static QString fmtDateTime(const QString& f, const QTime* dt = 0, const QDate* dd = 0);
77
/*****************************************************************************
78
QDate member functions
79
*****************************************************************************/
84
\brief The QDate class provides date functions.
89
A QDate object contains a calendar date, i.e. year, month, and day
90
numbers, in the modern Western (Gregorian) calendar. It can read
91
the current date from the system clock. It provides functions for
92
comparing dates, and for manipulating dates. For example, it is
93
possible to add and subtract days, months, and years to dates.
95
A QDate object is typically created either by giving the year,
96
month, and day numbers explicitly, or by using the static function
97
currentDate() that creates a QDate object containing the system
98
clock's date. An explicit date can also be set using setYMD(). The
99
fromString() function returns a QDate given a string and a date
100
format which is used to interpret the date within the string.
102
The year(), month(), and day() functions provide access to the
103
year, month, and day numbers. Also, dayOfWeek() and dayOfYear()
104
functions are provided. The same information is provided in
105
textual format by the toString(), shortDayName(), longDayName(),
106
shortMonthName(), and longMonthName() functions.
108
QDate provides a full set of operators to compare two QDate
109
objects where smaller means earlier, and larger means later.
111
You can increment (or decrement) a date by a given number of days
112
using addDays(). Similarly you can use addMonths() and addYears().
113
The daysTo() function returns the number of days between two
116
The daysInMonth() and daysInYear() functions return how many days
117
there are in this date's month and year, respectively. The
118
isLeapYear() function indicates whether this date is in a leap year.
120
Note that QDate should not be used for date calculations for dates
121
prior to the introduction of the Gregorian calendar. This calendar
122
was adopted by England from the 14 September 1752 (hence this is
123
the earliest valid QDate), and subsequently by most other Western
126
The latest valid year within this scheme is the year 8000.
128
\sa QTime QDateTime QDateEdit QDateTimeEdit
134
Constructs a null date. Null dates are invalid.
136
\sa isNull(), isValid()
141
Constructs a date with year \a y, month \a m and day \a d.
143
\a y must be in the range 1752 to 8000, \a m must be in the range
144
1 to 12, and \a d must be in the range 1 to 31.
146
\warning If \a y is in the range 0 to 99, it is interpreted as
147
a year in the range 1900 to 1999.
152
QDate::QDate(int y, int m, int d)
160
\fn bool QDate::isNull() const
162
Returns true if the date is null; otherwise returns false. A null
170
Returns true if this date is valid; otherwise returns false.
175
bool QDate::isValid() const
177
return jd >= FIRST_DAY;
182
Returns the year (1752 to 8000) of this date.
187
int QDate::year() const
190
julianToGregorian(jd, y, m, d);
195
Returns the number corresponding to the month of this date, using
196
the following convention:
216
int QDate::month() const
219
julianToGregorian(jd, y, m, d);
224
Returns the day of the month (1 to 31) of this date.
226
\sa year(), month(), dayOfWeek()
229
int QDate::day() const
232
julianToGregorian(jd, y, m, d);
237
Returns the weekday for this date.
239
\sa day(), dayOfYear(), Qt::DayOfWeek
242
int QDate::dayOfWeek() const
248
Returns the day of the year (1 to 365) for this date.
250
\sa day(), dayOfWeek()
253
int QDate::dayOfYear() const
255
return jd - gregorianToJulian(year(), 1, 1) + 1;
259
Returns the number of days in the month (28 to 31) for this date.
261
\sa day(), daysInYear()
264
int QDate::daysInMonth() const
267
julianToGregorian(jd, y, m, d);
268
if (m == 2 && isLeapYear(y))
275
Returns the number of days in the year (365 or 366) for this date.
277
\sa day(), daysInMonth()
280
int QDate::daysInYear() const
283
julianToGregorian(jd, y, m, d);
284
return isLeapYear(y) ? 366 : 365;
288
Returns the week number (1 to 53), and stores the year in
289
*\a{yearNumber} unless \a yearNumber is null (the default).
291
Returns 0 if the date is invalid.
293
In accordance with ISO 8601, weeks start on Qt::Monday and the first
294
Qt::Thursday of a year is always in week 1 of that year. Most years
295
have 52 weeks, but some have 53.
297
*\a{yearNumber} is not always the same as year(). For example, 1
298
January 2000 has week number 52 in the year 1999, and 31 December
299
2002 has week number 1 in the year 2003.
304
Copyright (c) 1989 The Regents of the University of California.
307
Redistribution and use in source and binary forms are permitted
308
provided that the above copyright notice and this paragraph are
309
duplicated in all such forms and that any documentation,
310
advertising materials, and other materials related to such
311
distribution and use acknowledge that the software was developed
312
by the University of California, Berkeley. The name of the
313
University may not be used to endorse or promote products derived
314
from this software without specific prior written permission.
315
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
316
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
317
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
323
int QDate::weekNumber(int *yearNumber) const
328
int year = QDate::year();
329
int yday = dayOfYear() - 1;
330
int wday = dayOfWeek();
340
len = isLeapYear(year) ? 366 : 365;
342
** What yday (-3 ... 3) does
343
** the ISO year begin on?
345
bot = ((yday + 11 - wday) % 7) - 3;
347
** What yday does the NEXT
348
** ISO year begin on?
350
top = bot - (len % 7);
360
w = 1 + ((yday - bot) / 7);
364
yday += isLeapYear(year) ? 366 : 365;
371
#ifndef QT_NO_TEXTDATE
373
Returns the name of the \a month using the following
391
The month names will be localized according to the system's locale
394
\sa toString(), longMonthName(), shortDayName(), longDayName()
397
QString QDate::shortMonthName(int month)
399
if (month < 1 || month > 12) {
400
qWarning("QDate::shortMonthName: Parameter out ouf range");
406
memset(&tt, 0, sizeof(tm));
407
tt.tm_mon = month - 1;
408
const QByteArray lctime(setlocale(LC_TIME, ""));
409
if (strftime(buffer, sizeof(buffer), "%b", &tt)) {
410
setlocale(LC_TIME, lctime.data());
411
return QString::fromLocal8Bit(buffer);
413
setlocale(LC_TIME, lctime.data());
416
memset(&st, 0, sizeof(SYSTEMTIME));
420
const wchar_t mmm_t[] = L"MMM"; // workaround for Borland
423
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, mmm_t, buf, 255))
424
return QString::fromUtf16((ushort*)buf);
427
if (GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, "MMM", (char*)&buf, 255))
428
return QString::fromLocal8Bit(buf);
435
Returns the long name of the \a month using the following
453
The month names will be localized according to the system's locale
456
\sa toString(), shortMonthName(), shortDayName(), longDayName()
459
QString QDate::longMonthName(int month)
461
if (month < 1 || month > 12) {
462
qWarning("QDate::longMonthName: Parameter out ouf range");
468
memset(&tt, 0, sizeof(tm));
469
tt.tm_mon = month - 1;
470
const QByteArray lctime(setlocale(LC_TIME, ""));
471
if (strftime(buffer, sizeof(buffer), "%B", &tt)) {
472
setlocale(LC_TIME, lctime.data());
473
return QString::fromLocal8Bit(buffer);
475
setlocale(LC_TIME, lctime.data());
478
memset(&st, 0, sizeof(SYSTEMTIME));
482
const wchar_t mmmm_t[] = L"MMMM"; // workaround for Borland
485
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, mmmm_t, buf, 255))
486
return QString::fromUtf16((ushort*)buf);
489
if (GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, "MMMM", (char*)&buf, 255))
490
return QString::fromLocal8Bit(buf);
497
Returns the name of the \a weekday using the following
510
The day names will be localized according to the system's locale
513
\sa toString(), shortMonthName(), longMonthName(), longDayName()
516
QString QDate::shortDayName(int weekday)
518
if (weekday < 1 || weekday > 7) {
519
qWarning("QDate::shortDayName: Parameter out of range");
525
memset(&tt, 0, sizeof(tm));
526
tt.tm_wday = (weekday == 7) ? 0 : weekday;
527
const QByteArray lctime(setlocale(LC_TIME, ""));
528
if (strftime(buffer, sizeof(buffer), "%a", &tt)) {
529
setlocale(LC_TIME, lctime.data());
530
return QString::fromLocal8Bit(buffer);
532
setlocale(LC_TIME, lctime.data());
536
memset(&st, 0, sizeof(SYSTEMTIME));
539
st.wDayOfWeek = (weekday == 7) ? 0 : weekday;
540
st.wDay = 21 + st.wDayOfWeek;
541
const wchar_t ddd_t[] = L"ddd"; // workaround for Borland
544
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, ddd_t, buf, 255))
545
return QString::fromUtf16((ushort*)buf);
548
if (GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, "ddd", (char*)&buf, 255))
549
return QString::fromLocal8Bit(buf);
556
Returns the long name of the \a weekday using the following
569
The day names will be localized according to the system's locale
572
\sa toString(), shortDayName(), shortMonthName(), longMonthName()
575
QString QDate::longDayName(int weekday)
577
if (weekday < 1 || weekday > 7) {
578
qWarning("QDate::longDayName: Parameter out of range");
584
memset(&tt, 0, sizeof(tm));
585
tt.tm_wday = (weekday == 7) ? 0 : weekday;
586
const QByteArray lctime(setlocale(LC_TIME, ""));
587
if (strftime(buffer, sizeof(buffer), "%A", &tt)) {
588
setlocale(LC_TIME, lctime.data());
589
return QString::fromLocal8Bit(buffer);
591
setlocale(LC_TIME, lctime.data());
594
memset(&st, 0, sizeof(SYSTEMTIME));
597
st.wDayOfWeek = (weekday == 7) ? 0 : weekday;
598
st.wDay = 21 + st.wDayOfWeek;
599
const wchar_t dddd_t[] = L"dddd"; // workaround for Borland
602
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, dddd_t, buf, 255))
603
return QString::fromUtf16((ushort*)buf);
606
if (GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, "dddd", (char*)&buf, 255))
607
return QString::fromLocal8Bit(buf);
612
#endif //QT_NO_TEXTDATE
614
#ifndef QT_NO_DATESTRING
617
\fn QString QDate::toString(Qt::DateFormat format) const
621
Returns the date as a string. The \a format parameter determines
622
the format of the string.
624
If the \a format is \c Qt::TextDate, the string is formatted in
625
the default way. QDate::shortDayName() and QDate::shortMonthName()
626
are used to generate the string, so the day and month names will
627
be localized names. An example of this formatting is
630
If the \a format is \c Qt::ISODate, the string format corresponds
631
to the ISO 8601 extended specification for representations of
632
dates and times, taking the form YYYY-MM-DD, where YYYY is the
633
year, MM is the month of the year (between 01 and 12), and DD is
634
the day of the month between 01 and 31.
636
If the \a format is \c Qt::LocalDate, the string format depends
637
on the locale settings of the system.
639
If the datetime is invalid, an empty string will be returned.
641
\sa shortDayName(), shortMonthName()
643
QString QDate::toString(Qt::DateFormat f) const
648
julianToGregorian(jd, y, m, d);
654
memset(&st, 0, sizeof(SYSTEMTIME));
660
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, 0, buf, 255))
661
return QString::fromUtf16((ushort*)buf);
664
if (GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, 0, (char*)&buf, 255))
665
return QString::fromLocal8Bit(buf);
667
#elif defined(Q_WS_MAC)
668
CFGregorianDate macGDate;
669
macGDate.year = year();
670
macGDate.month = month();
671
macGDate.day = day();
674
macGDate.second = 0.0;
675
QCFType<CFDateRef> myDate = CFDateCreate(0, CFGregorianDateGetAbsoluteTime(macGDate, 0));
676
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3)
677
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3) {
678
QCFType<CFLocaleRef> mylocale = CFLocaleCopyCurrent();
679
QCFType<CFDateFormatterRef> myFormatter = CFDateFormatterCreate(kCFAllocatorDefault,
680
mylocale, kCFDateFormatterLongStyle,
681
kCFDateFormatterNoStyle);
682
return QCFString(CFDateFormatterCreateStringWithDate(0, myFormatter, myDate));
686
Handle intlHandle = GetIntlResource(1);
687
LongDateTime oldDate;
688
UCConvertCFAbsoluteTimeToLongDateTime(CFGregorianDateGetAbsoluteTime(macGDate, 0),
691
LongDateString(&oldDate, longDate, pString, intlHandle);
692
return qt_mac_from_pascal_string(pString);
696
memset(&tt, 0, sizeof(tm));
699
tt.tm_mon = month() - 1;
700
tt.tm_year = year() - 1900;
702
const char *avoidEgcsWarning = "%x";
703
const QByteArray lctime(setlocale(LC_TIME, ""));
704
if (strftime(buf, sizeof(buf), avoidEgcsWarning, &tt)) {
705
setlocale(LC_TIME, lctime.data());
706
return QString::fromLocal8Bit(buf);
708
setlocale(LC_TIME, lctime.data());
713
#ifndef QT_NO_TEXTDATE
716
return QString::fromLatin1("%0 %1 %2 %3")
717
.arg(shortDayName(dayOfWeek()))
718
.arg(shortMonthName(m))
725
QString month(QString::number(m).rightJustified(2, QLatin1Char('0')));
726
QString day(QString::number(d).rightJustified(2, QLatin1Char('0')));
727
return QString::number(y) + QLatin1Char('-') + month + QLatin1Char('-') + day;
733
Returns the date as a string. The \a format parameter determines
734
the format of the result string.
736
These expressions may be used:
739
\header \i Expression \i Output
740
\row \i d \i the day as number without a leading zero (1 to31)
741
\row \i dd \i the day as number with a leading zero (01 to 31)
743
\i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
744
Uses QDate::shortDayName().
746
\i the long localized day name (e.g. 'Qt::Monday' to 'Qt::Sunday').
747
Uses QDate::longDayName().
748
\row \i M \i the month as number without a leading zero (1-12)
749
\row \i MM \i the month as number with a leading zero (01-12)
751
\i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
752
Uses QDate::shortMonthName().
754
\i the long localized month name (e.g. 'January' to 'December').
755
Uses QDate::longMonthName().
756
\row \i yy \i the year as two digit number (00 to 99)
757
\row \i yyyy \i the year as four digit number (1752 to 8000)
760
All other input characters will be ignored. Any sequence of characters that
761
are enclosed in singlequotes will be treated as text and not be used as an
764
Example format strings (assuming that the QDate is the 20 July
768
\header \o Format \o Result
769
\row \o dd.MM.yyyy \o 20.07.1969
770
\row \o ddd MMMM d yy \o Sun July 20 69
771
\row \o 'The day is' dddd \o The day is Sunday
774
If the datetime is invalid, an empty string will be returned.
776
\sa QDateTime::toString() QTime::toString()
779
QString QDate::toString(const QString& format) const
781
return fmtDateTime(format, 0, this);
783
#endif //QT_NO_DATESTRING
786
Sets the date's year \a y, month \a m, and day \a d.
788
\a y must be in the range 1752 to 8000, \a m must be in the range
789
1 to 12, and \a d must be in the range 1 to 31.
791
\warning If \a y is in the range 0 to 99, it is interpreted as
794
Returns true if the date is valid; otherwise returns false.
797
bool QDate::setYMD(int y, int m, int d)
799
if (year() == y && month() == m && day() == d)
801
if (!isValid(y,m,d)) {
805
jd = gregorianToJulian(y, m, d);
810
Returns a QDate object containing a date \a ndays later than the
811
date of this object (or earlier if \a ndays is negative).
813
\sa addMonths() addYears() daysTo()
816
QDate QDate::addDays(int ndays) const
824
Returns a QDate object containing a date \a nmonths later than the
825
date of this object (or earlier if \a nmonths is negative).
827
\sa addDays() addYears()
830
QDate QDate::addMonths(int nmonths) const
833
julianToGregorian(jd, y, m, d);
835
while (nmonths != 0) {
836
if (nmonths < 0 && nmonths + 12 <= 0) {
839
} else if (nmonths < 0) {
846
} else if (nmonths - 12 >= 0) {
849
} else if (m == 12) {
863
if (d > tmp.daysInMonth())
864
d = tmp.daysInMonth();
866
return QDate(y, m, d);
870
Returns a QDate object containing a date \a nyears later than the
871
date of this object (or earlier if \a nyears is negative).
873
\sa addDays(), addMonths()
876
QDate QDate::addYears(int nyears) const
879
julianToGregorian(jd, y, m, d);
884
if(d > tmp.daysInMonth())
885
d = tmp.daysInMonth();
894
Returns the number of days from this date to \a d (which is
895
negative if \a d is earlier than this date).
899
QDate d1(1995, 5, 17); // May 17, 1995
900
QDate d2(1995, 5, 20); // May 20, 1995
901
d1.daysTo(d2); // returns 3
902
d2.daysTo(d1); // returns -3
908
int QDate::daysTo(const QDate &d) const
915
\fn bool QDate::operator==(const QDate &d) const
917
Returns true if this date is equal to \a d; otherwise returns
922
\fn bool QDate::operator!=(const QDate &d) const
924
Returns true if this date is different from \a d; otherwise
929
\fn bool QDate::operator<(const QDate &d) const
931
Returns true if this date is earlier than \a d; otherwise returns
936
\fn bool QDate::operator<=(const QDate &d) const
938
Returns true if this date is earlier than or equal to \a d;
939
otherwise returns false.
943
\fn bool QDate::operator>(const QDate &d) const
945
Returns true if this date is later than \a d; otherwise returns
950
\fn bool QDate::operator>=(const QDate &d) const
952
Returns true if this date is later than or equal to \a d;
953
otherwise returns false.
958
Returns the current date, as reported by the system clock.
960
\sa QTime::currentTime(), QDateTime::currentDateTime()
963
QDate QDate::currentDate()
966
#if defined(Q_OS_WIN32)
968
memset(&st, 0, sizeof(SYSTEMTIME));
970
d.jd = QDate::gregorianToJulian(st.wYear, st.wMonth, st.wDay);
972
// posix compliant system
977
#if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
978
// use the reentrant version of localtime() where available
980
t = localtime_r(<ime, &res);
982
t = localtime(<ime);
983
#endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
985
d.jd = gregorianToJulian(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
990
#ifndef QT_NO_DATESTRING
992
\fn QDate QDate::fromString(const QString &string, Qt::DateFormat format)
994
Returns the QDate represented by the \a string, using the
995
\a format given, or an invalid date if the string cannot be
998
Note for \c Qt::TextDate: It is recommended that you use the
999
English short month names (e.g. "Jan"). Although localized month
1000
names can also be used, they depend on the user's locale settings.
1002
\warning \c Qt::LocalDate cannot be used here.
1004
QDate QDate::fromString(const QString& s, Qt::DateFormat f)
1006
if ((s.isEmpty()) || (f == Qt::LocalDate)) {
1014
int year(s.mid(0, 4).toInt());
1015
int month(s.mid(5, 2).toInt());
1016
int day(s.mid(8, 2).toInt());
1017
if (year && month && day)
1018
return QDate(year, month, day);
1022
#ifndef QT_NO_TEXTDATE
1026
This will fail gracefully if the input string doesn't
1029
int monthPos = s.indexOf(QLatin1Char(' ')) + 1;
1030
int dayPos = s.indexOf(QLatin1Char(' '), monthPos) + 1;
1032
QString monthName(s.mid(monthPos, dayPos - monthPos - 1));
1035
// try English names first
1036
for (int i = 0; i < 12; i++) {
1037
if (monthName == QLatin1String(qt_shortMonthNames[i])) {
1043
// try the localized names
1045
for (int i = 0; i < 12; i++) {
1046
if (monthName == shortMonthName(i + 1)) {
1052
if (month < 1 || month > 12) {
1057
int day = s.mid(dayPos, 2).trimmed().toInt();
1058
int year = s.right(4).toInt();
1059
return QDate(year, month, day);
1067
#endif //QT_NO_DATESTRING
1070
\fn QDate::fromString(const QString &string, const QString &format)
1072
Returns the QDate represented by the \a string, using the \a
1073
format given, or an invalid date if the string cannot be parsed.
1075
These expressions may be used for the format:
1078
\header \i Expression \i Output
1079
\row \i d \i The day as a number without a leading zero (1 to 31)
1080
\row \i dd \i The day as a number with a leading zero (01 to 31)
1082
\i The abbreviated localized day name (e.g. 'Mon' to 'Sun').
1083
Uses QDate::shortDayName().
1085
\i The long localized day name (e.g. 'Monday' to 'Sunday').
1086
Uses QDate::longDayName().
1087
\row \i M \i The month as a number without a leading zero (1 to 12)
1088
\row \i MM \i The month as a number with a leading zero (01 to 12)
1090
\i The abbreviated localized month name (e.g. 'Jan' to 'Dec').
1091
Uses QDate::shortMonthName().
1093
\i The long localized month name (e.g. 'January' to 'December').
1094
Uses QDate::longMonthName().
1095
\row \i yy \i The year as two digit number (00 to 99)
1096
\row \i yyyy \i The year as four digit number (1752 to 8000)
1099
All other input characters will be treated as text. Any sequence
1100
of characters that are enclosed in single quotes will also be
1101
treated as text and will not be used as an expression. For example:
1104
QDate date = QDate::fromString("1MM12car2003", "d'MM'MMcaryyyy");
1105
// date is 1 December 2003
1108
If the format is not satisfied, an invalid QDate is returned. The
1109
expressions that don't expect leading zeroes (d, M) will be
1110
greedy. This means that they will use two digits even if this
1111
will put them outside the accepted range of values and leaves too
1112
few digits for other sections. For example, the following format
1113
string could have meant January 30 but the M will grab two
1114
digits, resulting in an invalid date:
1117
QDate date = QDate::fromString("130", "Md"); // invalid
1120
For any field that is not represented in the format the following
1124
\header \i Field \i Default value
1125
\row \i Year \i The current year
1130
The following examples demonstrate the default values:
1133
QDate::fromString("1.30", "M.d"); // January 30 in the current year
1134
QDate::fromString("20000110", "yyyyMMdd"); // January 10, 2000
1135
QDate::fromString("20000110", "yyyyMd"); // January 10, 2000
1138
\sa QDateTime::fromString(), QTime::fromString(), QDate::toString(),
1139
QDateTime::toString(), QTime::toString()
1142
QDate QDate::fromString(const QString &string, const QString &format)
1144
QDateTimeParser dt(format, QVariant::Date);
1146
return dt.fromString(string, &date, 0) ? date : QDate();
1152
Returns true if the specified date (year \a y, month \a m, and day
1153
\a d) is valid; otherwise returns false.
1157
QDate::isValid(2002, 5, 17); // true
1158
QDate::isValid(2002, 2, 30); // false (Feb 30 does not exist)
1159
QDate::isValid(2004, 2, 29); // true (2004 is a leap year)
1160
QDate::isValid(1202, 6, 6); // false (1202 is pre-Gregorian)
1163
\warning A \a y value in the range 00 to 99 is interpreted as
1166
\sa isNull(), setYMD()
1169
bool QDate::isValid(int y, int m, int d)
1171
if (y >= 0 && y <= 99)
1173
else if (y < FIRST_YEAR || (y == FIRST_YEAR && (m < 9 || (m == 9 && d < 14))))
1175
return (d > 0 && m > 0 && m <= 12) &&
1176
(d <= monthDays[m] || (d == 29 && m == 2 && isLeapYear(y)));
1180
\fn bool QDate::isLeapYear(int year)
1182
Returns true if the specified \a year is a leap year; otherwise
1186
bool QDate::isLeapYear(int y)
1188
return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
1193
Converts a Gregorian date to a Julian day.
1194
This algorithm is taken from Communications of the ACM, Vol 6, No 8.
1195
\sa julianToGregorian()
1198
uint QDate::gregorianToJulian(int y, int m, int d)
1209
c = y; // NOTE: Sym C++ 6.0 bug
1212
return 1721119 + d + (146097*c)/4 + (1461*ya)/4 + (153*m+2)/5;
1217
Converts a Julian day to a Gregorian date.
1218
This algorithm is taken from Communications of the ACM, Vol 6, No 8.
1219
\sa gregorianToJulian()
1222
void QDate::julianToGregorian(uint jd, int &y, int &m, int &d)
1225
uint j = jd - 1721119;
1226
y = (j*4 - 1)/146097;
1227
j = j*4 - 146097*y - 1;
1229
j = (x*4 + 3) / 1461;
1231
x = (x*4) + 3 - 1461*j;
1234
x = 5*x - 3 - 153*m;
1244
/*! \fn static QDate QDate::fromJulianDay(int jd)
1246
Converts the Julian day \a jd to a QDate.
1251
/*! \fn int QDate::toJulianDay() const
1253
Converts the date to a Julian day.
1258
/*****************************************************************************
1259
QTime member functions
1260
*****************************************************************************/
1266
\brief The QTime class provides clock time functions.
1271
A QTime object contains a clock time, i.e. the number of hours,
1272
minutes, seconds, and milliseconds since midnight. It can read the
1273
current time from the system clock and measure a span of elapsed
1274
time. It provides functions for comparing times and for
1275
manipulating a time by adding a number of (milli)seconds.
1277
QTime uses the 24-hour clock format; it has no concept of AM/PM.
1278
It operates in local time; it knows nothing about time zones or
1279
daylight savings time.
1281
A QTime object is typically created either by giving the number of
1282
hours, minutes, seconds, and milliseconds explicitly, or by using
1283
the static function currentTime(), which creates a QTime object
1284
that contains the system's clock time. Note that the accuracy
1285
depends on the accuracy of the underlying operating system; not
1286
all systems provide 1-millisecond accuracy.
1288
The hour(), minute(), second(), and msec() functions provide
1289
access to the number of hours, minutes, seconds, and milliseconds
1290
of the time. The same information is provided in textual format by
1291
the toString() function.
1293
QTime provides a full set of operators to compare two QTime
1294
objects. One time is considered smaller than another if it is
1295
earlier than the other.
1297
The time a given number of seconds or milliseconds later than a
1298
given time can be found using the addSecs() or addMSecs()
1299
functions. Correspondingly, the number of (milli)seconds between
1300
two times can be found using the secsTo() or msecsTo() functions.
1302
QTime can be used to measure a span of elapsed time using the
1303
start(), restart(), and elapsed() functions.
1305
\sa QDate, QDateTime
1311
Constructs the time 0 hours, minutes, seconds and milliseconds,
1312
i.e. 00:00:00.000 (midnight). This is a valid time.
1318
Constructs a time with hour \a h, minute \a m, seconds \a s and
1321
\a h must be in the range 0 to 23, \a m and \a s must be in the
1322
range 0 to 59, and \a ms must be in the range 0 to 999.
1327
QTime::QTime(int h, int m, int s, int ms)
1329
setHMS(h, m, s, ms);
1334
\fn bool QTime::isNull() const
1336
Returns true if the time is equal to 00:00:00.000; otherwise
1337
returns false. A null time is valid.
1343
Returns true if the time is valid; otherwise returns false. For example,
1344
the time 23:30:55.746 is valid, but 24:12:30 is invalid.
1349
bool QTime::isValid() const
1351
return ds < MSECS_PER_DAY;
1356
Returns the hour part (0 to 23) of the time.
1358
\sa minute(), second(), msec()
1361
int QTime::hour() const
1363
return ds / MSECS_PER_HOUR;
1367
Returns the minute part (0 to 59) of the time.
1369
\sa hour(), second(), msec()
1372
int QTime::minute() const
1374
return (ds % MSECS_PER_HOUR)/MSECS_PER_MIN;
1378
Returns the second part (0 to 59) of the time.
1380
\sa hour(), minute(), msec()
1383
int QTime::second() const
1385
return (ds / 1000)%SECS_PER_MIN;
1389
Returns the millisecond part (0 to 999) of the time.
1391
\sa hour(), minute(), second()
1394
int QTime::msec() const
1399
#ifndef QT_NO_DATESTRING
1403
Returns the time as a string. Milliseconds are not included. The
1404
\a f parameter determines the format of the string.
1406
If \a f is \c Qt::TextDate, the string format is HH:MM:SS; e.g. 1
1407
second before midnight would be "23:59:59".
1409
If \a f is \c Qt::ISODate, the string format corresponds to the
1410
ISO 8601 extended specification for representations of dates,
1411
which is also HH:MM:SS.
1413
If \a f is Qt::LocalDate, the string format depends on the locale
1414
settings of the system.
1416
If the datetime is invalid, an empty string will be returned.
1419
QString QTime::toString(Qt::DateFormat f) const
1429
memset(&st, 0, sizeof(SYSTEMTIME));
1431
st.wMinute = minute();
1432
st.wSecond = second();
1433
st.wMilliseconds = 0;
1436
if (GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, 0, buf, 255))
1437
return QString::fromUtf16((ushort*)buf);
1440
if (GetTimeFormatA(LOCALE_USER_DEFAULT, 0, &st, 0, (char*)&buf, 255))
1441
return QString::fromLocal8Bit(buf);
1443
#elif defined (Q_WS_MAC)
1444
CFGregorianDate macGDate;
1445
// Assume this is local time and the current date
1446
QDate dt = QDate::currentDate();
1447
macGDate.year = dt.year();
1448
macGDate.month = dt.month();
1449
macGDate.day = dt.day();
1450
macGDate.hour = hour();
1451
macGDate.minute = minute();
1452
macGDate.second = second();
1453
QCFType<CFTimeZoneRef> myTz = CFTimeZoneCopyDefault();
1454
QCFType<CFDateRef> myDate = CFDateCreate(0,
1455
CFGregorianDateGetAbsoluteTime(macGDate,
1457
# if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3)
1458
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3) {
1460
QCFType<CFLocaleRef> mylocale = CFLocaleCopyCurrent();
1461
QCFType<CFDateFormatterRef> myFormatter = CFDateFormatterCreate(kCFAllocatorDefault,
1463
kCFDateFormatterNoStyle,
1464
kCFDateFormatterMediumStyle);
1465
return QCFString(CFDateFormatterCreateStringWithDate(0, myFormatter, myDate));
1469
// For Jaguar, must use the older non-recommended Stuff
1470
Handle intlHandle = GetIntlResource(0);
1471
LongDateTime oldDate;
1472
UCConvertCFAbsoluteTimeToLongDateTime(CFGregorianDateGetAbsoluteTime(macGDate, myTz),
1475
LongTimeString(&oldDate, true, pString, intlHandle);
1476
return qt_mac_from_pascal_string(pString);
1480
memset(&tt, 0, sizeof(tm));
1482
tt.tm_sec = second();
1483
tt.tm_min = minute();
1484
tt.tm_hour = hour();
1486
const QByteArray lctime(setlocale(LC_TIME, ""));
1487
if (strftime(buf, sizeof(buf), "%X", &tt)) {
1488
setlocale(LC_TIME, lctime.data());
1489
return QString::fromLocal8Bit(buf);
1491
setlocale(LC_TIME, lctime.data());
1498
return QString::fromLatin1("%1:%2:%3")
1499
.arg(hour(), 2, 10, QLatin1Char('0'))
1500
.arg(minute(), 2, 10, QLatin1Char('0'))
1501
.arg(second(), 2, 10, QLatin1Char('0'));
1506
Returns the time as a string. The \a format parameter determines
1507
the format of the result string.
1509
These expressions may be used:
1512
\header \i Expression \i Output
1514
\i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
1516
\i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
1517
\row \i m \i the minute without a leading zero (0 to 59)
1518
\row \i mm \i the minute with a leading zero (00 to 59)
1519
\row \i s \i the second whithout a leading zero (0 to 59)
1520
\row \i ss \i the second whith a leading zero (00 to 59)
1521
\row \i z \i the milliseconds without leading zeroes (0 to 999)
1522
\row \i zzz \i the milliseconds with leading zeroes (000 to 999)
1524
\i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
1526
\i use am/pm display. \e ap will be replaced by either "am" or "pm".
1529
All other input characters will be ignored. Any sequence of characters that
1530
are enclosed in singlequotes will be treated as text and not be used as an
1533
Example format strings (assuming that the QTime is 14:13:09.042)
1536
\header \i Format \i Result
1537
\row \i hh:mm:ss.zzz \i 14:13:09.042
1538
\row \i h:m:s ap \i 2:13:9 pm
1541
If the datetime is invalid, an empty string will be returned.
1543
\sa QDate::toString() QDateTime::toString()
1545
QString QTime::toString(const QString& format) const
1547
return fmtDateTime(format, this, 0);
1549
#endif //QT_NO_DATESTRING
1551
Sets the time to hour \a h, minute \a m, seconds \a s and
1554
\a h must be in the range 0 to 23, \a m and \a s must be in the
1555
range 0 to 59, and \a ms must be in the range 0 to 999.
1556
Returns true if the set time is valid; otherwise returns false.
1561
bool QTime::setHMS(int h, int m, int s, int ms)
1563
if (!isValid(h,m,s,ms)) {
1564
ds = MSECS_PER_DAY; // make this invalid
1567
ds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
1572
Returns a QTime object containing a time \a nsecs seconds later
1573
than the time of this object (or earlier if \a nsecs is negative).
1575
Note that the time will wrap if it passes midnight.
1580
QTime n(14, 0, 0); // n == 14:00:00
1582
t = n.addSecs(70); // t == 14:01:10
1583
t = n.addSecs(-70); // t == 13:58:50
1584
t = n.addSecs(10 * 60 * 60 + 5); // t == 00:00:05
1585
t = n.addSecs(-15 * 60 * 60); // t == 23:00:00
1588
\sa addMSecs(), secsTo(), QDateTime::addSecs()
1591
QTime QTime::addSecs(int nsecs) const
1593
return addMSecs(nsecs * 1000);
1597
Returns the number of seconds from this time to \a t.
1598
If \a t is earlier than this time, the number of seconds returned
1601
Because QTime measures time within a day and there are 86400
1602
seconds in a day, the result is always between -86400 and 86400.
1604
\sa addSecs(), QDateTime::secsTo()
1607
int QTime::secsTo(const QTime &t) const
1609
return ((int)t.ds - (int)ds)/1000;
1613
Returns a QTime object containing a time \a ms milliseconds later
1614
than the time of this object (or earlier if \a ms is negative).
1616
Note that the time will wrap if it passes midnight. See addSecs()
1619
\sa addSecs(), msecsTo()
1622
QTime QTime::addMSecs(int ms) const
1626
// % not well-defined for -ve, but / is.
1627
int negdays = (MSECS_PER_DAY-ms) / MSECS_PER_DAY;
1628
t.ds = ((int)ds + ms + negdays*MSECS_PER_DAY)
1631
t.ds = ((int)ds + ms) % MSECS_PER_DAY;
1637
Returns the number of milliseconds from this time to \a t.
1638
If \a t is earlier than this time, the number of milliseconds returned
1641
Because QTime measures time within a day and there are 86400
1642
seconds in a day, the result is always between -86400000 and
1645
\sa secsTo(), addMSecs()
1648
int QTime::msecsTo(const QTime &t) const
1650
return (int)t.ds - (int)ds;
1655
\fn bool QTime::operator==(const QTime &t) const
1657
Returns true if this time is equal to \a t; otherwise returns false.
1661
\fn bool QTime::operator!=(const QTime &t) const
1663
Returns true if this time is different from \a t; otherwise returns false.
1667
\fn bool QTime::operator<(const QTime &t) const
1669
Returns true if this time is earlier than \a t; otherwise returns false.
1673
\fn bool QTime::operator<=(const QTime &t) const
1675
Returns true if this time is earlier than or equal to \a t;
1676
otherwise returns false.
1680
\fn bool QTime::operator>(const QTime &t) const
1682
Returns true if this time is later than \a t; otherwise returns false.
1686
\fn bool QTime::operator>=(const QTime &t) const
1688
Returns true if this time is later than or equal to \a t;
1689
otherwise returns false.
1695
Returns the current time as reported by the system clock.
1697
Note that the accuracy depends on the accuracy of the underlying
1698
operating system; not all systems provide 1-millisecond accuracy.
1701
QTime QTime::currentTime()
1705
#if defined(Q_OS_WIN32)
1707
memset(&st, 0, sizeof(SYSTEMTIME));
1709
ct.ds = (uint)(MSECS_PER_HOUR * st.wHour + MSECS_PER_MIN * st.wMinute + 1000 * st.wSecond
1710
+ st.wMilliseconds);
1711
#elif defined(Q_OS_UNIX)
1712
// posix compliant system
1714
gettimeofday(&tv, 0);
1715
time_t ltime = tv.tv_sec;
1718
#if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
1719
// use the reentrant version of localtime() where available
1721
t = localtime_r(<ime, &res);
1723
t = localtime(<ime);
1726
ct.ds = (uint)(MSECS_PER_HOUR * t->tm_hour + MSECS_PER_MIN * t->tm_min + 1000 * t->tm_sec
1727
+ tv.tv_usec / 1000);
1729
time_t ltime; // no millisecond resolution
1733
ct.ds = (uint)(MSECS_PER_HOUR * t->tm_hour + MSECS_PER_MIN * t->tm_min + 1000 * t->tm_sec);
1738
#ifndef QT_NO_DATESTRING
1740
\fn QTime QTime::fromString(const QString &string, Qt::DateFormat format)
1742
Returns the time represented in the \a string as a QTime using the
1743
\a format given, or an invalid time if this is not possible.
1745
\warning Note that \c Qt::LocalDate cannot be used here.
1747
QTime QTime::fromString(const QString& s, Qt::DateFormat f)
1749
if (s.isEmpty() || f == Qt::LocalDate) {
1750
qWarning("QTime::fromString: Parameter out of range");
1752
t.ds = MSECS_PER_DAY;
1756
int hour(s.mid(0, 2).toInt());
1757
int minute(s.mid(3, 2).toInt());
1758
int second(s.mid(6, 2).toInt());
1759
int msec(s.mid(9, 3).toInt());
1760
return QTime(hour, minute, second, msec);
1766
\fn QTime::fromString(const QString &string, const QString &format)
1768
Returns the QTime represented by the \a string, using the \a
1769
format given, or an invalid time if the string cannot be parsed.
1771
These expressions may be used for the format:
1774
\header \i Expression \i Output
1776
\i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
1778
\i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
1779
\row \i m \i the minute without a leading zero (0 to 59)
1780
\row \i mm \i the minute with a leading zero (00 to 59)
1781
\row \i s \i the second whithout a leading zero (0 to 59)
1782
\row \i ss \i the second whith a leading zero (00 to 59)
1783
\row \i z \i the milliseconds without leading zeroes (0 to 999)
1784
\row \i zzz \i the milliseconds with leading zeroes (000 to 999)
1786
\i interpret as an AM/PM time. \e AP must be either "AM" or "PM".
1788
\i Interpret as an AM/PM time. \e ap must be either "am" or "pm".
1791
All other input characters will be treated as text. Any sequence
1792
of characters that are enclosed in single quotes will also be
1793
treated as text and not be used as an expression.
1796
QTime time = QTime::fromString("1mm12car00", "m'mm'hcarss");
1800
If the format is not satisfied an invalid QTime is returned.
1801
Expressions that do not expect leading zeroes to be given (h, m, s
1802
and z) are greedy. This means that they will use two digits even if
1803
this puts them outside the range of accepted values and leaves too
1804
few digits for other sections. For example, the following string
1805
could have meant 00:07:10, but the m will grab two digits, resulting
1809
QTime time = QTime::fromString("00:710", "hh:ms"); // invalid
1812
Any field that is not represented in the format will be set to zero.
1816
QTime time = QTime::fromString("1.30", "m.s");
1817
// time is 00:01:30.000
1820
\sa QDateTime::fromString() QDate::fromString() QDate::toString()
1821
QDateTime::toString() QTime::toString()
1824
QTime QTime::fromString(const QString &string, const QString &format)
1826
QDateTimeParser dt(format, QVariant::Time);
1828
return dt.fromString(string, 0, &time) ? time : QTime(-1, -1, -1);
1834
Returns true if the specified time is valid; otherwise returns
1837
The time is valid if \a h is in the range 0 to 23, \a m and
1838
\a s are in the range 0 to 59, and \a ms is in the range 0 to 999.
1843
QTime::isValid(21, 10, 30); // returns true
1844
QTime::isValid(22, 5, 62); // returns false
1848
bool QTime::isValid(int h, int m, int s, int ms)
1850
return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
1855
Sets this time to the current time. This is practical for timing:
1860
some_lengthy_task();
1861
qDebug("Time elapsed: %d ms", t.elapsed());
1864
\sa restart(), elapsed(), currentTime()
1869
*this = currentTime();
1873
Sets this time to the current time and returns the number of
1874
milliseconds that have elapsed since the last time start() or
1875
restart() was called.
1877
This function is guaranteed to be atomic and is thus very handy
1878
for repeated measurements. Call start() to start the first
1879
measurement, and restart() for each later measurement.
1881
Note that the counter wraps to zero 24 hours after the last call
1882
to start() or restart().
1884
\warning If the system's clock setting has been changed since the
1885
last time start() or restart() was called, the result is
1886
undefined. This can happen when daylight savings time is turned on
1889
\sa start(), elapsed(), currentTime()
1892
int QTime::restart()
1894
QTime t = currentTime();
1896
if (n < 0) // passed midnight
1903
Returns the number of milliseconds that have elapsed since the
1904
last time start() or restart() was called.
1906
Note that the counter wraps to zero 24 hours after the last call
1907
to start() or restart.
1909
Note that the accuracy depends on the accuracy of the underlying
1910
operating system; not all systems provide 1-millisecond accuracy.
1912
\warning If the system's clock setting has been changed since the
1913
last time start() or restart() was called, the result is
1914
undefined. This can happen when daylight savings time is turned on
1917
\sa start(), restart()
1920
int QTime::elapsed() const
1922
int n = msecsTo(currentTime());
1923
if (n < 0) // passed midnight
1929
/*****************************************************************************
1930
QDateTime member functions
1931
*****************************************************************************/
1936
\brief The QDateTime class provides date and time functions.
1941
A QDateTime object contains a calendar date and a clock time (a
1942
"datetime"). It is a combination of the QDate and QTime classes.
1943
It can read the current datetime from the system clock. It
1944
provides functions for comparing datetimes and for manipulating a
1945
datetime by adding a number of seconds, days, months, or years.
1947
A QDateTime object is typically created either by giving a date
1948
and time explicitly in the constructor, or by using the static
1949
function currentDateTime() that returns a QDateTime object set
1950
to the system clock's time. The date and time can be changed with
1951
setDate() and setTime(). A datetime can also be set using the
1952
setTime_t() function that takes a POSIX-standard "number of
1953
seconds since 00:00:00 on January 1, 1970" value. The fromString()
1954
function returns a QDateTime, given a string and a date format
1955
used to interpret the date within the string.
1957
The date() and time() functions provide access to the date and
1958
time parts of the datetime. The same information is provided in
1959
textual format by the toString() function.
1961
QDateTime provides a full set of operators to compare two
1962
QDateTime objects where smaller means earlier and larger means
1965
You can increment (or decrement) a datetime by a given number of
1966
seconds using addSecs(), or days using addDays(). Similarly you can
1967
use addMonths() and addYears(). The daysTo() function returns the
1968
number of days between two datetimes, and secsTo() returns the
1969
number of seconds between two datetimes.
1971
QDateTime can store datetimes as \l{Qt::LocalTime}{local time} or
1972
as \l{Qt::UTC}{UTC}. QDateTime::currentDateTime() returns a
1973
QDateTime expressed as local time; use toUTC() to convert it to
1974
UTC. You can also use timeSpec() to find out if a QDateTime
1975
object stores a UTC time or a local time. Operations such as
1976
addSecs() and secsTo() are aware of daylight saving time (DST).
1978
\sa QDate QTime QDateTimeEdit
1982
Constructs a null datetime (i.e. null date and null time). A null
1983
datetime is invalid, since the date is invalid.
1987
QDateTime::QDateTime()
1989
d = new QDateTimePrivate;
1994
Constructs a datetime with the given \a date, and a null but valid
1995
time (00:00:00.000).
1998
QDateTime::QDateTime(const QDate &date)
2000
d = new QDateTimePrivate;
2005
Constructs a datetime with the given \a date and \a time, using
2006
the time specification defined by \a spec.
2009
QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec)
2011
d = new QDateTimePrivate;
2014
d->spec = (spec == Qt::UTC) ? QDateTimePrivate::UTC : QDateTimePrivate::LocalUnknown;
2018
Constructs a copy of the \a other datetime.
2021
QDateTime::QDateTime(const QDateTime &other)
2028
Destroys the datetime.
2030
QDateTime::~QDateTime()
2032
if (!d->ref.deref())
2037
Makes a copy of the \a other datetime and returns a reference to the
2041
QDateTime &QDateTime::operator=(const QDateTime &other)
2043
qAtomicAssign(d, other.d);
2048
Returns true if both the date and the time are null; otherwise
2049
returns false. A null datetime is invalid.
2051
\sa QDate::isNull(), QTime::isNull(), isValid()
2054
bool QDateTime::isNull() const
2056
return d->date.isNull() && d->time.isNull();
2060
Returns true if both the date and the time are valid; otherwise
2063
\sa QDate::isValid(), QTime::isValid()
2066
bool QDateTime::isValid() const
2068
return d->date.isValid() && d->time.isValid();
2072
Returns the date part of the datetime.
2074
\sa setDate(), time(), timeSpec()
2077
QDate QDateTime::date() const
2083
Returns the time part of the datetime.
2085
\sa setTime(), date(), timeSpec()
2088
QTime QDateTime::time() const
2094
Returns the time specification of the datetime.
2096
\sa setTimeSpec(), date(), time(), Qt::TimeSpec
2099
Qt::TimeSpec QDateTime::timeSpec() const
2101
return d->spec == QDateTimePrivate::UTC ? Qt::UTC : Qt::LocalTime;
2105
Sets the date part of this datetime to \a date.
2107
\sa date(), setTime(), setTimeSpec()
2110
void QDateTime::setDate(const QDate &date)
2117
Sets the time part of this datetime to \a time.
2119
\sa time(), setDate(), setTimeSpec()
2122
void QDateTime::setTime(const QTime &time)
2129
Sets the time specification used in this datetime to \a spec.
2131
\sa timeSpec(), setDate(), setTime(), Qt::TimeSpec
2134
void QDateTime::setTimeSpec(Qt::TimeSpec spec)
2137
d->spec = (spec == Qt::UTC) ? QDateTimePrivate::UTC : QDateTimePrivate::LocalUnknown;
2140
static uint toTime_t(const QDate &utcDate, const QTime &utcTime)
2142
return (QDate(1970, 1, 1).daysTo(utcDate) * SECS_PER_DAY) + QTime().secsTo(utcTime);
2146
Returns the datetime as the number of seconds that have passed
2147
since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).
2149
On systems that do not support timezones, this function will
2150
behave as if local time were \c Qt::UTC.
2155
uint QDateTime::toTime_t() const
2159
d->getUTC(utcDate, utcTime);
2161
int secsSince1Jan1970UTC = ::toTime_t(utcDate, utcTime);
2162
if (secsSince1Jan1970UTC < 0)
2164
return (uint)secsSince1Jan1970UTC;
2168
\fn void QDateTime::setTime_t(uint seconds)
2170
Sets the date and time given the number of \a seconds that have
2171
passed since 1970-01-01T00:00:00, Coordinated Universal Time
2172
(Qt::UTC). On systems that do not support timezones this function
2173
will behave as if local time were Qt::UTC.
2178
void QDateTime::setTime_t(uint secsSince1Jan1970UTC)
2182
QDateTimePrivate::Spec oldSpec = d->spec;
2184
d->date = QDate(1970, 1, 1).addDays(secsSince1Jan1970UTC / SECS_PER_DAY);
2185
d->time = QTime().addSecs(secsSince1Jan1970UTC % SECS_PER_DAY);
2186
d->spec = QDateTimePrivate::UTC;
2188
if (oldSpec != QDateTimePrivate::UTC)
2189
d->spec = d->getLocal(d->date, d->time);
2192
#ifndef QT_NO_DATESTRING
2194
\fn QString QDateTime::toString(Qt::DateFormat format) const
2198
Returns the datetime as a string in the \a format given.
2200
If the \a format is \c Qt::TextDate, the string is formatted in
2201
the default way. QDate::shortDayName(), QDate::shortMonthName(),
2202
and QTime::toString() are used to generate the string, so the
2203
day and month names will be localized names. An example of this
2204
formatting is "Wed May 20 03:40:13 1998".
2206
If the \a format is \c Qt::ISODate, the string format corresponds
2207
to the ISO 8601 extended specification for representations of
2208
dates and times, taking the form YYYY-MM-DDTHH:MM:SS.
2210
If the \a format is \c Qt::LocalDate, the string format depends
2211
on the locale settings of the system.
2213
If the datetime is invalid, an empty string will be returned.
2215
\sa QDate::toString() QTime::toString() Qt::DateFormat
2218
QString QDateTime::toString(Qt::DateFormat f) const
2224
if (f == Qt::ISODate) {
2225
buf = d->date.toString(Qt::ISODate);
2226
buf += QLatin1Char('T');
2227
buf += d->time.toString(Qt::ISODate);
2229
#ifndef QT_NO_TEXTDATE
2230
else if (f == Qt::TextDate) {
2232
buf = d->date.shortDayName(d->date.dayOfWeek());
2233
buf += QLatin1Char(' ');
2234
buf += d->date.shortMonthName(d->date.month());
2235
buf += QLatin1Char(' ');
2236
buf += QString::number(d->date.day());
2241
GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ILDATE, out, 255);
2242
winstr = QString::fromUtf16((ushort*)out);
2245
GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_ILDATE, (char*)&out, 255);
2246
winstr = QString::fromLocal8Bit(out);
2248
switch (winstr.toInt()) {
2250
buf = d->date.shortDayName(d->date.dayOfWeek());
2251
buf += QLatin1Char(' ');
2252
buf += QString::number(d->date.day());
2253
buf += QLatin1String(". ");
2254
buf += d->date.shortMonthName(d->date.month());
2257
buf = d->date.shortDayName(d->date.dayOfWeek());
2258
buf += QLatin1Char(' ');
2259
buf += d->date.shortMonthName(d->date.month());
2260
buf += QLatin1Char(' ');
2261
buf += QString::number(d->date.day());
2264
buf += QLatin1Char(' ');
2265
buf += d->time.toString();
2266
buf += QLatin1Char(' ');
2267
buf += QString::number(d->date.year());
2270
else if (f == Qt::LocalDate) {
2271
buf = d->date.toString(Qt::LocalDate);
2272
buf += QLatin1Char(' ');
2273
buf += d->time.toString(Qt::LocalDate);
2279
Returns the datetime as a string. The \a format parameter
2280
determines the format of the result string.
2282
These expressions may be used for the date:
2285
\header \i Expression \i Output
2286
\row \i d \i the day as number without a leading zero (1 to 31)
2287
\row \i dd \i the day as number with a leading zero (01 to 31)
2289
\i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
2290
Uses QDate::shortDayName().
2292
\i the long localized day name (e.g. 'Qt::Monday' to 'Qt::Sunday').
2293
Uses QDate::longDayName().
2294
\row \i M \i the month as number without a leading zero (1-12)
2295
\row \i MM \i the month as number with a leading zero (01-12)
2297
\i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
2298
Uses QDate::shortMonthName().
2300
\i the long localized month name (e.g. 'January' to 'December').
2301
Uses QDate::longMonthName().
2302
\row \i yy \i the year as two digit number (00-99)
2303
\row \i yyyy \i the year as four digit number (1752-8000)
2306
These expressions may be used for the time:
2309
\header \i Expression \i Output
2311
\i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
2313
\i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
2314
\row \i m \i the minute without a leading zero (0 to 59)
2315
\row \i mm \i the minute with a leading zero (00 to 59)
2316
\row \i s \i the second whithout a leading zero (0 to 59)
2317
\row \i ss \i the second whith a leading zero (00 to 59)
2318
\row \i z \i the milliseconds without leading zeroes (0 to 999)
2319
\row \i zzz \i the milliseconds with leading zeroes (000 to 999)
2321
\i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
2323
\i use am/pm display. \e ap will be replaced by either "am" or "pm".
2326
All other input characters will be ignored. Any sequence of characters that
2327
are enclosed in singlequotes will be treated as text and not be used as an
2330
Example format strings (assumed that the QDateTime is 21 May 2001
2334
\header \i Format \i Result
2335
\row \i dd.MM.yyyy \i 21.05.2001
2336
\row \i ddd MMMM d yy \i Tue May 21 01
2337
\row \i hh:mm:ss.zzz \i 14:13:09.042
2338
\row \i h:m:s ap \i 2:13:9 pm
2341
If the datetime is invalid, an empty string will be returned.
2343
\sa QDate::toString() QTime::toString()
2345
QString QDateTime::toString(const QString& format) const
2347
return fmtDateTime(format, &d->time, &d->date);
2349
#endif //QT_NO_DATESTRING
2352
Returns a QDateTime object containing a datetime \a ndays days
2353
later than the datetime of this object (or earlier if \a ndays is
2356
\sa daysTo(), addMonths(), addYears(), addSecs()
2359
QDateTime QDateTime::addDays(int ndays) const
2361
return QDateTime(d->date.addDays(ndays), d->time, timeSpec());
2365
Returns a QDateTime object containing a datetime \a nmonths months
2366
later than the datetime of this object (or earlier if \a nmonths
2369
\sa daysTo(), addDays(), addYears(), addSecs()
2372
QDateTime QDateTime::addMonths(int nmonths) const
2374
return QDateTime(d->date.addMonths(nmonths), d->time, timeSpec());
2378
Returns a QDateTime object containing a datetime \a nyears years
2379
later than the datetime of this object (or earlier if \a nyears is
2382
\sa daysTo(), addDays(), addMonths(), addSecs()
2385
QDateTime QDateTime::addYears(int nyears) const
2387
return QDateTime(d->date.addYears(nyears), d->time, timeSpec());
2391
Returns a QDateTime object containing a datetime \a nsecs seconds
2392
later than the datetime of this object (or earlier if \a nsecs is
2395
\sa secsTo(), addDays(), addMonths(), addYears()
2398
QDateTime QDateTime::addSecs(int nsecs) const
2402
d->getUTC(utcDate, utcTime);
2404
uint dd = utcDate.jd;
2405
int tt = utcTime.ds;
2411
if (nsecs >= (int)SECS_PER_DAY) {
2412
dd += sign * (nsecs / SECS_PER_DAY);
2413
nsecs %= SECS_PER_DAY;
2415
tt += sign * nsecs * 1000;
2417
tt = MSECS_PER_DAY - tt - 1;
2418
dd -= tt / MSECS_PER_DAY;
2419
tt = tt % MSECS_PER_DAY;
2420
tt = MSECS_PER_DAY - tt - 1;
2421
} else if (tt >= (int)MSECS_PER_DAY) {
2422
dd += tt / MSECS_PER_DAY;
2423
tt = tt % MSECS_PER_DAY;
2427
return QDateTime(utcDate, utcTime, Qt::UTC).toTimeSpec(timeSpec());
2431
Returns the number of days from this datetime to the \a other
2432
datetime. If the \a other datetime is earlier than this datetime,
2433
the value returned is negative.
2435
\sa addDays(), secsTo()
2438
int QDateTime::daysTo(const QDateTime &other) const
2440
return d->date.daysTo(other.d->date);
2444
Returns the number of seconds from this datetime to the \a other
2445
datetime. If the \a other datetime is earlier than this datetime,
2446
the value returned is negative.
2448
Before performing the comparison, the two datetimes are converted
2449
to Qt::UTC to ensure that the result is correct if one of the two
2450
datetimes has daylight saving time (DST) and the other doesn't.
2454
QDateTime now = QDateTime::currentDateTime();
2455
QDateTime xmas(QDate(dt.date().year(), 12, 25), QTime(0, 0));
2456
qDebug("There are %d seconds to Christmas", dt.secsTo(xmas));
2459
\sa addSecs(), daysTo(), QTime::secsTo()
2462
int QDateTime::secsTo(const QDateTime &other) const
2467
d->getUTC(date1, time1);
2468
other.d->getUTC(date2, time2);
2470
return (date1.daysTo(date2) * SECS_PER_DAY) + time1.secsTo(time2);
2474
\fn QDateTime QDateTime::toTimeSpec(Qt::TimeSpec specification) const
2476
Returns a copy of this datetime configured to use the given time
2479
\sa timeSpec(), toUTC(), toLocalTime()
2482
QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const
2484
if ((d->spec == QDateTimePrivate::UTC) == (spec == Qt::UTC))
2488
if (spec == Qt::UTC) {
2489
d->getUTC(ret.d->date, ret.d->time);
2490
ret.d->spec = QDateTimePrivate::UTC;
2492
ret.d->spec = d->getLocal(ret.d->date, ret.d->time);
2498
Returns true if this datetime is equal to the \a other datetime;
2499
otherwise returns false.
2504
bool QDateTime::operator==(const QDateTime &other) const
2506
if (d->spec != other.d->spec) {
2507
if (d->spec == QDateTimePrivate::UTC || other.d->spec == QDateTimePrivate::UTC)
2509
if (d->spec != QDateTimePrivate::LocalUnknown
2510
&& other.d->spec != QDateTimePrivate::LocalUnknown)
2515
d->getUTC(date1, time1);
2516
other.d->getUTC(date2, time2);
2517
return time1 == time2 && date1 == date2;
2519
return d->time == other.d->time && d->date == other.d->date;
2524
\fn bool QDateTime::operator!=(const QDateTime &other) const
2526
Returns true if this datetime is different from the \a other
2527
datetime; otherwise returns false.
2529
Two datetimes are different if either the date, the time, or the
2530
time zone components are different.
2536
Returns true if this datetime is earlier than the \a other
2537
datetime; otherwise returns false.
2540
bool QDateTime::operator<(const QDateTime &other) const
2542
if (d->spec == other.d->spec) {
2543
if (d->date != other.d->date)
2544
return d->date < other.d->date;
2545
return d->time < other.d->time;
2549
d->getUTC(date1, time1);
2550
other.d->getUTC(date2, time2);
2552
return date1 < date2;
2553
return time1 < time2;
2558
\fn bool QDateTime::operator<=(const QDateTime &other) const
2560
Returns true if this datetime is earlier than or equal to the
2561
\a other datetime; otherwise returns false.
2565
\fn bool QDateTime::operator>(const QDateTime &other) const
2567
Returns true if this datetime is later than the \a other datetime;
2568
otherwise returns false.
2572
\fn bool QDateTime::operator>=(const QDateTime &other) const
2574
Returns true if this datetime is later than or equal to the
2575
\a other datetime; otherwise returns false.
2579
Returns the current datetime, as reported by the system clock, in
2580
the local time zone.
2582
\sa QDate::currentDate(), QTime::currentTime(), toTimeSpec()
2585
QDateTime QDateTime::currentDateTime()
2587
#if defined(Q_OS_WIN32)
2591
memset(&st, 0, sizeof(SYSTEMTIME));
2593
d.jd = QDate::gregorianToJulian(st.wYear, st.wMonth, st.wDay);
2594
t.ds = (uint)(MSECS_PER_HOUR * st.wHour + MSECS_PER_MIN * st.wMinute + 1000 * st.wSecond
2595
+ st.wMilliseconds);
2596
return QDateTime(d, t);
2600
dt.setDate(QDate::currentDate());
2601
t = QTime::currentTime();
2602
if (t.ds < (uint)MSECS_PER_MIN) // midnight or right after?
2603
dt.setDate(QDate::currentDate()); // fetch date again
2609
#ifndef QT_NO_DATESTRING
2611
\fn QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
2613
Returns the QDateTime represented by the \a string, using the
2614
\a format given, or an invalid datetime if this is not possible.
2616
Note for \c Qt::TextDate: It is recommended that you use the
2617
English short month names (e.g. "Jan"). Although localized month
2618
names can also be used, they depend on the user's locale settings.
2620
\warning Note that \c Qt::LocalDate cannot be used here.
2622
QDateTime QDateTime::fromString(const QString& s, Qt::DateFormat f)
2624
if (s.isEmpty() || f == Qt::LocalDate) {
2625
qWarning("QDateTime::fromString: Parameter out of range");
2628
if (f == Qt::ISODate) {
2629
return QDateTime(QDate::fromString(s.mid(0, 10), Qt::ISODate),
2630
QTime::fromString(s.mid(11), Qt::ISODate));
2632
#if !defined(QT_NO_REGEXP) && !defined(QT_NO_TEXTDATE)
2633
else if (f == Qt::TextDate) {
2634
QString monthName(s.mid(4, 3));
2636
// Assume that English monthnames are the default
2637
for (int i = 0; i < 12; ++i) {
2638
if (monthName == QLatin1String(qt_shortMonthNames[i])) {
2643
// If English names can't be found, search the localized ones
2645
for (int i = 1; i <= 12; ++i) {
2646
if (monthName == QDate::shortMonthName(i)) {
2652
if (month < 1 || month > 12) {
2653
qWarning("QDateTime::fromString: Parameter out of range");
2656
int day = s.mid(8, 2).simplified().toInt();
2657
int year = s.right(4).toInt();
2658
QDate date(year, month, day);
2660
int hour, minute, second;
2661
int pivot = s.indexOf(QRegExp(QString::fromLatin1("[0-9][0-9]:[0-9][0-9]:[0-9][0-9]")));
2663
hour = s.mid(pivot, 2).toInt();
2664
minute = s.mid(pivot + 3, 2).toInt();
2665
second = s.mid(pivot + 6, 2).toInt();
2666
time.setHMS(hour, minute, second);
2668
return QDateTime(date, time);
2670
#endif //QT_NO_REGEXP
2673
#endif //QT_NO_DATESTRING
2676
\fn QDateTime::fromString(const QString &string, const QString &format)
2678
Returns the QDateTime represented by the \a string, using the \a
2679
format given, or an invalid datetime if the string cannot be parsed.
2681
These expressions may be used for the date part of the format string:
2684
\header \i Expression \i Output
2685
\row \i d \i the day as number without a leading zero (1 to 31)
2686
\row \i dd \i the day as number with a leading zero (01 to 31)
2688
\i the abbreviated localized day name (e.g. 'Mon' to 'Sun').
2689
Uses QDate::shortDayName().
2691
\i the long localized day name (e.g. 'Qt::Monday' to 'Qt::Sunday').
2692
Uses QDate::longDayName().
2693
\row \i M \i the month as number without a leading zero (1-12)
2694
\row \i MM \i the month as number with a leading zero (01-12)
2696
\i the abbreviated localized month name (e.g. 'Jan' to 'Dec').
2697
Uses QDate::shortMonthName().
2699
\i the long localized month name (e.g. 'January' to 'December').
2700
Uses QDate::longMonthName().
2701
\row \i yy \i the year as two digit number (00-99)
2702
\row \i yyyy \i the year as four digit number (1752-8000)
2705
These expressions may be used for the time part of the format string:
2708
\header \i Expression \i Output
2710
\i the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
2712
\i the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
2713
\row \i m \i the minute without a leading zero (0 to 59)
2714
\row \i mm \i the minute with a leading zero (00 to 59)
2715
\row \i s \i the second whithout a leading zero (0 to 59)
2716
\row \i ss \i the second whith a leading zero (00 to 59)
2717
\row \i z \i the milliseconds without leading zeroes (0 to 999)
2718
\row \i zzz \i the milliseconds with leading zeroes (000 to 999)
2720
\i interpret as an AM/PM time. \e AP must be either "AM" or "PM".
2722
\i Interpret as an AM/PM time. \e ap must be either "am" or "pm".
2725
All other input characters will be treated as text. Any sequence
2726
of characters that are enclosed in singlequotes will also be
2727
treated as text and not be used as an expression.
2730
QDateTime dateTime = QDateTime::fromString("M1d1y9800:01:02",
2731
"'M'M'd'd'y'yyhh:mm:ss");
2732
// dateTime is 1 January 1998 00:01:02
2735
If the format is not satisfied an invalid QDateTime is returned.
2736
The expressions that don't have leading zeroes (d, M, h, m, s, z) will be
2737
greedy. This means that they will use two digits even if this will
2738
put them outside the range and/or leave too few digits for other
2742
QDateTime dateTime = QDateTime::fromString("130", "Mm"); // invalid
2745
This could have meant 1 January 00:30.00 but the M will grab
2748
For any field that is not represented in the format the following
2752
\header \i Field \i Default value
2753
\row \i Year \i The current year
2754
\row \i Month \i 1 (January)
2764
QDateTime dateTime = QDateTime::fromString("1.30.1", "M.d.s");
2765
// dateTime is January 30 in the current year 00:00:01
2768
\sa QDate::fromString() QTime::fromString() QDate::toString()
2769
QDateTime::toString() QTime::toString()
2772
QDateTime QDateTime::fromString(const QString &string, const QString &format)
2774
QDateTimeParser dt(format, QVariant::DateTime);
2777
return dt.fromString(string, &date, &time) ? QDateTime(date, time) : QDateTime(QDate(), QTime(-1, -1, -1));
2781
\fn QDateTime QDateTime::toLocalTime() const
2783
Returns a datetime containing the date and time information in
2784
this datetime, but specified using the Qt::LocalTime definition.
2790
\fn QDateTime QDateTime::toUTC() const
2792
Returns a datetime containing the date and time information in
2793
this datetime, but specified using the Qt::UTC definition.
2800
void QDateTime::detach()
2805
/*****************************************************************************
2806
Date/time stream functions
2807
*****************************************************************************/
2809
#ifndef QT_NO_DATASTREAM
2813
Writes the \a date to stream \a out.
2815
\sa {Format of the QDataStream operators}
2818
QDataStream &operator<<(QDataStream &out, const QDate &date)
2820
return out << (quint32)(date.jd);
2826
Reads a date from stream \a in into the \a date.
2828
\sa {Format of the QDataStream operators}
2831
QDataStream &operator>>(QDataStream &in, QDate &date)
2842
Writes \a time to stream \a out.
2844
\sa {Format of the QDataStream operators}
2847
QDataStream &operator<<(QDataStream &out, const QTime &time)
2849
return out << (quint32)time.ds;
2855
Reads a time from stream \a in into the given \a time.
2857
\sa {Format of the QDataStream operators}
2860
QDataStream &operator>>(QDataStream &in, QTime &time)
2871
Writes \a dateTime to the \a out stream.
2873
\sa {Format of the QDataStream operators}
2875
QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
2877
out << dateTime.d->date << dateTime.d->time;
2878
if (out.version() >= 7)
2879
out << (qint8)dateTime.d->spec;
2886
Reads a datetime from the stream \a in into \a dateTime.
2888
\sa {Format of the QDataStream operators}
2891
QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
2895
qint8 ts = (qint8)QDateTimePrivate::LocalUnknown;
2896
in >> dateTime.d->date >> dateTime.d->time;
2897
if (in.version() >= 7)
2899
dateTime.d->spec = (QDateTimePrivate::Spec)ts;
2902
#endif // QT_NO_DATASTREAM
2906
\fn QString QDate::monthName(int month)
2908
Use shortMonthName() instead.
2912
\fn QString QDate::dayName(int weekday)
2914
Use shortDayName() instead.
2918
\fn bool QDate::leapYear(int year)
2920
Use isLeapYear() instead.
2924
\fn QDate QDate::currentDate(Qt::TimeSpec spec)
2926
Use the currentDate() overload that takes no parameters; or
2927
extract from currentDateTime() instead.
2931
\fn QDate QTime::currentDate(Qt::TimeSpec spec)
2933
Use the currentDate() overload that takes no parameters; or
2934
extract from currentDateTime() instead.
2938
\fn QTime QTime::currentTime(Qt::TimeSpec spec)
2940
Use the currentTime() overload that takes no parameters; or
2941
extract from currentDateTime() instead.
2945
\fn void QDateTime::setTime_t(uint secsSince1Jan1970UTC, Qt::TimeSpec spec)
2947
Use the single-argument overload of setTime_t() instead.
2951
\fn QDateTime QDateTime::currentDateTime(Qt::TimeSpec spec)
2953
Use the currentDateTime() overload that takes no parameters
2957
#ifndef QT_NO_DATESTRING
2958
/*****************************************************************************
2959
Some static function used by QDate, QTime and QDateTime
2960
*****************************************************************************/
2962
// Replaces tokens by their value. See QDateTime::toString() for a list of valid tokens
2963
static QString getFmtString(const QString& f, const QTime* dt = 0, const QDate* dd = 0, bool am_pm = false)
2972
if (f.startsWith(QLatin1String("hh"))) {
2973
if ((am_pm) && (dt->hour() > 12))
2974
buf = QString::number(dt->hour() - 12).rightJustified(2, QLatin1Char('0'), true);
2975
else if ((am_pm) && (dt->hour() == 0))
2976
buf = QLatin1String("12");
2978
buf = QString::number(dt->hour()).rightJustified(2, QLatin1Char('0'), true);
2980
} else if (f.at(0) == QLatin1Char('h')) {
2981
if ((am_pm) && (dt->hour() > 12))
2982
buf = QString::number(dt->hour() - 12);
2983
else if ((am_pm) && (dt->hour() == 0))
2984
buf = QLatin1String("12");
2986
buf = QString::number(dt->hour());
2988
} else if (f.startsWith(QLatin1String("mm"))) {
2989
buf = QString::number(dt->minute()).rightJustified(2, QLatin1Char('0'), true);
2991
} else if (f.at(0) == (QLatin1Char('m'))) {
2992
buf = QString::number(dt->minute());
2994
} else if (f.startsWith(QLatin1String("ss"))) {
2995
buf = QString::number(dt->second()).rightJustified(2, QLatin1Char('0'), true);
2997
} else if (f.at(0) == QLatin1Char('s')) {
2998
buf = QString::number(dt->second());
2999
} else if (f.startsWith(QLatin1String("zzz"))) {
3000
buf = QString::number(dt->msec()).rightJustified(3, QLatin1Char('0'), true);
3002
} else if (f.at(0) == QLatin1Char('z')) {
3003
buf = QString::number(dt->msec());
3005
} else if (f.startsWith(QLatin1String("ap"))) {
3006
buf = dt->hour() < 12 ? QLatin1String("am") : QLatin1String("pm");
3008
} else if (f.startsWith(QLatin1String("AP"))) {
3009
buf = dt->hour() < 12 ? QLatin1String("AM") : QLatin1String("PM");
3015
if (f.startsWith(QLatin1String("dddd"))) {
3016
buf = dd->longDayName(dd->dayOfWeek());
3018
} else if (f.startsWith(QLatin1String("ddd"))) {
3019
buf = dd->shortDayName(dd->dayOfWeek());
3021
} else if (f.startsWith(QLatin1String("dd"))) {
3022
buf = QString::number(dd->day()).rightJustified(2, QLatin1Char('0'), true);
3024
} else if (f.at(0) == QLatin1Char('d')) {
3025
buf = QString::number(dd->day());
3027
} else if (f.startsWith(QLatin1String("MMMM"))) {
3028
buf = dd->longMonthName(dd->month());
3030
} else if (f.startsWith(QLatin1String("MMM"))) {
3031
buf = dd->shortMonthName(dd->month());
3033
} else if (f.startsWith(QLatin1String("MM"))) {
3034
buf = QString::number(dd->month()).rightJustified(2, QLatin1Char('0'), true);
3036
} else if (f.at(0) == QLatin1Char('M')) {
3037
buf = QString::number(dd->month());
3039
} else if (f.startsWith(QLatin1String("yyyy"))) {
3040
buf = QString::number(dd->year());
3042
} else if (f.startsWith(QLatin1String("yy"))) {
3043
buf = QString::number(dd->year()).right(2);
3047
if (removed == 0 || removed >= f.size())
3049
return buf + getFmtString(f.mid(removed), dt, dd, am_pm);
3052
// checks if there is an unqoted 'AP' or 'ap' in the string
3053
static bool hasUnqutedAP(const QString &f)
3055
const char quote = '\'';
3056
QChar status = QLatin1Char('0');
3057
for (int i=0; i<f.size(); ++i) {
3058
if (f.at(i) == quote) {
3059
if (status == quote) {
3060
if (f.at(i - 1) != QLatin1Char('\\'))
3061
status = QLatin1Char('0');
3065
} else if (status != quote) {
3066
if (f.at(i).toUpper() == QLatin1Char('A')) {
3068
} else if ((f.at(i) == QLatin1Char('p') && status == QLatin1Char('a'))
3069
|| (f.at(i) == QLatin1Char('P') && status == QLatin1Char('A'))) {
3072
status = QLatin1Char('0');
3080
// Parses the format string and uses getFmtString to get the values for the tokens. Ret
3081
static QString fmtDateTime(const QString& f, const QTime* dt, const QDate* dd)
3083
const char quote = '\'';
3086
if (dt && !dt->isValid())
3088
if (dd && !dd->isValid())
3091
bool ap = hasUnqutedAP(f);
3095
QChar status = QLatin1Char('0');
3097
for (int i = 0; i < (int)f.length(); ++i) {
3098
if (f.at(i) == quote) {
3099
if (status == quote) {
3100
status = QLatin1Char('0');
3102
if (!frm.isEmpty()) {
3103
buf += getFmtString(frm, dt, dd, ap);
3108
} else if (status == quote) {
3110
} else if (f.at(i) == status) {
3111
if ((ap) && ((f.at(i) == QLatin1Char('P')) || (f.at(i) == QLatin1Char('p'))))
3112
status = QLatin1Char('0');
3115
buf += getFmtString(frm, dt, dd, ap);
3117
if ((f.at(i) == QLatin1Char('h')) || (f.at(i) == QLatin1Char('m'))
3118
|| (f.at(i) == QLatin1Char('s')) || (f.at(i) == QLatin1Char('z'))) {
3121
} else if ((f.at(i) == QLatin1Char('d')) || (f.at(i) == QLatin1Char('M')) || (f.at(i) == QLatin1Char('y'))) {
3124
} else if ((ap) && (f.at(i) == QLatin1Char('A'))) {
3125
status = QLatin1Char('P');
3127
} else if((ap) && (f.at(i) == QLatin1Char('a'))) {
3128
status = QLatin1Char('p');
3132
status = QLatin1Char('0');
3137
buf += getFmtString(frm, dt, dd, ap);
3141
#endif // QT_NO_DATESTRING
3144
static const int LowerYear = 1980;
3146
static const int LowerYear = 1970;
3149
static QDateTimePrivate::Spec utcToLocal(QDate &date, QTime &time)
3151
QDate lowerLimit(LowerYear, 1, 2);
3152
QDate upperLimit(2037, 12, 30);
3154
QDate fakeDate = date;
3156
if (fakeDate < lowerLimit) {
3157
fakeDate = lowerLimit;
3158
} else if (fakeDate > upperLimit) {
3159
fakeDate = upperLimit;
3162
time_t secsSince1Jan1970UTC = toTime_t(fakeDate, time);
3164
#if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3165
// use the reentrant version of localtime() where available
3167
tm *brokenDown = localtime_r(&secsSince1Jan1970UTC, &res);
3169
tm *brokenDown = localtime(&secsSince1Jan1970UTC);
3170
#endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
3172
date = QDate(1970, 1, 1);
3174
return QDateTimePrivate::LocalUnknown;
3176
int deltaDays = fakeDate.daysTo(date);
3177
date = QDate(brokenDown->tm_year + 1900, brokenDown->tm_mon + 1, brokenDown->tm_mday);
3178
time = QTime(brokenDown->tm_hour, brokenDown->tm_min, brokenDown->tm_sec);
3179
date = date.addDays(deltaDays);
3180
if (brokenDown->tm_isdst > 0)
3181
return QDateTimePrivate::LocalDST;
3182
else if (brokenDown->tm_isdst < 0)
3183
return QDateTimePrivate::LocalUnknown;
3185
return QDateTimePrivate::LocalStandard;
3189
static void localToUtc(QDate &date, QTime &time, int isdst)
3191
if (!date.isValid())
3194
QDate lowerLimit(LowerYear, 1, 2);
3195
QDate upperLimit(2037, 12, 30);
3197
QDate fakeDate = date;
3199
if (fakeDate < lowerLimit) {
3200
fakeDate = lowerLimit;
3202
} else if (fakeDate > upperLimit) {
3203
fakeDate = upperLimit;
3208
localTM.tm_sec = time.second();
3209
localTM.tm_min = time.minute();
3210
localTM.tm_hour = time.hour();
3211
localTM.tm_mday = fakeDate.day();
3212
localTM.tm_mon = fakeDate.month() - 1;
3213
localTM.tm_year = fakeDate.year() - 1900;
3214
localTM.tm_isdst = (int)isdst;
3216
time_t secsSince1Jan1970UTC = mktime(&localTM);
3218
#if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
3219
// use the reentrant version of gmtime() where available
3221
tm *brokenDown = gmtime_r(&secsSince1Jan1970UTC, &res);
3223
tm *brokenDown = gmtime(&secsSince1Jan1970UTC);
3224
#endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
3226
date = QDate(1970, 1, 1);
3229
int deltaDays = fakeDate.daysTo(date);
3230
date = QDate(brokenDown->tm_year + 1900, brokenDown->tm_mon + 1, brokenDown->tm_mday);
3231
time = QTime(brokenDown->tm_hour, brokenDown->tm_min, brokenDown->tm_sec);
3232
date = date.addDays(deltaDays);
3236
QDateTimePrivate::Spec QDateTimePrivate::getLocal(QDate &outDate, QTime &outTime) const
3240
if (spec == QDateTimePrivate::UTC)
3241
return utcToLocal(outDate, outTime);
3245
void QDateTimePrivate::getUTC(QDate &outDate, QTime &outTime) const
3249
if (spec != QDateTimePrivate::UTC)
3250
localToUtc(outDate, outTime, (int)spec);
3253
#ifndef QT_NO_DEBUG_STREAM
3254
QDebug operator<<(QDebug dbg, const QDate &date)
3256
dbg.nospace() << "QDate(" << date.toString() << ")";
3260
QDebug operator<<(QDebug dbg, const QTime &time)
3262
dbg.nospace() << "QTime(" << time.toString() << ")";
3266
QDebug operator<<(QDebug dbg, const QDateTime &date)
3268
dbg.nospace() << "QDateTime(" << date.toString() << ")";
3273
QFormatSection QDateTimeParser::firstSection = QFormatSection(0, QDateTimeParser::FirstSection);
3274
QFormatSection QDateTimeParser::lastSection = QFormatSection(-1, QDateTimeParser::LastSection);
3276
QFormatSection::QFormatSection(int ind, const QString &sep)
3277
: index(ind), chars(sep), type(QDateTimeParser::Separator)
3281
QFormatSection::QFormatSection(int ind, QDateTimeParser::Section typ)
3282
: index(ind), type(typ)
3286
int QFormatSection::length() const
3288
return type == QDateTimeParser::Separator ? chars.size() : QFormatSection::length(type);
3291
int QFormatSection::length(QDateTimeParser::Section t)
3294
case QDateTimeParser::Day1: case QDateTimeParser::Month1: case QDateTimeParser::Hour1: case QDateTimeParser::Minute1:
3295
case QDateTimeParser::Second1: case QDateTimeParser::MSecond1: case QDateTimeParser::Quote: return 1;
3297
case QDateTimeParser::Day2: case QDateTimeParser::Month2: case QDateTimeParser::Year2: case QDateTimeParser::Hour2:
3298
case QDateTimeParser::Minute2: case QDateTimeParser::Second2: case QDateTimeParser::APLower: case QDateTimeParser::APUpper: return 2;
3300
case QDateTimeParser::Day3: case QDateTimeParser::Month3: case QDateTimeParser::MSecond3: return 3;
3302
case QDateTimeParser::Day4: case QDateTimeParser::Month4: case QDateTimeParser::Year4: return 4;
3305
qWarning("%s:%d QDateTimeParser::length() %d should never be called here", __FILE__, __LINE__, t);
3310
QDateTimeParser::QDateTimeParser(const QString &f, QVariant::Type t)
3316
bool QDateTimeParser::withinBounds(QDateTimeParser::Section t, int num)
3319
if (t == QDateTimeParser::Year2) {
3321
} else if (t == QDateTimeParser::Day3 || t == QDateTimeParser::Day4) {
3323
} else if (t == QDateTimeParser::Year4) {
3324
min = 1752; max = 7999;
3325
} else if (t & QDateTimeParser::MonthMask) {
3327
} else if (t & QDateTimeParser::DayMask) {
3329
} else if (t & QDateTimeParser::HourMask) {
3331
} else if (t & QDateTimeParser::MinuteMask) {
3333
} else if (t & QDateTimeParser::SecondMask) {
3335
} else if (t & QDateTimeParser::MSecondMask) {
3338
qWarning("%s:%d QDateTimeParser::withinBounds() %0x should never be called with this argument", __FILE__, __LINE__, t);
3342
return num >= min && num <= max;
3345
int QDateTimeParser::getNumber(int index, const QString &str, int mindigits, int maxdigits, bool *ok, int *digits)
3347
if (str.size() < index + mindigits) {
3355
while (i < str.size() && str.at(i++).isNumber() && *digits < maxdigits)
3358
if (*digits < mindigits) {
3363
return str.mid(index, *digits).toInt(ok);
3367
bool QDateTimeParser::isSpecial(const QChar &c) const
3370
case 'd': case 'M': case 'y':
3371
return (formatType == QVariant::Date || formatType == QVariant::DateTime);
3372
case 'h': case 'm': case 's': case 'z': case 'a': case 'p': case 'A': case 'P':
3373
return (formatType == QVariant::Time || formatType == QVariant::DateTime);
3374
case '\'': return true;
3375
default: return false;
3379
QFormatSection QDateTimeParser::findNextFormat(const QString &str, const int start)
3381
const char quote = '\'';
3383
QDateTimeParser::Section typ = QDateTimeParser::NoSection;
3384
while (i < str.size()) {
3385
const QChar &ch = str.at(i);
3386
if (isSpecial(ch)) {
3387
const QString rest = str.mid(i);
3388
switch (ch.cell()) {
3389
case quote: typ = QDateTimeParser::Quote; break;
3391
if (rest.startsWith(QLatin1String("dddd"))) {
3392
typ = QDateTimeParser::Day4;
3393
} else if (rest.startsWith(QLatin1String("ddd"))) {
3394
typ = QDateTimeParser::Day3;
3395
} else if (rest.startsWith(QLatin1String("dd"))) {
3396
typ = QDateTimeParser::Day2;
3398
typ = QDateTimeParser::Day1;
3402
if (rest.startsWith(QLatin1String("MMMM"))) {
3403
typ = QDateTimeParser::Month4;
3404
} else if (rest.startsWith(QLatin1String("MMM"))) {
3405
typ = QDateTimeParser::Month3;
3406
} else if (rest.startsWith(QLatin1String("MM"))) {
3407
typ = QDateTimeParser::Month2;
3409
typ = QDateTimeParser::Month1;
3414
if (rest.startsWith(QLatin1String("yyyy"))) {
3415
typ = QDateTimeParser::Year4;
3416
} else if (rest.startsWith(QLatin1String("yy"))) {
3417
typ = QDateTimeParser::Year2;
3422
if (rest.startsWith(QLatin1String("hh"))) {
3423
typ = QDateTimeParser::Hour2;
3425
typ = QDateTimeParser::Hour1;
3430
if (rest.startsWith(QLatin1String("mm"))) {
3431
typ = QDateTimeParser::Minute2;
3433
typ = QDateTimeParser::Minute1;
3438
if (rest.startsWith(QLatin1String("ss"))) {
3439
typ = QDateTimeParser::Second2;
3441
typ = QDateTimeParser::Second1;
3446
if (rest.startsWith(QLatin1String("zzz"))) {
3447
typ = QDateTimeParser::MSecond3;
3449
typ = QDateTimeParser::MSecond1;
3454
if (rest.count() > 1 && rest.at(1) == QLatin1Char('p')) {
3455
typ = QDateTimeParser::APLower;
3460
if (rest.count() > 1 && rest.at(1) == QLatin1Char('P')) {
3461
typ = QDateTimeParser::APUpper;
3465
default: qFatal("Should never happen"); break;
3468
if (typ != QDateTimeParser::NoSection) {
3470
return QFormatSection(start, typ);
3472
break; // found a separator before this section
3478
return QFormatSection(start, str.mid(start, i - start));
3481
void QDateTimeParser::parseFormat(const QString &f, QVariant::Type t)
3483
const char quote = '\'';
3490
while (i < format.size()) {
3492
if (format.at(i) == quote) {
3493
int nextQuote = format.indexOf(quote, i + 1);
3494
if (nextQuote == -1)
3495
nextQuote = format.size() + 1;
3496
s = QFormatSection(i, format.mid(i, nextQuote - i + 1));
3498
s = findNextFormat(format, i);
3500
if (s.type == QDateTimeParser::Separator && !sect.isEmpty() && sect.last().type == QDateTimeParser::Separator) {
3501
sect.last().chars += s.chars;
3506
i = s.index + s.length();
3510
bool QDateTimeParser::fromString(const QString &string, QDate *dateIn, QTime *timeIn)
3512
Q_ASSERT(dateIn || timeIn);
3513
const char quote = '\'';
3526
while (i<sect.size()) {
3527
if (index >= string.size()) {
3531
QString (*nameFunction)(int) = 0;
3532
const char * const * nameArray = 0;
3535
const QFormatSection &s = sect.at(i);
3537
case QDateTimeParser::Separator: {
3538
QString sep = s.chars;
3541
if (string.mid(index, sep.length()) != sep) {
3544
index += sep.size();
3547
case QDateTimeParser::APLower: {
3548
case QDateTimeParser::APUpper:
3549
const QChar a = s.type == QDateTimeParser::APLower ? QLatin1Char('a') : QLatin1Char('A');
3550
const QChar p = s.type == QDateTimeParser::APLower ? QLatin1Char('p') : QLatin1Char('P');
3551
const QChar m = s.type == QDateTimeParser::APLower ? QLatin1Char('m') : QLatin1Char('M');
3553
if ((string.at(index) != a && string.at(index) != p)
3554
|| string.size() < index + 2
3555
|| string.at(index + 1) != m) {
3558
int newampm = string.at(index) == a ? 0 : 1;
3559
if (ampm != -1 && newampm != ampm) {
3566
case QDateTimeParser::Day3: num = &day; nameFunction = &QDate::shortDayName; nameArray = qt_shortDayNames; max = 7; break;
3567
case QDateTimeParser::Day4: num = &day; nameFunction = &QDate::longDayName; nameArray = qt_longDayNames; max = 7; break;
3568
case QDateTimeParser::Month3: num = &month; nameFunction = &QDate::shortMonthName; nameArray = qt_shortMonthNames; max = 12; break;
3569
case QDateTimeParser::Month4: num = &month; nameFunction = &QDate::longMonthName; nameArray = qt_longMonthNames; max = 12; break;
3571
case QDateTimeParser::Day1: num = &day; max = 2; break;
3572
case QDateTimeParser::Month1: num = &month; max = 2; break;
3573
case QDateTimeParser::Hour1: num = &hour; max = 2; break;
3574
case QDateTimeParser::Minute1: num = &minute; max = 2; break;
3575
case QDateTimeParser::Second1: num = &sec; max = 2; break;
3576
case QDateTimeParser::MSecond1: num = &msec; max = 3; break;
3577
case QDateTimeParser::Day2: num = &day; min = 2; max = 2; break;
3578
case QDateTimeParser::Month2: num = &month; min = 2; max = 2; break;
3579
case QDateTimeParser::Year2: num = &year; min = 2; max = 2; break;
3580
case QDateTimeParser::Hour2: num = &hour; min = 2; max = 2; break;
3581
case QDateTimeParser::Minute2: num = &minute; min = 2; max = 2; break;
3582
case QDateTimeParser::Second2: num = &sec; min = 2; max = 2; break;
3583
case QDateTimeParser::MSecond3: num = &msec; min = 3; max = 3; break;
3584
case QDateTimeParser::Year4: num = &year; min = 4; max = 4; break;
3587
qWarning("%s:%d QDateTimeParser::fromString() %d should never be called here", __FILE__, __LINE__, s.type);
3592
const QString rest = string.mid(index);
3595
for (j=min; j<=max; ++j) {
3596
const QString tmp = nameFunction(j);
3597
if (rest.startsWith(tmp)) {
3601
const QLatin1String tmp2(nameArray[j - 1]);
3602
if (rest.startsWith(tmp2)) {
3603
add = strlen(tmp2.latin1());
3607
if (j > max || (*num != -1 && *num != j) || add == -1) {
3615
int number = getNumber(index, string, min, max, &ok, &digits);
3616
if (!ok || !withinBounds(s.type, number) || (*num != -1 && *num != number)) {
3625
if (index < string.size()) {
3632
year = QDate::currentDate().year();
3633
if (dayOfWeek != -1) {
3635
QDate dt(year, month, day);
3636
if (dt.dayOfWeek() != dayOfWeek) {
3640
QDate dt(year, month, 1);
3641
if (dt.dayOfWeek() < dayOfWeek) {
3642
dt = dt.addDays(dayOfWeek - dt.dayOfWeek());
3643
} else if (dt.dayOfWeek() > dayOfWeek) {
3644
dt = dt.addDays(7 + dayOfWeek - dt.dayOfWeek());
3662
} else if (hour > 12) {
3665
} else if (ampm == 1) {
3668
} else if (hour > 12) {
3674
QTime t(hour, minute, sec, msec);
3682
QDate dt(year, month, day);
3683
if (!dt.isValid()) {