PageRenderTime 68ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 1ms

/src/corelib/tools/qdatetime.cpp

https://bitbucket.org/ottoshmidt/qtbase
C++ | 5865 lines | 3215 code | 551 blank | 2099 comment | 929 complexity | 048e1a64d4221eb88f15be8d614e9c94 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, CC0-1.0, LGPL-3.0, CC-BY-SA-4.0, GPL-3.0, LGPL-2.1
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the QtCore module of the Qt Toolkit.
  7. **
  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.
  16. **
  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.
  24. **
  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.
  28. **
  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.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qplatformdefs.h"
  42. #include "private/qdatetime_p.h"
  43. #include "qdatastream.h"
  44. #include "qset.h"
  45. #include "qlocale.h"
  46. #include "qdatetime.h"
  47. #include "qregexp.h"
  48. #include "qdebug.h"
  49. #ifndef Q_OS_WIN
  50. #include <locale.h>
  51. #endif
  52. #include <cmath>
  53. #include <time.h>
  54. #ifdef Q_OS_WIN
  55. # include <qt_windows.h>
  56. # ifdef Q_OS_WINCE
  57. # include "qfunctions_wince.h"
  58. # endif
  59. #endif
  60. //#define QDATETIMEPARSER_DEBUG
  61. #if defined (QDATETIMEPARSER_DEBUG) && !defined(QT_NO_DEBUG_STREAM)
  62. # define QDTPDEBUG qDebug() << QString("%1:%2").arg(__FILE__).arg(__LINE__)
  63. # define QDTPDEBUGN qDebug
  64. #else
  65. # define QDTPDEBUG if (false) qDebug()
  66. # define QDTPDEBUGN if (false) qDebug
  67. #endif
  68. #if defined(Q_OS_MAC)
  69. #include <private/qcore_mac_p.h>
  70. #endif
  71. QT_BEGIN_NAMESPACE
  72. enum {
  73. SECS_PER_DAY = 86400,
  74. MSECS_PER_DAY = 86400000,
  75. SECS_PER_HOUR = 3600,
  76. MSECS_PER_HOUR = 3600000,
  77. SECS_PER_MIN = 60,
  78. MSECS_PER_MIN = 60000,
  79. JULIAN_DAY_FOR_EPOCH = 2440588 // result of julianDayFromDate(1970, 1, 1)
  80. };
  81. static inline QDate fixedDate(int y, int m, int d)
  82. {
  83. QDate result(y, m, 1);
  84. result.setDate(y, m, qMin(d, result.daysInMonth()));
  85. return result;
  86. }
  87. static inline qint64 floordiv(qint64 a, qint64 b)
  88. {
  89. return (a - (a < 0 ? b-1 : 0)) / b;
  90. }
  91. static inline qint64 floordiv(qint64 a, int b)
  92. {
  93. return (a - (a < 0 ? b-1 : 0)) / b;
  94. }
  95. static inline int floordiv(int a, int b)
  96. {
  97. return (a - (a < 0 ? b-1 : 0)) / b;
  98. }
  99. static inline qint64 julianDayFromDate(int year, int month, int day)
  100. {
  101. // Adjust for no year 0
  102. if (year < 0)
  103. ++year;
  104. /*
  105. * Math from The Calendar FAQ at http://www.tondering.dk/claus/cal/julperiod.php
  106. * This formula is correct for all julian days, when using mathematical integer
  107. * division (round to negative infinity), not c++11 integer division (round to zero)
  108. */
  109. int a = floordiv(14 - month, 12);
  110. qint64 y = (qint64)year + 4800 - a;
  111. int m = month + 12 * a - 3;
  112. return day + floordiv(153 * m + 2, 5) + 365 * y + floordiv(y, 4) - floordiv(y, 100) + floordiv(y, 400) - 32045;
  113. }
  114. static void getDateFromJulianDay(qint64 julianDay, int *yearp, int *monthp, int *dayp)
  115. {
  116. /*
  117. * Math from The Calendar FAQ at http://www.tondering.dk/claus/cal/julperiod.php
  118. * This formula is correct for all julian days, when using mathematical integer
  119. * division (round to negative infinity), not c++11 integer division (round to zero)
  120. */
  121. qint64 a = julianDay + 32044;
  122. qint64 b = floordiv(4 * a + 3, 146097);
  123. int c = a - floordiv(146097 * b, 4);
  124. int d = floordiv(4 * c + 3, 1461);
  125. int e = c - floordiv(1461 * d, 4);
  126. int m = floordiv(5 * e + 2, 153);
  127. int day = e - floordiv(153 * m + 2, 5) + 1;
  128. int month = m + 3 - 12 * floordiv(m, 10);
  129. int year = 100 * b + d - 4800 + floordiv(m, 10);
  130. // Adjust for no year 0
  131. if (year <= 0)
  132. --year ;
  133. if (yearp)
  134. *yearp = year;
  135. if (monthp)
  136. *monthp = month;
  137. if (dayp)
  138. *dayp = day;
  139. }
  140. static const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  141. #ifndef QT_NO_TEXTDATE
  142. static const char * const qt_shortMonthNames[] = {
  143. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  144. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  145. #endif
  146. #ifndef QT_NO_DATESTRING
  147. static QString fmtDateTime(const QString& f, const QTime* dt = 0, const QDate* dd = 0);
  148. #endif
  149. /*****************************************************************************
  150. QDate member functions
  151. *****************************************************************************/
  152. /*!
  153. \since 4.5
  154. \enum QDate::MonthNameType
  155. This enum describes the types of the string representation used
  156. for the month name.
  157. \value DateFormat This type of name can be used for date-to-string formatting.
  158. \value StandaloneFormat This type is used when you need to enumerate months or weekdays.
  159. Usually standalone names are represented in singular forms with
  160. capitalized first letter.
  161. */
  162. /*!
  163. \class QDate
  164. \inmodule QtCore
  165. \reentrant
  166. \brief The QDate class provides date functions.
  167. A QDate object contains a calendar date, i.e. year, month, and day
  168. numbers, in the Gregorian calendar. It can read the current date
  169. from the system clock. It provides functions for comparing dates,
  170. and for manipulating dates. For example, it is possible to add
  171. and subtract days, months, and years to dates.
  172. A QDate object is typically created by giving the year,
  173. month, and day numbers explicitly. Note that QDate interprets two
  174. digit years as is, i.e., years 0 - 99. A QDate can also be
  175. constructed with the static function currentDate(), which creates
  176. a QDate object containing the system clock's date. An explicit
  177. date can also be set using setDate(). The fromString() function
  178. returns a QDate given a string and a date format which is used to
  179. interpret the date within the string.
  180. The year(), month(), and day() functions provide access to the
  181. year, month, and day numbers. Also, dayOfWeek() and dayOfYear()
  182. functions are provided. The same information is provided in
  183. textual format by the toString(), shortDayName(), longDayName(),
  184. shortMonthName(), and longMonthName() functions.
  185. QDate provides a full set of operators to compare two QDate
  186. objects where smaller means earlier, and larger means later.
  187. You can increment (or decrement) a date by a given number of days
  188. using addDays(). Similarly you can use addMonths() and addYears().
  189. The daysTo() function returns the number of days between two
  190. dates.
  191. The daysInMonth() and daysInYear() functions return how many days
  192. there are in this date's month and year, respectively. The
  193. isLeapYear() function indicates whether a date is in a leap year.
  194. \section1
  195. \section2 No Year 0
  196. There is no year 0. Dates in that year are considered invalid. The
  197. year -1 is the year "1 before Christ" or "1 before current era."
  198. The day before 1 January 1 CE is 31 December 1 BCE.
  199. \section2 Range of Valid Dates
  200. Dates are stored internally as a Julian Day number, an integer count of
  201. every day in a contiguous range, with 24 November 4714 BCE in the Gregorian
  202. calendar being Julian Day 0 (1 January 4713 BCE in the Julian calendar).
  203. As well as being an efficient and accurate way of storing an absolute date,
  204. it is suitable for converting a Date into other calendar systems such as
  205. Hebrew, Islamic or Chinese. The Julian Day number can be obtained using
  206. QDate::toJulianDay() and can be set using QDate::fromJulianDay().
  207. The range of dates able to be stored by QDate as a Julian Day number is
  208. for technical reasons limited to between -784350574879 and 784354017364,
  209. which means from before 2 billion BCE to after 2 billion CE.
  210. \sa QTime, QDateTime, QDateEdit, QDateTimeEdit, QCalendarWidget
  211. */
  212. /*!
  213. \fn QDate::QDate()
  214. Constructs a null date. Null dates are invalid.
  215. \sa isNull(), isValid()
  216. */
  217. /*!
  218. Constructs a date with year \a y, month \a m and day \a d.
  219. If the specified date is invalid, the date is not set and
  220. isValid() returns false.
  221. \warning Years 0 to 99 are interpreted as is, i.e., years
  222. 0-99.
  223. \sa isValid()
  224. */
  225. QDate::QDate(int y, int m, int d)
  226. {
  227. setDate(y, m, d);
  228. }
  229. /*!
  230. \fn bool QDate::isNull() const
  231. Returns true if the date is null; otherwise returns false. A null
  232. date is invalid.
  233. \note The behavior of this function is equivalent to isValid().
  234. \sa isValid()
  235. */
  236. /*!
  237. \fn bool QDate::isValid() const
  238. Returns true if this date is valid; otherwise returns false.
  239. \sa isNull()
  240. */
  241. /*!
  242. Returns the year of this date. Negative numbers indicate years
  243. before 1 CE, such that year -44 is 44 BCE.
  244. Returns 0 if the date is invalid.
  245. \sa month(), day()
  246. */
  247. int QDate::year() const
  248. {
  249. if (isNull())
  250. return 0;
  251. int y;
  252. getDateFromJulianDay(jd, &y, 0, 0);
  253. return y;
  254. }
  255. /*!
  256. Returns the number corresponding to the month of this date, using
  257. the following convention:
  258. \list
  259. \li 1 = "January"
  260. \li 2 = "February"
  261. \li 3 = "March"
  262. \li 4 = "April"
  263. \li 5 = "May"
  264. \li 6 = "June"
  265. \li 7 = "July"
  266. \li 8 = "August"
  267. \li 9 = "September"
  268. \li 10 = "October"
  269. \li 11 = "November"
  270. \li 12 = "December"
  271. \endlist
  272. Returns 0 if the date is invalid.
  273. \sa year(), day()
  274. */
  275. int QDate::month() const
  276. {
  277. if (isNull())
  278. return 0;
  279. int m;
  280. getDateFromJulianDay(jd, 0, &m, 0);
  281. return m;
  282. }
  283. /*!
  284. Returns the day of the month (1 to 31) of this date.
  285. Returns 0 if the date is invalid.
  286. \sa year(), month(), dayOfWeek()
  287. */
  288. int QDate::day() const
  289. {
  290. if (isNull())
  291. return 0;
  292. int d;
  293. getDateFromJulianDay(jd, 0, 0, &d);
  294. return d;
  295. }
  296. /*!
  297. Returns the weekday (1 = Monday to 7 = Sunday) for this date.
  298. Returns 0 if the date is invalid.
  299. \sa day(), dayOfYear(), Qt::DayOfWeek
  300. */
  301. int QDate::dayOfWeek() const
  302. {
  303. if (isNull())
  304. return 0;
  305. if (jd >= 0)
  306. return (jd % 7) + 1;
  307. else
  308. return ((jd + 1) % 7) + 7;
  309. }
  310. /*!
  311. Returns the day of the year (1 to 365 or 366 on leap years) for
  312. this date.
  313. Returns 0 if the date is invalid.
  314. \sa day(), dayOfWeek()
  315. */
  316. int QDate::dayOfYear() const
  317. {
  318. if (isNull())
  319. return 0;
  320. return jd - julianDayFromDate(year(), 1, 1) + 1;
  321. }
  322. /*!
  323. Returns the number of days in the month (28 to 31) for this date.
  324. Returns 0 if the date is invalid.
  325. \sa day(), daysInYear()
  326. */
  327. int QDate::daysInMonth() const
  328. {
  329. if (isNull())
  330. return 0;
  331. int y, m;
  332. getDateFromJulianDay(jd, &y, &m, 0);
  333. if (m == 2 && isLeapYear(y))
  334. return 29;
  335. else
  336. return monthDays[m];
  337. }
  338. /*!
  339. Returns the number of days in the year (365 or 366) for this date.
  340. Returns 0 if the date is invalid.
  341. \sa day(), daysInMonth()
  342. */
  343. int QDate::daysInYear() const
  344. {
  345. if (isNull())
  346. return 0;
  347. int y;
  348. getDateFromJulianDay(jd, &y, 0, 0);
  349. return isLeapYear(y) ? 366 : 365;
  350. }
  351. /*!
  352. Returns the week number (1 to 53), and stores the year in
  353. *\a{yearNumber} unless \a yearNumber is null (the default).
  354. Returns 0 if the date is invalid.
  355. In accordance with ISO 8601, weeks start on Monday and the first
  356. Thursday of a year is always in week 1 of that year. Most years
  357. have 52 weeks, but some have 53.
  358. *\a{yearNumber} is not always the same as year(). For example, 1
  359. January 2000 has week number 52 in the year 1999, and 31 December
  360. 2002 has week number 1 in the year 2003.
  361. \legalese
  362. Copyright (c) 1989 The Regents of the University of California.
  363. All rights reserved.
  364. Redistribution and use in source and binary forms are permitted
  365. provided that the above copyright notice and this paragraph are
  366. duplicated in all such forms and that any documentation,
  367. advertising materials, and other materials related to such
  368. distribution and use acknowledge that the software was developed
  369. by the University of California, Berkeley. The name of the
  370. University may not be used to endorse or promote products derived
  371. from this software without specific prior written permission.
  372. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
  373. IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  374. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  375. \sa isValid()
  376. */
  377. int QDate::weekNumber(int *yearNumber) const
  378. {
  379. if (!isValid())
  380. return 0;
  381. int year = QDate::year();
  382. int yday = dayOfYear() - 1;
  383. int wday = dayOfWeek();
  384. if (wday == 7)
  385. wday = 0;
  386. int w;
  387. for (;;) {
  388. int len;
  389. int bot;
  390. int top;
  391. len = isLeapYear(year) ? 366 : 365;
  392. /*
  393. ** What yday (-3 ... 3) does
  394. ** the ISO year begin on?
  395. */
  396. bot = ((yday + 11 - wday) % 7) - 3;
  397. /*
  398. ** What yday does the NEXT
  399. ** ISO year begin on?
  400. */
  401. top = bot - (len % 7);
  402. if (top < -3)
  403. top += 7;
  404. top += len;
  405. if (yday >= top) {
  406. ++year;
  407. w = 1;
  408. break;
  409. }
  410. if (yday >= bot) {
  411. w = 1 + ((yday - bot) / 7);
  412. break;
  413. }
  414. --year;
  415. yday += isLeapYear(year) ? 366 : 365;
  416. }
  417. if (yearNumber != 0)
  418. *yearNumber = year;
  419. return w;
  420. }
  421. #ifndef QT_NO_TEXTDATE
  422. /*!
  423. \since 4.5
  424. Returns the short name of the \a month for the representation specified
  425. by \a type.
  426. The months are enumerated using the following convention:
  427. \list
  428. \li 1 = "Jan"
  429. \li 2 = "Feb"
  430. \li 3 = "Mar"
  431. \li 4 = "Apr"
  432. \li 5 = "May"
  433. \li 6 = "Jun"
  434. \li 7 = "Jul"
  435. \li 8 = "Aug"
  436. \li 9 = "Sep"
  437. \li 10 = "Oct"
  438. \li 11 = "Nov"
  439. \li 12 = "Dec"
  440. \endlist
  441. The month names will be localized according to the system's locale
  442. settings.
  443. Returns an empty string if the date is invalid.
  444. \sa toString(), longMonthName(), shortDayName(), longDayName()
  445. */
  446. QString QDate::shortMonthName(int month, QDate::MonthNameType type)
  447. {
  448. if (month < 1 || month > 12)
  449. return QString();
  450. switch (type) {
  451. case QDate::DateFormat:
  452. return QLocale::system().monthName(month, QLocale::ShortFormat);
  453. case QDate::StandaloneFormat:
  454. return QLocale::system().standaloneMonthName(month, QLocale::ShortFormat);
  455. default:
  456. break;
  457. }
  458. return QString();
  459. }
  460. /*!
  461. \since 4.5
  462. Returns the long name of the \a month for the representation specified
  463. by \a type.
  464. The months are enumerated using the following convention:
  465. \list
  466. \li 1 = "January"
  467. \li 2 = "February"
  468. \li 3 = "March"
  469. \li 4 = "April"
  470. \li 5 = "May"
  471. \li 6 = "June"
  472. \li 7 = "July"
  473. \li 8 = "August"
  474. \li 9 = "September"
  475. \li 10 = "October"
  476. \li 11 = "November"
  477. \li 12 = "December"
  478. \endlist
  479. The month names will be localized according to the system's locale
  480. settings.
  481. Returns an empty string if the date is invalid.
  482. \sa toString(), shortMonthName(), shortDayName(), longDayName()
  483. */
  484. QString QDate::longMonthName(int month, MonthNameType type)
  485. {
  486. if (month < 1 || month > 12)
  487. return QString();
  488. switch (type) {
  489. case QDate::DateFormat:
  490. return QLocale::system().monthName(month, QLocale::LongFormat);
  491. case QDate::StandaloneFormat:
  492. return QLocale::system().standaloneMonthName(month, QLocale::LongFormat);
  493. default:
  494. break;
  495. }
  496. return QString();
  497. }
  498. /*!
  499. \since 4.5
  500. Returns the short name of the \a weekday for the representation specified
  501. by \a type.
  502. The days are enumerated using the following convention:
  503. \list
  504. \li 1 = "Mon"
  505. \li 2 = "Tue"
  506. \li 3 = "Wed"
  507. \li 4 = "Thu"
  508. \li 5 = "Fri"
  509. \li 6 = "Sat"
  510. \li 7 = "Sun"
  511. \endlist
  512. The day names will be localized according to the system's locale
  513. settings.
  514. Returns an empty string if the date is invalid.
  515. \sa toString(), shortMonthName(), longMonthName(), longDayName()
  516. */
  517. QString QDate::shortDayName(int weekday, MonthNameType type)
  518. {
  519. if (weekday < 1 || weekday > 7)
  520. return QString();
  521. switch (type) {
  522. case QDate::DateFormat:
  523. return QLocale::system().dayName(weekday, QLocale::ShortFormat);
  524. case QDate::StandaloneFormat:
  525. return QLocale::system().standaloneDayName(weekday, QLocale::ShortFormat);
  526. default:
  527. break;
  528. }
  529. return QString();
  530. }
  531. /*!
  532. \since 4.5
  533. Returns the long name of the \a weekday for the representation specified
  534. by \a type.
  535. The days are enumerated using the following convention:
  536. \list
  537. \li 1 = "Monday"
  538. \li 2 = "Tuesday"
  539. \li 3 = "Wednesday"
  540. \li 4 = "Thursday"
  541. \li 5 = "Friday"
  542. \li 6 = "Saturday"
  543. \li 7 = "Sunday"
  544. \endlist
  545. The day names will be localized according to the system's locale
  546. settings.
  547. Returns an empty string if the date is invalid.
  548. \sa toString(), shortDayName(), shortMonthName(), longMonthName()
  549. */
  550. QString QDate::longDayName(int weekday, MonthNameType type)
  551. {
  552. if (weekday < 1 || weekday > 7)
  553. return QString();
  554. switch (type) {
  555. case QDate::DateFormat:
  556. return QLocale::system().dayName(weekday, QLocale::LongFormat);
  557. case QDate::StandaloneFormat:
  558. return QLocale::system().standaloneDayName(weekday, QLocale::LongFormat);
  559. default:
  560. break;
  561. }
  562. return QLocale::system().dayName(weekday, QLocale::LongFormat);
  563. }
  564. #endif //QT_NO_TEXTDATE
  565. #ifndef QT_NO_DATESTRING
  566. /*!
  567. \fn QString QDate::toString(Qt::DateFormat format) const
  568. \overload
  569. Returns the date as a string. The \a format parameter determines
  570. the format of the string.
  571. If the \a format is Qt::TextDate, the string is formatted in
  572. the default way. QDate::shortDayName() and QDate::shortMonthName()
  573. are used to generate the string, so the day and month names will
  574. be localized names. An example of this formatting is
  575. "Sat May 20 1995".
  576. If the \a format is Qt::ISODate, the string format corresponds
  577. to the ISO 8601 extended specification for representations of
  578. dates and times, taking the form YYYY-MM-DD, where YYYY is the
  579. year, MM is the month of the year (between 01 and 12), and DD is
  580. the day of the month between 01 and 31.
  581. If the \a format is Qt::SystemLocaleShortDate or
  582. Qt::SystemLocaleLongDate, the string format depends on the locale
  583. settings of the system. Identical to calling
  584. QLocale::system().toString(date, QLocale::ShortFormat) or
  585. QLocale::system().toString(date, QLocale::LongFormat).
  586. If the \a format is Qt::DefaultLocaleShortDate or
  587. Qt::DefaultLocaleLongDate, the string format depends on the
  588. default application locale. This is the locale set with
  589. QLocale::setDefault(), or the system locale if no default locale
  590. has been set. Identical to calling QLocale().toString(date,
  591. QLocale::ShortFormat) or QLocale().toString(date,
  592. QLocale::LongFormat).
  593. If the date is invalid, an empty string will be returned.
  594. \warning The Qt::ISODate format is only valid for years in the
  595. range 0 to 9999. This restriction may apply to locale-aware
  596. formats as well, depending on the locale settings.
  597. \sa shortDayName(), shortMonthName()
  598. */
  599. QString QDate::toString(Qt::DateFormat f) const
  600. {
  601. if (!isValid())
  602. return QString();
  603. int y, m, d;
  604. getDateFromJulianDay(jd, &y, &m, &d);
  605. switch (f) {
  606. case Qt::SystemLocaleDate:
  607. case Qt::SystemLocaleShortDate:
  608. case Qt::SystemLocaleLongDate:
  609. return QLocale::system().toString(*this, f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  610. : QLocale::ShortFormat);
  611. case Qt::LocaleDate:
  612. case Qt::DefaultLocaleShortDate:
  613. case Qt::DefaultLocaleLongDate:
  614. return QLocale().toString(*this, f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  615. : QLocale::ShortFormat);
  616. default:
  617. #ifndef QT_NO_TEXTDATE
  618. case Qt::TextDate:
  619. {
  620. return QString::fromLatin1("%0 %1 %2 %3")
  621. .arg(shortDayName(dayOfWeek()))
  622. .arg(shortMonthName(m))
  623. .arg(d)
  624. .arg(y);
  625. }
  626. #endif
  627. case Qt::ISODate:
  628. {
  629. if (year() < 0 || year() > 9999)
  630. return QString();
  631. QString year(QString::number(y).rightJustified(4, QLatin1Char('0')));
  632. QString month(QString::number(m).rightJustified(2, QLatin1Char('0')));
  633. QString day(QString::number(d).rightJustified(2, QLatin1Char('0')));
  634. return year + QLatin1Char('-') + month + QLatin1Char('-') + day;
  635. }
  636. }
  637. }
  638. /*!
  639. Returns the date as a string. The \a format parameter determines
  640. the format of the result string.
  641. These expressions may be used:
  642. \table
  643. \header \li Expression \li Output
  644. \row \li d \li the day as number without a leading zero (1 to 31)
  645. \row \li dd \li the day as number with a leading zero (01 to 31)
  646. \row \li ddd
  647. \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
  648. Uses QDate::shortDayName().
  649. \row \li dddd
  650. \li the long localized day name (e.g. 'Monday' to 'Sunday').
  651. Uses QDate::longDayName().
  652. \row \li M \li the month as number without a leading zero (1 to 12)
  653. \row \li MM \li the month as number with a leading zero (01 to 12)
  654. \row \li MMM
  655. \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
  656. Uses QDate::shortMonthName().
  657. \row \li MMMM
  658. \li the long localized month name (e.g. 'January' to 'December').
  659. Uses QDate::longMonthName().
  660. \row \li yy \li the year as two digit number (00 to 99)
  661. \row \li yyyy \li the year as four digit number. If the year is negative,
  662. a minus sign is prepended in addition.
  663. \endtable
  664. All other input characters will be ignored. Any sequence of characters that
  665. are enclosed in single quotes will be treated as text and not be used as an
  666. expression. Two consecutive single quotes ("''") are replaced by a singlequote
  667. in the output. Formats without separators (e.g. "ddMM") are currently not supported.
  668. Example format strings (assuming that the QDate is the 20 July
  669. 1969):
  670. \table
  671. \header \li Format \li Result
  672. \row \li dd.MM.yyyy \li 20.07.1969
  673. \row \li ddd MMMM d yy \li Sun July 20 69
  674. \row \li 'The day is' dddd \li The day is Sunday
  675. \endtable
  676. If the datetime is invalid, an empty string will be returned.
  677. \warning The Qt::ISODate format is only valid for years in the
  678. range 0 to 9999. This restriction may apply to locale-aware
  679. formats as well, depending on the locale settings.
  680. \sa QDateTime::toString(), QTime::toString()
  681. */
  682. QString QDate::toString(const QString& format) const
  683. {
  684. if (year() > 9999)
  685. return QString();
  686. return fmtDateTime(format, 0, this);
  687. }
  688. #endif //QT_NO_DATESTRING
  689. /*!
  690. \fn bool QDate::setYMD(int y, int m, int d)
  691. \deprecated in 5.0, use setDate() instead.
  692. Sets the date's year \a y, month \a m, and day \a d.
  693. If \a y is in the range 0 to 99, it is interpreted as 1900 to
  694. 1999.
  695. Returns \c false if the date is invalid.
  696. Use setDate() instead.
  697. */
  698. /*!
  699. \since 4.2
  700. Sets the date's \a year, \a month, and \a day. Returns true if
  701. the date is valid; otherwise returns false.
  702. If the specified date is invalid, the QDate object is set to be
  703. invalid.
  704. \sa isValid()
  705. */
  706. bool QDate::setDate(int year, int month, int day)
  707. {
  708. if (isValid(year, month, day))
  709. jd = julianDayFromDate(year, month, day);
  710. else
  711. jd = nullJd();
  712. return isValid();
  713. }
  714. /*!
  715. \since 4.5
  716. Extracts the date's year, month, and day, and assigns them to
  717. *\a year, *\a month, and *\a day. The pointers may be null.
  718. Returns 0 if the date is invalid.
  719. \sa year(), month(), day(), isValid()
  720. */
  721. void QDate::getDate(int *year, int *month, int *day)
  722. {
  723. if (isValid()) {
  724. getDateFromJulianDay(jd, year, month, day);
  725. } else {
  726. if (year)
  727. *year = 0;
  728. if (month)
  729. *month = 0;
  730. if (day)
  731. *day = 0;
  732. }
  733. }
  734. /*!
  735. Returns a QDate object containing a date \a ndays later than the
  736. date of this object (or earlier if \a ndays is negative).
  737. Returns a null date if the current date is invalid or the new date is
  738. out of range.
  739. \sa addMonths(), addYears(), daysTo()
  740. */
  741. QDate QDate::addDays(qint64 ndays) const
  742. {
  743. if (isNull())
  744. return QDate();
  745. // Due to limits on minJd() and maxJd() we know that any overflow
  746. // will be invalid and caught by fromJulianDay().
  747. return fromJulianDay(jd + ndays);
  748. }
  749. /*!
  750. Returns a QDate object containing a date \a nmonths later than the
  751. date of this object (or earlier if \a nmonths is negative).
  752. \note If the ending day/month combination does not exist in the
  753. resulting month/year, this function will return a date that is the
  754. latest valid date.
  755. \sa addDays(), addYears()
  756. */
  757. QDate QDate::addMonths(int nmonths) const
  758. {
  759. if (!isValid())
  760. return QDate();
  761. if (!nmonths)
  762. return *this;
  763. int old_y, y, m, d;
  764. getDateFromJulianDay(jd, &y, &m, &d);
  765. old_y = y;
  766. bool increasing = nmonths > 0;
  767. while (nmonths != 0) {
  768. if (nmonths < 0 && nmonths + 12 <= 0) {
  769. y--;
  770. nmonths+=12;
  771. } else if (nmonths < 0) {
  772. m+= nmonths;
  773. nmonths = 0;
  774. if (m <= 0) {
  775. --y;
  776. m += 12;
  777. }
  778. } else if (nmonths - 12 >= 0) {
  779. y++;
  780. nmonths -= 12;
  781. } else if (m == 12) {
  782. y++;
  783. m = 0;
  784. } else {
  785. m += nmonths;
  786. nmonths = 0;
  787. if (m > 12) {
  788. ++y;
  789. m -= 12;
  790. }
  791. }
  792. }
  793. // was there a sign change?
  794. if ((old_y > 0 && y <= 0) ||
  795. (old_y < 0 && y >= 0))
  796. // yes, adjust the date by +1 or -1 years
  797. y += increasing ? +1 : -1;
  798. return fixedDate(y, m, d);
  799. }
  800. /*!
  801. Returns a QDate object containing a date \a nyears later than the
  802. date of this object (or earlier if \a nyears is negative).
  803. \note If the ending day/month combination does not exist in the
  804. resulting year (i.e., if the date was Feb 29 and the final year is
  805. not a leap year), this function will return a date that is the
  806. latest valid date (that is, Feb 28).
  807. \sa addDays(), addMonths()
  808. */
  809. QDate QDate::addYears(int nyears) const
  810. {
  811. if (!isValid())
  812. return QDate();
  813. int y, m, d;
  814. getDateFromJulianDay(jd, &y, &m, &d);
  815. int old_y = y;
  816. y += nyears;
  817. // was there a sign change?
  818. if ((old_y > 0 && y <= 0) ||
  819. (old_y < 0 && y >= 0))
  820. // yes, adjust the date by +1 or -1 years
  821. y += nyears > 0 ? +1 : -1;
  822. return fixedDate(y, m, d);
  823. }
  824. /*!
  825. Returns the number of days from this date to \a d (which is
  826. negative if \a d is earlier than this date).
  827. Returns 0 if either date is invalid.
  828. Example:
  829. \snippet code/src_corelib_tools_qdatetime.cpp 0
  830. \sa addDays()
  831. */
  832. qint64 QDate::daysTo(const QDate &d) const
  833. {
  834. if (isNull() || d.isNull())
  835. return 0;
  836. // Due to limits on minJd() and maxJd() we know this will never overflow
  837. return d.jd - jd;
  838. }
  839. /*!
  840. \fn bool QDate::operator==(const QDate &d) const
  841. Returns true if this date is equal to \a d; otherwise returns
  842. false.
  843. */
  844. /*!
  845. \fn bool QDate::operator!=(const QDate &d) const
  846. Returns true if this date is different from \a d; otherwise
  847. returns false.
  848. */
  849. /*!
  850. \fn bool QDate::operator<(const QDate &d) const
  851. Returns true if this date is earlier than \a d; otherwise returns
  852. false.
  853. */
  854. /*!
  855. \fn bool QDate::operator<=(const QDate &d) const
  856. Returns true if this date is earlier than or equal to \a d;
  857. otherwise returns false.
  858. */
  859. /*!
  860. \fn bool QDate::operator>(const QDate &d) const
  861. Returns true if this date is later than \a d; otherwise returns
  862. false.
  863. */
  864. /*!
  865. \fn bool QDate::operator>=(const QDate &d) const
  866. Returns true if this date is later than or equal to \a d;
  867. otherwise returns false.
  868. */
  869. /*!
  870. \fn QDate::currentDate()
  871. Returns the current date, as reported by the system clock.
  872. \sa QTime::currentTime(), QDateTime::currentDateTime()
  873. */
  874. #ifndef QT_NO_DATESTRING
  875. /*!
  876. \fn QDate QDate::fromString(const QString &string, Qt::DateFormat format)
  877. Returns the QDate represented by the \a string, using the
  878. \a format given, or an invalid date if the string cannot be
  879. parsed.
  880. Note for Qt::TextDate: It is recommended that you use the
  881. English short month names (e.g. "Jan"). Although localized month
  882. names can also be used, they depend on the user's locale settings.
  883. */
  884. QDate QDate::fromString(const QString& s, Qt::DateFormat f)
  885. {
  886. if (s.isEmpty())
  887. return QDate();
  888. switch (f) {
  889. case Qt::ISODate:
  890. {
  891. int year(s.mid(0, 4).toInt());
  892. int month(s.mid(5, 2).toInt());
  893. int day(s.mid(8, 2).toInt());
  894. if (year && month && day)
  895. return QDate(year, month, day);
  896. }
  897. break;
  898. case Qt::SystemLocaleDate:
  899. case Qt::SystemLocaleShortDate:
  900. case Qt::SystemLocaleLongDate:
  901. return fromString(s, QLocale::system().dateFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  902. : QLocale::ShortFormat));
  903. case Qt::LocaleDate:
  904. case Qt::DefaultLocaleShortDate:
  905. case Qt::DefaultLocaleLongDate:
  906. return fromString(s, QLocale().dateFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  907. : QLocale::ShortFormat));
  908. default:
  909. #ifndef QT_NO_TEXTDATE
  910. case Qt::TextDate: {
  911. QStringList parts = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
  912. if (parts.count() != 4) {
  913. return QDate();
  914. }
  915. QString monthName = parts.at(1);
  916. int month = -1;
  917. // Assume that English monthnames are the default
  918. for (int i = 0; i < 12; ++i) {
  919. if (monthName == QLatin1String(qt_shortMonthNames[i])) {
  920. month = i + 1;
  921. break;
  922. }
  923. }
  924. // If English names can't be found, search the localized ones
  925. if (month == -1) {
  926. for (int i = 1; i <= 12; ++i) {
  927. if (monthName == QDate::shortMonthName(i)) {
  928. month = i;
  929. break;
  930. }
  931. }
  932. if (month == -1) {
  933. // Month name matches neither English nor other localised name.
  934. return QDate();
  935. }
  936. }
  937. bool ok;
  938. int day = parts.at(2).toInt(&ok);
  939. if (!ok) {
  940. return QDate();
  941. }
  942. int year = parts.at(3).toInt(&ok);
  943. if (!ok) {
  944. return QDate();
  945. }
  946. return QDate(year, month, day);
  947. }
  948. #else
  949. break;
  950. #endif
  951. }
  952. return QDate();
  953. }
  954. /*!
  955. \fn QDate::fromString(const QString &string, const QString &format)
  956. Returns the QDate represented by the \a string, using the \a
  957. format given, or an invalid date if the string cannot be parsed.
  958. These expressions may be used for the format:
  959. \table
  960. \header \li Expression \li Output
  961. \row \li d \li The day as a number without a leading zero (1 to 31)
  962. \row \li dd \li The day as a number with a leading zero (01 to 31)
  963. \row \li ddd
  964. \li The abbreviated localized day name (e.g. 'Mon' to 'Sun').
  965. Uses QDate::shortDayName().
  966. \row \li dddd
  967. \li The long localized day name (e.g. 'Monday' to 'Sunday').
  968. Uses QDate::longDayName().
  969. \row \li M \li The month as a number without a leading zero (1 to 12)
  970. \row \li MM \li The month as a number with a leading zero (01 to 12)
  971. \row \li MMM
  972. \li The abbreviated localized month name (e.g. 'Jan' to 'Dec').
  973. Uses QDate::shortMonthName().
  974. \row \li MMMM
  975. \li The long localized month name (e.g. 'January' to 'December').
  976. Uses QDate::longMonthName().
  977. \row \li yy \li The year as two digit number (00 to 99)
  978. \row \li yyyy \li The year as four digit number. If the year is negative,
  979. a minus sign is prepended in addition.
  980. \endtable
  981. All other input characters will be treated as text. Any sequence
  982. of characters that are enclosed in single quotes will also be
  983. treated as text and will not be used as an expression. For example:
  984. \snippet code/src_corelib_tools_qdatetime.cpp 1
  985. If the format is not satisfied, an invalid QDate is returned. The
  986. expressions that don't expect leading zeroes (d, M) will be
  987. greedy. This means that they will use two digits even if this
  988. will put them outside the accepted range of values and leaves too
  989. few digits for other sections. For example, the following format
  990. string could have meant January 30 but the M will grab two
  991. digits, resulting in an invalid date:
  992. \snippet code/src_corelib_tools_qdatetime.cpp 2
  993. For any field that is not represented in the format the following
  994. defaults are used:
  995. \table
  996. \header \li Field \li Default value
  997. \row \li Year \li 1900
  998. \row \li Month \li 1
  999. \row \li Day \li 1
  1000. \endtable
  1001. The following examples demonstrate the default values:
  1002. \snippet code/src_corelib_tools_qdatetime.cpp 3
  1003. \sa QDateTime::fromString(), QTime::fromString(), QDate::toString(),
  1004. QDateTime::toString(), QTime::toString()
  1005. */
  1006. QDate QDate::fromString(const QString &string, const QString &format)
  1007. {
  1008. QDate date;
  1009. #ifndef QT_BOOTSTRAPPED
  1010. QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString);
  1011. if (dt.parseFormat(format))
  1012. dt.fromString(string, &date, 0);
  1013. #else
  1014. Q_UNUSED(string);
  1015. Q_UNUSED(format);
  1016. #endif
  1017. return date;
  1018. }
  1019. #endif // QT_NO_DATESTRING
  1020. /*!
  1021. \overload
  1022. Returns true if the specified date (\a year, \a month, and \a
  1023. day) is valid; otherwise returns false.
  1024. Example:
  1025. \snippet code/src_corelib_tools_qdatetime.cpp 4
  1026. \sa isNull(), setDate()
  1027. */
  1028. bool QDate::isValid(int year, int month, int day)
  1029. {
  1030. // there is no year 0 in the Gregorian calendar
  1031. if (year == 0)
  1032. return false;
  1033. return (day > 0 && month > 0 && month <= 12) &&
  1034. (day <= monthDays[month] || (day == 29 && month == 2 && isLeapYear(year)));
  1035. }
  1036. /*!
  1037. \fn bool QDate::isLeapYear(int year)
  1038. Returns true if the specified \a year is a leap year; otherwise
  1039. returns false.
  1040. */
  1041. bool QDate::isLeapYear(int y)
  1042. {
  1043. // No year 0 in Gregorian calendar, so -1, -5, -9 etc are leap years
  1044. if ( y < 1)
  1045. ++y;
  1046. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  1047. }
  1048. /*! \fn static QDate QDate::fromJulianDay(qint64 jd)
  1049. Converts the Julian day \a jd to a QDate.
  1050. \sa toJulianDay()
  1051. */
  1052. /*! \fn int QDate::toJulianDay() const
  1053. Converts the date to a Julian day.
  1054. \sa fromJulianDay()
  1055. */
  1056. /*****************************************************************************
  1057. QTime member functions
  1058. *****************************************************************************/
  1059. /*!
  1060. \class QTime
  1061. \inmodule QtCore
  1062. \reentrant
  1063. \brief The QTime class provides clock time functions.
  1064. A QTime object contains a clock time, i.e. the number of hours,
  1065. minutes, seconds, and milliseconds since midnight. It can read the
  1066. current time from the system clock and measure a span of elapsed
  1067. time. It provides functions for comparing times and for
  1068. manipulating a time by adding a number of milliseconds.
  1069. QTime uses the 24-hour clock format; it has no concept of AM/PM.
  1070. Unlike QDateTime, QTime knows nothing about time zones or
  1071. daylight savings time (DST).
  1072. A QTime object is typically created either by giving the number
  1073. of hours, minutes, seconds, and milliseconds explicitly, or by
  1074. using the static function currentTime(), which creates a QTime
  1075. object that contains the system's local time. Note that the
  1076. accuracy depends on the accuracy of the underlying operating
  1077. system; not all systems provide 1-millisecond accuracy.
  1078. The hour(), minute(), second(), and msec() functions provide
  1079. access to the number of hours, minutes, seconds, and milliseconds
  1080. of the time. The same information is provided in textual format by
  1081. the toString() function.
  1082. QTime provides a full set of operators to compare two QTime
  1083. objects. QTime A is considered smaller than QTime B if A is
  1084. earlier than B.
  1085. The addSecs() and addMSecs() functions provide the time a given
  1086. number of seconds or milliseconds later than a given time.
  1087. Correspondingly, the number of seconds or milliseconds
  1088. between two times can be found using secsTo() or msecsTo().
  1089. QTime can be used to measure a span of elapsed time using the
  1090. start(), restart(), and elapsed() functions.
  1091. \sa QDate, QDateTime
  1092. */
  1093. /*!
  1094. \fn QTime::QTime()
  1095. Constructs a null time object. A null time can be a QTime(0, 0, 0, 0)
  1096. (i.e., midnight) object, except that isNull() returns true and isValid()
  1097. returns false.
  1098. \sa isNull(), isValid()
  1099. */
  1100. /*!
  1101. Constructs a time with hour \a h, minute \a m, seconds \a s and
  1102. milliseconds \a ms.
  1103. \a h must be in the range 0 to 23, \a m and \a s must be in the
  1104. range 0 to 59, and \a ms must be in the range 0 to 999.
  1105. \sa isValid()
  1106. */
  1107. QTime::QTime(int h, int m, int s, int ms)
  1108. {
  1109. setHMS(h, m, s, ms);
  1110. }
  1111. /*!
  1112. \fn bool QTime::isNull() const
  1113. Returns true if the time is null (i.e., the QTime object was
  1114. constructed using the default constructor); otherwise returns
  1115. false. A null time is also an invalid time.
  1116. \sa isValid()
  1117. */
  1118. /*!
  1119. Returns true if the time is valid; otherwise returns false. For example,
  1120. the time 23:30:55.746 is valid, but 24:12:30 is invalid.
  1121. \sa isNull()
  1122. */
  1123. bool QTime::isValid() const
  1124. {
  1125. return mds > NullTime && mds < MSECS_PER_DAY;
  1126. }
  1127. /*!
  1128. Returns the hour part (0 to 23) of the time.
  1129. Returns -1 if the time is invalid.
  1130. \sa minute(), second(), msec()
  1131. */
  1132. int QTime::hour() const
  1133. {
  1134. if (!isValid())
  1135. return -1;
  1136. return ds() / MSECS_PER_HOUR;
  1137. }
  1138. /*!
  1139. Returns the minute part (0 to 59) of the time.
  1140. Returns -1 if the time is invalid.
  1141. \sa hour(), second(), msec()
  1142. */
  1143. int QTime::minute() const
  1144. {
  1145. if (!isValid())
  1146. return -1;
  1147. return (ds() % MSECS_PER_HOUR) / MSECS_PER_MIN;
  1148. }
  1149. /*!
  1150. Returns the second part (0 to 59) of the time.
  1151. Returns -1 if the time is invalid.
  1152. \sa hour(), minute(), msec()
  1153. */
  1154. int QTime::second() const
  1155. {
  1156. if (!isValid())
  1157. return -1;
  1158. return (ds() / 1000)%SECS_PER_MIN;
  1159. }
  1160. /*!
  1161. Returns the millisecond part (0 to 999) of the time.
  1162. Returns -1 if the time is invalid.
  1163. \sa hour(), minute(), second()
  1164. */
  1165. int QTime::msec() const
  1166. {
  1167. if (!isValid())
  1168. return -1;
  1169. return ds() % 1000;
  1170. }
  1171. #ifndef QT_NO_DATESTRING
  1172. /*!
  1173. \overload
  1174. Returns the time as a string. Milliseconds are not included. The
  1175. \a format parameter determines the format of the string.
  1176. If \a format is Qt::TextDate, the string format is HH:MM:SS; e.g. 1
  1177. second before midnight would be "23:59:59".
  1178. If \a format is Qt::ISODate, the string format corresponds to the
  1179. ISO 8601 extended specification for representations of dates,
  1180. which is also HH:MM:SS. (However, contrary to ISO 8601, dates
  1181. before 15 October 1582 are handled as Julian dates, not Gregorian
  1182. dates. See \l{QDate G and J} {Use of Gregorian and Julian
  1183. Calendars}. This might change in a future version of Qt.)
  1184. If the \a format is Qt::SystemLocaleShortDate or
  1185. Qt::SystemLocaleLongDate, the string format depends on the locale
  1186. settings of the system. Identical to calling
  1187. QLocale::system().toString(time, QLocale::ShortFormat) or
  1188. QLocale::system().toString(time, QLocale::LongFormat).
  1189. If the \a format is Qt::DefaultLocaleShortDate or
  1190. Qt::DefaultLocaleLongDate, the string format depends on the
  1191. default application locale. This is the locale set with
  1192. QLocale::setDefault(), or the system locale if no default locale
  1193. has been set. Identical to calling QLocale().toString(time,
  1194. QLocale::ShortFormat) or QLocale().toString(time,
  1195. QLocale::LongFormat).
  1196. If the time is invalid, an empty string will be returned.
  1197. */
  1198. QString QTime::toString(Qt::DateFormat format) const
  1199. {
  1200. if (!isValid())
  1201. return QString();
  1202. switch (format) {
  1203. case Qt::SystemLocaleDate:
  1204. case Qt::SystemLocaleShortDate:
  1205. case Qt::SystemLocaleLongDate:
  1206. return QLocale::system().toString(*this, format == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  1207. : QLocale::ShortFormat);
  1208. case Qt::LocaleDate:
  1209. case Qt::DefaultLocaleShortDate:
  1210. case Qt::DefaultLocaleLongDate:
  1211. return QLocale().toString(*this, format == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  1212. : QLocale::ShortFormat);
  1213. default:
  1214. case Qt::ISODate:
  1215. case Qt::TextDate:
  1216. return QString::fromLatin1("%1:%2:%3")
  1217. .arg(hour(), 2, 10, QLatin1Char('0'))
  1218. .arg(minute(), 2, 10, QLatin1Char('0'))
  1219. .arg(second(), 2, 10, QLatin1Char('0'));
  1220. }
  1221. }
  1222. /*!
  1223. Returns the time as a string. The \a format parameter determines
  1224. the format of the result string.
  1225. These expressions may be used:
  1226. \table
  1227. \header \li Expression \li Output
  1228. \row \li h
  1229. \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
  1230. \row \li hh
  1231. \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
  1232. \row \li H
  1233. \li the hour without a leading zero (0 to 23, even with AM/PM display)
  1234. \row \li HH
  1235. \li the hour with a leading zero (00 to 23, even with AM/PM display)
  1236. \row \li m \li the minute without a leading zero (0 to 59)
  1237. \row \li mm \li the minute with a leading zero (00 to 59)
  1238. \row \li s \li the second without a leading zero (0 to 59)
  1239. \row \li ss \li the second with a leading zero (00 to 59)
  1240. \row \li z \li the milliseconds without leading zeroes (0 to 999)
  1241. \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
  1242. \row \li AP or A
  1243. \li use AM/PM display. \e AP will be replaced by either "AM" or "PM".
  1244. \row \li ap or a
  1245. \li use am/pm display. \e ap will be replaced by either "am" or "pm".
  1246. \row \li t \li the timezone (for example "CEST")
  1247. \endtable
  1248. All other input characters will be ignored. Any sequence of characters that
  1249. are enclosed in single quotes will be treated as text and not be used as an
  1250. expression. Two consecutive single quotes ("''") are replaced by a singlequote
  1251. in the output. Formats without separators (e.g. "HHmm") are currently not supported.
  1252. Example format strings (assuming that the QTime is 14:13:09.042)
  1253. \table
  1254. \header \li Format \li Result
  1255. \row \li hh:mm:ss.zzz \li 14:13:09.042
  1256. \row \li h:m:s ap \li 2:13:9 pm
  1257. \row \li H:m:s a \li 14:13:9 pm
  1258. \endtable
  1259. If the time is invalid, an empty string will be returned.
  1260. If \a format is empty, the default format "hh:mm:ss" is used.
  1261. \sa QDate::toString(), QDateTime::toString()
  1262. */
  1263. QString QTime::toString(const QString& format) const
  1264. {
  1265. return fmtDateTime(format, this, 0);
  1266. }
  1267. #endif //QT_NO_DATESTRING
  1268. /*!
  1269. Sets the time to hour \a h, minute \a m, seconds \a s and
  1270. milliseconds \a ms.
  1271. \a h must be in the range 0 to 23, \a m and \a s must be in the
  1272. range 0 to 59, and \a ms must be in the range 0 to 999.
  1273. Returns true if the set time is valid; otherwise returns false.
  1274. \sa isValid()
  1275. */
  1276. bool QTime::setHMS(int h, int m, int s, int ms)
  1277. {
  1278. #if defined(Q_OS_WINCE)
  1279. startTick = NullTime;
  1280. #endif
  1281. if (!isValid(h,m,s,ms)) {
  1282. mds = NullTime; // make this invalid
  1283. return false;
  1284. }
  1285. mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
  1286. return true;
  1287. }
  1288. /*!
  1289. Returns a QTime object containing a time \a s seconds later
  1290. than the time of this object (or earlier if \a s is negative).
  1291. Note that the time will wrap if it passes midnight.
  1292. Returns a null time if this time is invalid.
  1293. Example:
  1294. \snippet code/src_corelib_tools_qdatetime.cpp 5
  1295. \sa addMSecs(), secsTo(), QDateTime::addSecs()
  1296. */
  1297. QTime QTime::addSecs(int s) const
  1298. {
  1299. return addMSecs(s * 1000);
  1300. }
  1301. /*!
  1302. Returns the number of seconds from this time to \a t.
  1303. If \a t is earlier than this time, the number of seconds returned
  1304. is negative.
  1305. Because QTime measures time within a day and there are 86400
  1306. seconds in a day, the result is always between -86400 and 86400.
  1307. secsTo() does not take into account any milliseconds.
  1308. Returns 0 if either time is invalid.
  1309. \sa addSecs(), QDateTime::secsTo()
  1310. */
  1311. int QTime::secsTo(const QTime &t) const
  1312. {
  1313. if (!isValid() || !t.isValid())
  1314. return 0;
  1315. // Truncate milliseconds as we do not want to consider them.
  1316. int ourSeconds = ds() / 1000;
  1317. int theirSeconds = t.ds() / 1000;
  1318. return theirSeconds - ourSeconds;
  1319. }
  1320. /*!
  1321. Returns a QTime object containing a time \a ms milliseconds later
  1322. than the time of this object (or earlier if \a ms is negative).
  1323. Note that the time will wrap if it passes midnight. See addSecs()
  1324. for an example.
  1325. Returns a null time if this time is invalid.
  1326. \sa addSecs(), msecsTo(), QDateTime::addMSecs()
  1327. */
  1328. QTime QTime::addMSecs(int ms) const
  1329. {
  1330. QTime t;
  1331. if (isValid()) {
  1332. if (ms < 0) {
  1333. // % not well-defined for -ve, but / is.
  1334. int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
  1335. t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
  1336. } else {
  1337. t.mds = (ds() + ms) % MSECS_PER_DAY;
  1338. }
  1339. }
  1340. #if defined(Q_OS_WINCE)
  1341. if (startTick > NullTime)
  1342. t.startTick = (startTick + ms) % MSECS_PER_DAY;
  1343. #endif
  1344. return t;
  1345. }
  1346. /*!
  1347. Returns the number of milliseconds from this time to \a t.
  1348. If \a t is earlier than this time, the number of milliseconds returned
  1349. is negative.
  1350. Because QTime measures time within a day and there are 86400
  1351. seconds in a day, the result is always between -86400000 and
  1352. 86400000 ms.
  1353. Returns 0 if either time is invalid.
  1354. \sa secsTo(), addMSecs(), QDateTime::msecsTo()
  1355. */
  1356. int QTime::msecsTo(const QTime &t) const
  1357. {
  1358. if (!isValid() || !t.isValid())
  1359. return 0;
  1360. #if defined(Q_OS_WINCE)
  1361. // GetLocalTime() for Windows CE has no milliseconds resolution
  1362. if (t.startTick > NullTime && startTick > NullTime)
  1363. return t.startTick - startTick;
  1364. else
  1365. #endif
  1366. return t.ds() - ds();
  1367. }
  1368. /*!
  1369. \fn bool QTime::operator==(const QTime &t) const
  1370. Returns true if this time is equal to \a t; otherwise returns false.
  1371. */
  1372. /*!
  1373. \fn bool QTime::operator!=(const QTime &t) const
  1374. Returns true if this time is different from \a t; otherwise returns false.
  1375. */
  1376. /*!
  1377. \fn bool QTime::operator<(const QTime &t) const
  1378. Returns true if this time is earlier than \a t; otherwise returns false.
  1379. */
  1380. /*!
  1381. \fn bool QTime::operator<=(const QTime &t) const
  1382. Returns true if this time is earlier than or equal to \a t;
  1383. otherwise returns false.
  1384. */
  1385. /*!
  1386. \fn bool QTime::operator>(const QTime &t) const
  1387. Returns true if this time is later than \a t; otherwise returns false.
  1388. */
  1389. /*!
  1390. \fn bool QTime::operator>=(const QTime &t) const
  1391. Returns true if this time is later than or equal to \a t;
  1392. otherwise returns false.
  1393. */
  1394. /*!
  1395. \fn QTime::currentTime()
  1396. Returns the current time as reported by the system clock.
  1397. Note that the accuracy depends on the accuracy of the underlying
  1398. operating system; not all systems provide 1-millisecond accuracy.
  1399. */
  1400. #ifndef QT_NO_DATESTRING
  1401. // These anonymous functions tidy up QDateTime::fromString()
  1402. // and avoid confusion of responsibility between it and QTime::fromString().
  1403. namespace {
  1404. inline bool isMidnight(int hour, int minute, int second, int msec)
  1405. {
  1406. return hour == 24 && minute == 0 && second == 0 && msec == 0;
  1407. }
  1408. QTime fromStringImpl(const QString &s, Qt::DateFormat f, bool &isMidnight24)
  1409. {
  1410. if (s.isEmpty()) {
  1411. // Return a null time.
  1412. return QTime();
  1413. }
  1414. switch (f) {
  1415. case Qt::SystemLocaleDate:
  1416. case Qt::SystemLocaleShortDate:
  1417. case Qt::SystemLocaleLongDate:
  1418. {
  1419. QLocale::FormatType formatType(Qt::SystemLocaleLongDate ? QLocale::LongFormat : QLocale::ShortFormat);
  1420. return QTime::fromString(s, QLocale::system().timeFormat(formatType));
  1421. }
  1422. case Qt::LocaleDate:
  1423. case Qt::DefaultLocaleShortDate:
  1424. case Qt::DefaultLocaleLongDate:
  1425. {
  1426. QLocale::FormatType formatType(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat : QLocale::ShortFormat);
  1427. return QTime::fromString(s, QLocale().timeFormat(formatType));
  1428. }
  1429. case Qt::TextDate:
  1430. case Qt::ISODate:
  1431. {
  1432. bool ok = true;
  1433. const int hour(s.mid(0, 2).toInt(&ok));
  1434. if (!ok)
  1435. return QTime();
  1436. const int minute(s.mid(3, 2).toInt(&ok));
  1437. if (!ok)
  1438. return QTime();
  1439. if (f == Qt::ISODate) {
  1440. if (s.size() == 5) {
  1441. // Do not need to specify seconds if using ISO format.
  1442. return QTime(hour, minute, 0, 0);
  1443. } else if ((s.size() > 6) && (s[5] == QLatin1Char(',') || s[5] == QLatin1Char('.'))) {
  1444. // Possibly specifying fraction of a minute.
  1445. // We only want 5 digits worth of fraction of minute. This follows the existing
  1446. // behaviour that determines how milliseconds are read; 4 millisecond digits are
  1447. // read and then rounded to 3. If we read at most 5 digits for fraction of minute,
  1448. // the maximum amount of millisecond digits it will expand to once converted to
  1449. // seconds is 4. E.g. 12:34,99999 will expand to 12:34:59.9994. The milliseconds
  1450. // will then be rounded up AND clamped to 999.
  1451. const QString minuteFractionStr(QLatin1String("0.") + s.mid(6, 5));
  1452. const float minuteFraction = minuteFractionStr.toFloat(&ok);
  1453. if (!ok)
  1454. return QTime();
  1455. const float secondWithMs = minuteFraction * 60;
  1456. const float second = std::floor(secondWithMs);
  1457. const float millisecond = 1000 * (secondWithMs - second);
  1458. const int millisecondRounded = qMin(qRound(millisecond), 999);
  1459. if (isMidnight(hour, minute, second, millisecondRounded)) {
  1460. isMidnight24 = true;
  1461. return QTime(0, 0, 0, 0);
  1462. }
  1463. return QTime(hour, minute, second, millisecondRounded);
  1464. }
  1465. }
  1466. const int second(s.mid(6, 2).toInt(&ok));
  1467. if (!ok)
  1468. return QTime();
  1469. const QString msec_s(QLatin1String("0.") + s.mid(9, 4));
  1470. const double msec(msec_s.toDouble(&ok));
  1471. if (!ok)
  1472. return QTime(hour, minute, second, 0);
  1473. if (f == Qt::ISODate) {
  1474. if (isMidnight(hour, minute, second, msec)) {
  1475. isMidnight24 = true;
  1476. return QTime(0, 0, 0, 0);
  1477. }
  1478. }
  1479. return QTime(hour, minute, second, qMin(qRound(msec * 1000.0), 999));
  1480. }
  1481. }
  1482. Q_UNREACHABLE();
  1483. return QTime();
  1484. }
  1485. }
  1486. /*!
  1487. \fn QTime QTime::fromString(const QString &string, Qt::DateFormat format)
  1488. Returns the time represented in the \a string as a QTime using the
  1489. \a format given, or an invalid time if this is not possible.
  1490. Note that fromString() uses a "C" locale encoded string to convert
  1491. milliseconds to a float value. If the default locale is not "C",
  1492. this may result in two conversion attempts (if the conversion
  1493. fails for the default locale). This should be considered an
  1494. implementation detail.
  1495. */
  1496. QTime QTime::fromString(const QString& s, Qt::DateFormat f)
  1497. {
  1498. bool unused;
  1499. return fromStringImpl(s, f, unused);
  1500. }
  1501. /*!
  1502. \fn QTime::fromString(const QString &string, const QString &format)
  1503. Returns the QTime represented by the \a string, using the \a
  1504. format given, or an invalid time if the string cannot be parsed.
  1505. These expressions may be used for the format:
  1506. \table
  1507. \header \li Expression \li Output
  1508. \row \li h
  1509. \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
  1510. \row \li hh
  1511. \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
  1512. \row \li m \li the minute without a leading zero (0 to 59)
  1513. \row \li mm \li the minute with a leading zero (00 to 59)
  1514. \row \li s \li the second without a leading zero (0 to 59)
  1515. \row \li ss \li the second with a leading zero (00 to 59)
  1516. \row \li z \li the milliseconds without leading zeroes (0 to 999)
  1517. \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
  1518. \row \li AP
  1519. \li interpret as an AM/PM time. \e AP must be either "AM" or "PM".
  1520. \row \li ap
  1521. \li Interpret as an AM/PM time. \e ap must be either "am" or "pm".
  1522. \endtable
  1523. All other input characters will be treated as text. Any sequence
  1524. of characters that are enclosed in single quotes will also be
  1525. treated as text and not be used as an expression.
  1526. \snippet code/src_corelib_tools_qdatetime.cpp 6
  1527. If the format is not satisfied, an invalid QTime is returned.
  1528. Expressions that do not expect leading zeroes to be given (h, m, s
  1529. and z) are greedy. This means that they will use two digits even if
  1530. this puts them outside the range of accepted values and leaves too
  1531. few digits for other sections. For example, the following string
  1532. could have meant 00:07:10, but the m will grab two digits, resulting
  1533. in an invalid time:
  1534. \snippet code/src_corelib_tools_qdatetime.cpp 7
  1535. Any field that is not represented in the format will be set to zero.
  1536. For example:
  1537. \snippet code/src_corelib_tools_qdatetime.cpp 8
  1538. \sa QDateTime::fromString(), QDate::fromString(), QDate::toString(),
  1539. QDateTime::toString(), QTime::toString()
  1540. */
  1541. QTime QTime::fromString(const QString &string, const QString &format)
  1542. {
  1543. QTime time;
  1544. #ifndef QT_BOOTSTRAPPED
  1545. QDateTimeParser dt(QVariant::Time, QDateTimeParser::FromString);
  1546. if (dt.parseFormat(format))
  1547. dt.fromString(string, 0, &time);
  1548. #else
  1549. Q_UNUSED(string);
  1550. Q_UNUSED(format);
  1551. #endif
  1552. return time;
  1553. }
  1554. #endif // QT_NO_DATESTRING
  1555. /*!
  1556. \overload
  1557. Returns true if the specified time is valid; otherwise returns
  1558. false.
  1559. The time is valid if \a h is in the range 0 to 23, \a m and
  1560. \a s are in the range 0 to 59, and \a ms is in the range 0 to 999.
  1561. Example:
  1562. \snippet code/src_corelib_tools_qdatetime.cpp 9
  1563. */
  1564. bool QTime::isValid(int h, int m, int s, int ms)
  1565. {
  1566. return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
  1567. }
  1568. /*!
  1569. Sets this time to the current time. This is practical for timing:
  1570. \snippet code/src_corelib_tools_qdatetime.cpp 10
  1571. \sa restart(), elapsed(), currentTime()
  1572. */
  1573. void QTime::start()
  1574. {
  1575. *this = currentTime();
  1576. }
  1577. /*!
  1578. Sets this time to the current time and returns the number of
  1579. milliseconds that have elapsed since the last time start() or
  1580. restart() was called.
  1581. This function is guaranteed to be atomic and is thus very handy
  1582. for repeated measurements. Call start() to start the first
  1583. measurement, and restart() for each later measurement.
  1584. Note that the counter wraps to zero 24 hours after the last call
  1585. to start() or restart().
  1586. \warning If the system's clock setting has been changed since the
  1587. last time start() or restart() was called, the result is
  1588. undefined. This can happen when daylight savings time is turned on
  1589. or off.
  1590. \sa start(), elapsed(), currentTime()
  1591. */
  1592. int QTime::restart()
  1593. {
  1594. QTime t = currentTime();
  1595. int n = msecsTo(t);
  1596. if (n < 0) // passed midnight
  1597. n += 86400*1000;
  1598. *this = t;
  1599. return n;
  1600. }
  1601. /*!
  1602. Returns the number of milliseconds that have elapsed since the
  1603. last time start() or restart() was called.
  1604. Note that the counter wraps to zero 24 hours after the last call
  1605. to start() or restart.
  1606. Note that the accuracy depends on the accuracy of the underlying
  1607. operating system; not all systems provide 1-millisecond accuracy.
  1608. \warning If the system's clock setting has been changed since the
  1609. last time start() or restart() was called, the result is
  1610. undefined. This can happen when daylight savings time is turned on
  1611. or off.
  1612. \sa start(), restart()
  1613. */
  1614. int QTime::elapsed() const
  1615. {
  1616. int n = msecsTo(currentTime());
  1617. if (n < 0) // passed midnight
  1618. n += 86400 * 1000;
  1619. return n;
  1620. }
  1621. /*****************************************************************************
  1622. QDateTime member functions
  1623. *****************************************************************************/
  1624. /*!
  1625. \class QDateTime
  1626. \inmodule QtCore
  1627. \reentrant
  1628. \brief The QDateTime class provides date and time functions.
  1629. A QDateTime object contains a calendar date and a clock time (a
  1630. "datetime"). It is a combination of the QDate and QTime classes.
  1631. It can read the current datetime from the system clock. It
  1632. provides functions for comparing datetimes and for manipulating a
  1633. datetime by adding a number of seconds, days, months, or years.
  1634. A QDateTime object is typically created either by giving a date
  1635. and time explicitly in the constructor, or by using the static
  1636. function currentDateTime() that returns a QDateTime object set
  1637. to the system clock's time. The date and time can be changed with
  1638. setDate() and setTime(). A datetime can also be set using the
  1639. setTime_t() function that takes a POSIX-standard "number of
  1640. seconds since 00:00:00 on January 1, 1970" value. The fromString()
  1641. function returns a QDateTime, given a string and a date format
  1642. used to interpret the date within the string.
  1643. The date() and time() functions provide access to the date and
  1644. time parts of the datetime. The same information is provided in
  1645. textual format by the toString() function.
  1646. QDateTime provides a full set of operators to compare two
  1647. QDateTime objects, where smaller means earlier and larger means
  1648. later.
  1649. You can increment (or decrement) a datetime by a given number of
  1650. milliseconds using addMSecs(), seconds using addSecs(), or days
  1651. using addDays(). Similarly, you can use addMonths() and addYears().
  1652. The daysTo() function returns the number of days between two datetimes,
  1653. secsTo() returns the number of seconds between two datetimes, and
  1654. msecsTo() returns the number of milliseconds between two datetimes.
  1655. QDateTime can store datetimes as \l{Qt::LocalTime}{local time} or
  1656. as \l{Qt::UTC}{UTC}. QDateTime::currentDateTime() returns a
  1657. QDateTime expressed as local time; use toUTC() to convert it to
  1658. UTC. You can also use timeSpec() to find out if a QDateTime
  1659. object stores a UTC time or a local time. Operations such as
  1660. addSecs() and secsTo() are aware of daylight saving time (DST).
  1661. \note QDateTime does not account for leap seconds.
  1662. \section1
  1663. \section2 No Year 0
  1664. There is no year 0. Dates in that year are considered invalid. The
  1665. year -1 is the year "1 before Christ" or "1 before current era."
  1666. The day before 1 January 1 CE is 31 December 1 BCE.
  1667. \section2 Range of Valid Dates
  1668. Dates are stored internally as a Julian Day number, an integer count of
  1669. every day in a contiguous range, with 24 November 4714 BCE in the Gregorian
  1670. calendar being Julian Day 0 (1 January 4713 BCE in the Julian calendar).
  1671. As well as being an efficient and accurate way of storing an absolute date,
  1672. it is suitable for converting a Date into other calendar systems such as
  1673. Hebrew, Islamic or Chinese. The Julian Day number can be obtained using
  1674. QDate::toJulianDay() and can be set using QDate::fromJulianDay().
  1675. The range of dates able to be stored by QDate as a Julian Day number is
  1676. for technical reasons limited to between -784350574879 and 784354017364,
  1677. which means from before 2 billion BCE to after 2 billion CE.
  1678. \section2
  1679. Use of System Timezone
  1680. QDateTime uses the system's time zone information to determine the
  1681. offset of local time from UTC. If the system is not configured
  1682. correctly or not up-to-date, QDateTime will give wrong results as
  1683. well.
  1684. \section2 Daylight Savings Time (DST)
  1685. QDateTime takes into account the system's time zone information
  1686. when dealing with DST. On modern Unix systems, this means it
  1687. applies the correct historical DST data whenever possible. On
  1688. Windows and Windows CE, where the system doesn't support
  1689. historical DST data, historical accuracy is not maintained with
  1690. respect to DST.
  1691. The range of valid dates taking DST into account is 1970-01-01 to
  1692. the present, and rules are in place for handling DST correctly
  1693. until 2037-12-31, but these could change. For dates falling
  1694. outside that range, QDateTime makes a \e{best guess} using the
  1695. rules for year 1970 or 2037, but we can't guarantee accuracy. This
  1696. means QDateTime doesn't take into account changes in a locale's
  1697. time zone before 1970, even if the system's time zone database
  1698. supports that information.
  1699. \sa QDate, QTime, QDateTimeEdit
  1700. */
  1701. /*!
  1702. Constructs a null datetime (i.e. null date and null time). A null
  1703. datetime is invalid, since the date is invalid.
  1704. \sa isValid()
  1705. */
  1706. QDateTime::QDateTime()
  1707. : d(new QDateTimePrivate)
  1708. {
  1709. }
  1710. /*!
  1711. Constructs a datetime with the given \a date, a valid
  1712. time(00:00:00.000), and sets the timeSpec() to Qt::LocalTime.
  1713. */
  1714. QDateTime::QDateTime(const QDate &date)
  1715. : d(new QDateTimePrivate)
  1716. {
  1717. d->date = date;
  1718. d->time = QTime(0, 0, 0);
  1719. }
  1720. /*!
  1721. Constructs a datetime with the given \a date and \a time, using
  1722. the time specification defined by \a spec.
  1723. If \a date is valid and \a time is not, the time will be set to midnight.
  1724. */
  1725. QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec)
  1726. : d(new QDateTimePrivate)
  1727. {
  1728. d->date = date;
  1729. d->time = date.isValid() && !time.isValid() ? QTime(0, 0, 0) : time;
  1730. d->spec = (spec == Qt::UTC) ? QDateTimePrivate::UTC : QDateTimePrivate::LocalUnknown;
  1731. }
  1732. /*!
  1733. Constructs a copy of the \a other datetime.
  1734. */
  1735. QDateTime::QDateTime(const QDateTime &other)
  1736. : d(other.d)
  1737. {
  1738. }
  1739. /*!
  1740. Destroys the datetime.
  1741. */
  1742. QDateTime::~QDateTime()
  1743. {
  1744. }
  1745. /*!
  1746. Makes a copy of the \a other datetime and returns a reference to the
  1747. copy.
  1748. */
  1749. QDateTime &QDateTime::operator=(const QDateTime &other)
  1750. {
  1751. d = other.d;
  1752. return *this;
  1753. }
  1754. /*!
  1755. \fn void QDateTime::swap(QDateTime &other)
  1756. \since 5.0
  1757. Swaps this datetime with \a other. This operation is very fast
  1758. and never fails.
  1759. */
  1760. /*!
  1761. Returns true if both the date and the time are null; otherwise
  1762. returns false. A null datetime is invalid.
  1763. \sa QDate::isNull(), QTime::isNull(), isValid()
  1764. */
  1765. bool QDateTime::isNull() const
  1766. {
  1767. return d->date.isNull() && d->time.isNull();
  1768. }
  1769. /*!
  1770. Returns true if both the date and the time are valid; otherwise
  1771. returns false.
  1772. \sa QDate::isValid(), QTime::isValid()
  1773. */
  1774. bool QDateTime::isValid() const
  1775. {
  1776. return d->date.isValid() && d->time.isValid();
  1777. }
  1778. /*!
  1779. Returns the date part of the datetime.
  1780. \sa setDate(), time(), timeSpec()
  1781. */
  1782. QDate QDateTime::date() const
  1783. {
  1784. return d->date;
  1785. }
  1786. /*!
  1787. Returns the time part of the datetime.
  1788. \sa setTime(), date(), timeSpec()
  1789. */
  1790. QTime QDateTime::time() const
  1791. {
  1792. return d->time;
  1793. }
  1794. /*!
  1795. Returns the time specification of the datetime.
  1796. \sa setTimeSpec(), date(), time(), Qt::TimeSpec
  1797. */
  1798. Qt::TimeSpec QDateTime::timeSpec() const
  1799. {
  1800. switch(d->spec)
  1801. {
  1802. case QDateTimePrivate::UTC:
  1803. return Qt::UTC;
  1804. case QDateTimePrivate::OffsetFromUTC:
  1805. return Qt::OffsetFromUTC;
  1806. default:
  1807. return Qt::LocalTime;
  1808. }
  1809. }
  1810. /*!
  1811. Sets the date part of this datetime to \a date.
  1812. If no time is set, it is set to midnight.
  1813. \sa date(), setTime(), setTimeSpec()
  1814. */
  1815. void QDateTime::setDate(const QDate &date)
  1816. {
  1817. detach();
  1818. d->date = date;
  1819. if (d->spec == QDateTimePrivate::LocalStandard
  1820. || d->spec == QDateTimePrivate::LocalDST)
  1821. d->spec = QDateTimePrivate::LocalUnknown;
  1822. if (date.isValid() && !d->time.isValid())
  1823. d->time = QTime(0, 0, 0);
  1824. }
  1825. /*!
  1826. Sets the time part of this datetime to \a time.
  1827. \sa time(), setDate(), setTimeSpec()
  1828. */
  1829. void QDateTime::setTime(const QTime &time)
  1830. {
  1831. detach();
  1832. if (d->spec == QDateTimePrivate::LocalStandard
  1833. || d->spec == QDateTimePrivate::LocalDST)
  1834. d->spec = QDateTimePrivate::LocalUnknown;
  1835. d->time = time;
  1836. }
  1837. /*!
  1838. Sets the time specification used in this datetime to \a spec.
  1839. The datetime will refer to a different point in time.
  1840. Example:
  1841. \snippet code/src_corelib_tools_qdatetime.cpp 19
  1842. \sa timeSpec(), setDate(), setTime(), Qt::TimeSpec
  1843. */
  1844. void QDateTime::setTimeSpec(Qt::TimeSpec spec)
  1845. {
  1846. detach();
  1847. switch(spec)
  1848. {
  1849. case Qt::UTC:
  1850. d->spec = QDateTimePrivate::UTC;
  1851. break;
  1852. case Qt::OffsetFromUTC:
  1853. d->spec = QDateTimePrivate::OffsetFromUTC;
  1854. break;
  1855. default:
  1856. d->spec = QDateTimePrivate::LocalUnknown;
  1857. break;
  1858. }
  1859. }
  1860. qint64 toMSecsSinceEpoch_helper(qint64 jd, int msecs)
  1861. {
  1862. qint64 days = jd - JULIAN_DAY_FOR_EPOCH;
  1863. qint64 retval = (days * MSECS_PER_DAY) + msecs;
  1864. return retval;
  1865. }
  1866. /*!
  1867. \since 4.7
  1868. Returns the datetime as the number of milliseconds that have passed
  1869. since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
  1870. On systems that do not support time zones, this function will
  1871. behave as if local time were Qt::UTC.
  1872. The behavior for this function is undefined if the datetime stored in
  1873. this object is not valid. However, for all valid dates, this function
  1874. returns a unique value.
  1875. \sa toTime_t(), setMSecsSinceEpoch()
  1876. */
  1877. qint64 QDateTime::toMSecsSinceEpoch() const
  1878. {
  1879. QDate utcDate;
  1880. QTime utcTime;
  1881. d->getUTC(utcDate, utcTime);
  1882. return toMSecsSinceEpoch_helper(utcDate.toJulianDay(), QTime(0, 0, 0).msecsTo(utcTime));
  1883. }
  1884. /*!
  1885. Returns the datetime as the number of seconds that have passed
  1886. since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).
  1887. On systems that do not support time zones, this function will
  1888. behave as if local time were Qt::UTC.
  1889. \note This function returns a 32-bit unsigned integer, so it does not
  1890. support dates before 1970, but it does support dates after
  1891. 2038-01-19T03:14:06, which may not be valid time_t values. Be careful
  1892. when passing those time_t values to system functions, which could
  1893. interpret them as negative dates.
  1894. If the date is outside the range 1970-01-01T00:00:00 to
  1895. 2106-02-07T06:28:14, this function returns -1 cast to an unsigned integer
  1896. (i.e., 0xFFFFFFFF).
  1897. To get an extended range, use toMSecsSinceEpoch().
  1898. \sa toMSecsSinceEpoch(), setTime_t()
  1899. */
  1900. uint QDateTime::toTime_t() const
  1901. {
  1902. qint64 retval = toMSecsSinceEpoch() / 1000;
  1903. if (quint64(retval) >= Q_UINT64_C(0xFFFFFFFF))
  1904. return uint(-1);
  1905. return uint(retval);
  1906. }
  1907. /*!
  1908. \since 4.7
  1909. Sets the date and time given the number of milliseconds \a msecs that have
  1910. passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
  1911. (Qt::UTC). On systems that do not support time zones this function
  1912. will behave as if local time were Qt::UTC.
  1913. Note that there are possible values for \a msecs that lie outside the
  1914. valid range of QDateTime, both negative and positive. The behavior of
  1915. this function is undefined for those values.
  1916. \sa toMSecsSinceEpoch(), setTime_t()
  1917. */
  1918. void QDateTime::setMSecsSinceEpoch(qint64 msecs)
  1919. {
  1920. detach();
  1921. QDateTimePrivate::Spec oldSpec = d->spec;
  1922. qint64 ddays = msecs / MSECS_PER_DAY;
  1923. msecs %= MSECS_PER_DAY;
  1924. if (msecs < 0) {
  1925. // negative
  1926. --ddays;
  1927. msecs += MSECS_PER_DAY;
  1928. }
  1929. d->date = QDate(1970, 1, 1).addDays(ddays);
  1930. d->time = QTime(0, 0, 0).addMSecs(msecs);
  1931. d->spec = QDateTimePrivate::UTC;
  1932. if (oldSpec != QDateTimePrivate::UTC)
  1933. d->spec = d->getLocal(d->date, d->time);
  1934. }
  1935. /*!
  1936. \fn void QDateTime::setTime_t(uint seconds)
  1937. Sets the date and time given the number of \a seconds that have
  1938. passed since 1970-01-01T00:00:00, Coordinated Universal Time
  1939. (Qt::UTC). On systems that do not support time zones this function
  1940. will behave as if local time were Qt::UTC.
  1941. \sa toTime_t()
  1942. */
  1943. void QDateTime::setTime_t(uint secsSince1Jan1970UTC)
  1944. {
  1945. detach();
  1946. QDateTimePrivate::Spec oldSpec = d->spec;
  1947. d->date = QDate(1970, 1, 1).addDays(secsSince1Jan1970UTC / SECS_PER_DAY);
  1948. d->time = QTime(0, 0, 0).addSecs(secsSince1Jan1970UTC % SECS_PER_DAY);
  1949. d->spec = QDateTimePrivate::UTC;
  1950. if (oldSpec != QDateTimePrivate::UTC)
  1951. d->spec = d->getLocal(d->date, d->time);
  1952. }
  1953. #ifndef QT_NO_DATESTRING
  1954. /*!
  1955. \fn QString QDateTime::toString(Qt::DateFormat format) const
  1956. \overload
  1957. Returns the datetime as a string in the \a format given.
  1958. If the \a format is Qt::TextDate, the string is formatted in
  1959. the default way. QDate::shortDayName(), QDate::shortMonthName(),
  1960. and QTime::toString() are used to generate the string, so the
  1961. day and month names will be localized names. An example of this
  1962. formatting is "Wed May 20 03:40:13 1998".
  1963. If the \a format is Qt::ISODate, the string format corresponds
  1964. to the ISO 8601 extended specification for representations of
  1965. dates and times, taking the form YYYY-MM-DDTHH:MM:SS[Z|[+|-]HH:MM],
  1966. depending on the timeSpec() of the QDateTime. If the timeSpec()
  1967. is Qt::UTC, Z will be appended to the string; if the timeSpec() is
  1968. Qt::OffsetFromUTC, the offset in hours and minutes from UTC will
  1969. be appended to the string.
  1970. If the \a format is Qt::SystemLocaleShortDate or
  1971. Qt::SystemLocaleLongDate, the string format depends on the locale
  1972. settings of the system. Identical to calling
  1973. QLocale::system().toString(datetime, QLocale::ShortFormat) or
  1974. QLocale::system().toString(datetime, QLocale::LongFormat).
  1975. If the \a format is Qt::DefaultLocaleShortDate or
  1976. Qt::DefaultLocaleLongDate, the string format depends on the
  1977. default application locale. This is the locale set with
  1978. QLocale::setDefault(), or the system locale if no default locale
  1979. has been set. Identical to calling QLocale().toString(datetime,
  1980. QLocale::ShortFormat) or QLocale().toString(datetime,
  1981. QLocale::LongFormat).
  1982. If the datetime is invalid, an empty string will be returned.
  1983. \warning The Qt::ISODate format is only valid for years in the
  1984. range 0 to 9999. This restriction may apply to locale-aware
  1985. formats as well, depending on the locale settings.
  1986. \sa QDate::toString(), QTime::toString(), Qt::DateFormat
  1987. */
  1988. QString QDateTime::toString(Qt::DateFormat f) const
  1989. {
  1990. QString buf;
  1991. if (!isValid())
  1992. return buf;
  1993. if (f == Qt::ISODate) {
  1994. buf = d->date.toString(Qt::ISODate);
  1995. if (buf.isEmpty())
  1996. return QString(); // failed to convert
  1997. buf += QLatin1Char('T');
  1998. buf += d->time.toString(Qt::ISODate);
  1999. switch (d->spec) {
  2000. case QDateTimePrivate::UTC:
  2001. buf += QLatin1Char('Z');
  2002. break;
  2003. case QDateTimePrivate::OffsetFromUTC: {
  2004. int sign = d->utcOffset >= 0 ? 1: -1;
  2005. buf += QString::fromLatin1("%1%2:%3").
  2006. arg(sign == 1 ? QLatin1Char('+') : QLatin1Char('-')).
  2007. arg(d->utcOffset * sign / SECS_PER_HOUR, 2, 10, QLatin1Char('0')).
  2008. arg((d->utcOffset / 60) % 60, 2, 10, QLatin1Char('0'));
  2009. break;
  2010. }
  2011. default:
  2012. break;
  2013. }
  2014. }
  2015. #ifndef QT_NO_TEXTDATE
  2016. else if (f == Qt::TextDate) {
  2017. #ifndef Q_OS_WIN
  2018. buf = d->date.shortDayName(d->date.dayOfWeek());
  2019. buf += QLatin1Char(' ');
  2020. buf += d->date.shortMonthName(d->date.month());
  2021. buf += QLatin1Char(' ');
  2022. buf += QString::number(d->date.day());
  2023. #else
  2024. wchar_t out[255];
  2025. GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ILDATE, out, 255);
  2026. QString winstr = QString::fromWCharArray(out);
  2027. switch (winstr.toInt()) {
  2028. case 1:
  2029. buf = d->date.shortDayName(d->date.dayOfWeek());
  2030. buf += QLatin1Char(' ');
  2031. buf += QString::number(d->date.day());
  2032. buf += QLatin1String(". ");
  2033. buf += d->date.shortMonthName(d->date.month());
  2034. break;
  2035. default:
  2036. buf = d->date.shortDayName(d->date.dayOfWeek());
  2037. buf += QLatin1Char(' ');
  2038. buf += d->date.shortMonthName(d->date.month());
  2039. buf += QLatin1Char(' ');
  2040. buf += QString::number(d->date.day());
  2041. }
  2042. #endif
  2043. buf += QLatin1Char(' ');
  2044. buf += d->time.toString();
  2045. buf += QLatin1Char(' ');
  2046. buf += QString::number(d->date.year());
  2047. }
  2048. #endif
  2049. else {
  2050. buf = d->date.toString(f);
  2051. if (buf.isEmpty())
  2052. return QString(); // failed to convert
  2053. buf += QLatin1Char(' ');
  2054. buf += d->time.toString(f);
  2055. }
  2056. return buf;
  2057. }
  2058. /*!
  2059. Returns the datetime as a string. The \a format parameter
  2060. determines the format of the result string.
  2061. These expressions may be used for the date:
  2062. \table
  2063. \header \li Expression \li Output
  2064. \row \li d \li the day as number without a leading zero (1 to 31)
  2065. \row \li dd \li the day as number with a leading zero (01 to 31)
  2066. \row \li ddd
  2067. \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
  2068. Uses QDate::shortDayName().
  2069. \row \li dddd
  2070. \li the long localized day name (e.g. 'Monday' to 'Qt::Sunday').
  2071. Uses QDate::longDayName().
  2072. \row \li M \li the month as number without a leading zero (1-12)
  2073. \row \li MM \li the month as number with a leading zero (01-12)
  2074. \row \li MMM
  2075. \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
  2076. Uses QDate::shortMonthName().
  2077. \row \li MMMM
  2078. \li the long localized month name (e.g. 'January' to 'December').
  2079. Uses QDate::longMonthName().
  2080. \row \li yy \li the year as two digit number (00-99)
  2081. \row \li yyyy \li the year as four digit number
  2082. \endtable
  2083. These expressions may be used for the time:
  2084. \table
  2085. \header \li Expression \li Output
  2086. \row \li h
  2087. \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
  2088. \row \li hh
  2089. \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
  2090. \row \li m \li the minute without a leading zero (0 to 59)
  2091. \row \li mm \li the minute with a leading zero (00 to 59)
  2092. \row \li s \li the second without a leading zero (0 to 59)
  2093. \row \li ss \li the second with a leading zero (00 to 59)
  2094. \row \li z \li the milliseconds without leading zeroes (0 to 999)
  2095. \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
  2096. \row \li AP
  2097. \li use AM/PM display. \e AP will be replaced by either "AM" or "PM".
  2098. \row \li ap
  2099. \li use am/pm display. \e ap will be replaced by either "am" or "pm".
  2100. \endtable
  2101. All other input characters will be ignored. Any sequence of characters that
  2102. are enclosed in single quotes will be treated as text and not be used as an
  2103. expression. Two consecutive single quotes ("''") are replaced by a singlequote
  2104. in the output. Formats without separators (e.g. "HHmm") are currently not supported.
  2105. Example format strings (assumed that the QDateTime is 21 May 2001
  2106. 14:13:09):
  2107. \table
  2108. \header \li Format \li Result
  2109. \row \li dd.MM.yyyy \li 21.05.2001
  2110. \row \li ddd MMMM d yy \li Tue May 21 01
  2111. \row \li hh:mm:ss.zzz \li 14:13:09.042
  2112. \row \li h:m:s ap \li 2:13:9 pm
  2113. \endtable
  2114. If the datetime is invalid, an empty string will be returned.
  2115. \sa QDate::toString(), QTime::toString()
  2116. */
  2117. QString QDateTime::toString(const QString& format) const
  2118. {
  2119. return fmtDateTime(format, &d->time, &d->date);
  2120. }
  2121. #endif //QT_NO_DATESTRING
  2122. /*!
  2123. Returns a QDateTime object containing a datetime \a ndays days
  2124. later than the datetime of this object (or earlier if \a ndays is
  2125. negative).
  2126. \sa daysTo(), addMonths(), addYears(), addSecs()
  2127. */
  2128. QDateTime QDateTime::addDays(qint64 ndays) const
  2129. {
  2130. return QDateTime(d->date.addDays(ndays), d->time, timeSpec());
  2131. }
  2132. /*!
  2133. Returns a QDateTime object containing a datetime \a nmonths months
  2134. later than the datetime of this object (or earlier if \a nmonths
  2135. is negative).
  2136. \sa daysTo(), addDays(), addYears(), addSecs()
  2137. */
  2138. QDateTime QDateTime::addMonths(int nmonths) const
  2139. {
  2140. return QDateTime(d->date.addMonths(nmonths), d->time, timeSpec());
  2141. }
  2142. /*!
  2143. Returns a QDateTime object containing a datetime \a nyears years
  2144. later than the datetime of this object (or earlier if \a nyears is
  2145. negative).
  2146. \sa daysTo(), addDays(), addMonths(), addSecs()
  2147. */
  2148. QDateTime QDateTime::addYears(int nyears) const
  2149. {
  2150. return QDateTime(d->date.addYears(nyears), d->time, timeSpec());
  2151. }
  2152. QDateTime QDateTimePrivate::addMSecs(const QDateTime &dt, qint64 msecs)
  2153. {
  2154. if (!dt.isValid())
  2155. return QDateTime();
  2156. QDate utcDate;
  2157. QTime utcTime;
  2158. dt.d->getUTC(utcDate, utcTime);
  2159. addMSecs(utcDate, utcTime, msecs);
  2160. return QDateTime(utcDate, utcTime, Qt::UTC).toTimeSpec(dt.timeSpec());
  2161. }
  2162. /*!
  2163. Adds \a msecs to utcDate and \a utcTime as appropriate. It is assumed that
  2164. utcDate and utcTime are adjusted to UTC.
  2165. \since 4.5
  2166. \internal
  2167. */
  2168. void QDateTimePrivate::addMSecs(QDate &utcDate, QTime &utcTime, qint64 msecs)
  2169. {
  2170. qint64 dd = utcDate.toJulianDay();
  2171. int tt = QTime(0, 0, 0).msecsTo(utcTime);
  2172. int sign = 1;
  2173. if (msecs < 0) {
  2174. msecs = -msecs;
  2175. sign = -1;
  2176. }
  2177. if (msecs >= int(MSECS_PER_DAY)) {
  2178. dd += sign * (msecs / MSECS_PER_DAY);
  2179. msecs %= MSECS_PER_DAY;
  2180. }
  2181. tt += sign * msecs;
  2182. if (tt < 0) {
  2183. tt = MSECS_PER_DAY - tt - 1;
  2184. dd -= tt / MSECS_PER_DAY;
  2185. tt = tt % MSECS_PER_DAY;
  2186. tt = MSECS_PER_DAY - tt - 1;
  2187. } else if (tt >= int(MSECS_PER_DAY)) {
  2188. dd += tt / MSECS_PER_DAY;
  2189. tt = tt % MSECS_PER_DAY;
  2190. }
  2191. utcDate = QDate::fromJulianDay(dd);
  2192. utcTime = QTime(0, 0, 0).addMSecs(tt);
  2193. }
  2194. /*!
  2195. Returns a QDateTime object containing a datetime \a s seconds
  2196. later than the datetime of this object (or earlier if \a s is
  2197. negative).
  2198. If this datetime is invalid, an invalid datetime will be returned.
  2199. \sa addMSecs(), secsTo(), addDays(), addMonths(), addYears()
  2200. */
  2201. QDateTime QDateTime::addSecs(qint64 s) const
  2202. {
  2203. return d->addMSecs(*this, s * 1000);
  2204. }
  2205. /*!
  2206. Returns a QDateTime object containing a datetime \a msecs miliseconds
  2207. later than the datetime of this object (or earlier if \a msecs is
  2208. negative).
  2209. If this datetime is invalid, an invalid datetime will be returned.
  2210. \sa addSecs(), msecsTo(), addDays(), addMonths(), addYears()
  2211. */
  2212. QDateTime QDateTime::addMSecs(qint64 msecs) const
  2213. {
  2214. return d->addMSecs(*this, msecs);
  2215. }
  2216. /*!
  2217. Returns the number of days from this datetime to the \a other
  2218. datetime. The number of days is counted as the number of times
  2219. midnight is reached between this datetime to the \a other
  2220. datetime. This means that a 10 minute difference from 23:55 to
  2221. 0:05 the next day counts as one day.
  2222. If the \a other datetime is earlier than this datetime,
  2223. the value returned is negative.
  2224. Example:
  2225. \snippet code/src_corelib_tools_qdatetime.cpp 15
  2226. \sa addDays(), secsTo(), msecsTo()
  2227. */
  2228. qint64 QDateTime::daysTo(const QDateTime &other) const
  2229. {
  2230. return d->date.daysTo(other.d->date);
  2231. }
  2232. /*!
  2233. Returns the number of seconds from this datetime to the \a other
  2234. datetime. If the \a other datetime is earlier than this datetime,
  2235. the value returned is negative.
  2236. Before performing the comparison, the two datetimes are converted
  2237. to Qt::UTC to ensure that the result is correct if one of the two
  2238. datetimes has daylight saving time (DST) and the other doesn't.
  2239. Returns 0 if either datetime is invalid.
  2240. Example:
  2241. \snippet code/src_corelib_tools_qdatetime.cpp 11
  2242. \sa addSecs(), daysTo(), QTime::secsTo()
  2243. */
  2244. qint64 QDateTime::secsTo(const QDateTime &other) const
  2245. {
  2246. if (!isValid() || !other.isValid())
  2247. return 0;
  2248. QDate date1, date2;
  2249. QTime time1, time2;
  2250. d->getUTC(date1, time1);
  2251. other.d->getUTC(date2, time2);
  2252. return (date1.daysTo(date2) * SECS_PER_DAY) + time1.secsTo(time2);
  2253. }
  2254. /*!
  2255. Returns the number of milliseconds from this datetime to the \a other
  2256. datetime. If the \a other datetime is earlier than this datetime,
  2257. the value returned is negative.
  2258. Before performing the comparison, the two datetimes are converted
  2259. to Qt::UTC to ensure that the result is correct if one of the two
  2260. datetimes has daylight saving time (DST) and the other doesn't.
  2261. Returns 0 if either datetime is invalid.
  2262. \sa addMSecs(), daysTo(), QTime::msecsTo()
  2263. */
  2264. qint64 QDateTime::msecsTo(const QDateTime &other) const
  2265. {
  2266. if (!isValid() || !other.isValid())
  2267. return 0;
  2268. QDate selfDate;
  2269. QDate otherDate;
  2270. QTime selfTime;
  2271. QTime otherTime;
  2272. d->getUTC(selfDate, selfTime);
  2273. other.d->getUTC(otherDate, otherTime);
  2274. return (static_cast<qint64>(selfDate.daysTo(otherDate)) * static_cast<qint64>(MSECS_PER_DAY))
  2275. + static_cast<qint64>(selfTime.msecsTo(otherTime));
  2276. }
  2277. /*!
  2278. \fn QDateTime QDateTime::toTimeSpec(Qt::TimeSpec specification) const
  2279. Returns a copy of this datetime converted to the given time
  2280. \a specification.
  2281. Example:
  2282. \snippet code/src_corelib_tools_qdatetime.cpp 16
  2283. \sa timeSpec(), toUTC(), toLocalTime()
  2284. */
  2285. QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const
  2286. {
  2287. if ((d->spec == QDateTimePrivate::UTC) == (spec == Qt::UTC))
  2288. return *this;
  2289. QDateTime ret;
  2290. if (spec == Qt::UTC) {
  2291. d->getUTC(ret.d->date, ret.d->time);
  2292. ret.d->spec = QDateTimePrivate::UTC;
  2293. } else {
  2294. ret.d->spec = d->getLocal(ret.d->date, ret.d->time);
  2295. }
  2296. return ret;
  2297. }
  2298. /*!
  2299. Returns true if this datetime is equal to the \a other datetime;
  2300. otherwise returns false.
  2301. \sa operator!=()
  2302. */
  2303. bool QDateTime::operator==(const QDateTime &other) const
  2304. {
  2305. if (d->spec == other.d->spec && d->utcOffset == other.d->utcOffset)
  2306. return d->time == other.d->time && d->date == other.d->date;
  2307. else {
  2308. QDate date1, date2;
  2309. QTime time1, time2;
  2310. d->getUTC(date1, time1);
  2311. other.d->getUTC(date2, time2);
  2312. return time1 == time2 && date1 == date2;
  2313. }
  2314. }
  2315. /*!
  2316. \fn bool QDateTime::operator!=(const QDateTime &other) const
  2317. Returns true if this datetime is different from the \a other
  2318. datetime; otherwise returns false.
  2319. Two datetimes are different if either the date, the time, or the
  2320. time zone components are different.
  2321. \sa operator==()
  2322. */
  2323. /*!
  2324. Returns true if this datetime is earlier than the \a other
  2325. datetime; otherwise returns false.
  2326. */
  2327. bool QDateTime::operator<(const QDateTime &other) const
  2328. {
  2329. if (d->spec == other.d->spec && d->spec != QDateTimePrivate::OffsetFromUTC) {
  2330. if (d->date != other.d->date)
  2331. return d->date < other.d->date;
  2332. return d->time < other.d->time;
  2333. } else {
  2334. QDate date1, date2;
  2335. QTime time1, time2;
  2336. d->getUTC(date1, time1);
  2337. other.d->getUTC(date2, time2);
  2338. if (date1 != date2)
  2339. return date1 < date2;
  2340. return time1 < time2;
  2341. }
  2342. }
  2343. /*!
  2344. \fn bool QDateTime::operator<=(const QDateTime &other) const
  2345. Returns true if this datetime is earlier than or equal to the
  2346. \a other datetime; otherwise returns false.
  2347. */
  2348. /*!
  2349. \fn bool QDateTime::operator>(const QDateTime &other) const
  2350. Returns true if this datetime is later than the \a other datetime;
  2351. otherwise returns false.
  2352. */
  2353. /*!
  2354. \fn bool QDateTime::operator>=(const QDateTime &other) const
  2355. Returns true if this datetime is later than or equal to the
  2356. \a other datetime; otherwise returns false.
  2357. */
  2358. /*!
  2359. \fn QDateTime QDateTime::currentDateTime()
  2360. Returns the current datetime, as reported by the system clock, in
  2361. the local time zone.
  2362. \sa currentDateTimeUtc(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
  2363. */
  2364. /*!
  2365. \fn QDateTime QDateTime::currentDateTimeUtc()
  2366. \since 4.7
  2367. Returns the current datetime, as reported by the system clock, in
  2368. UTC.
  2369. \sa currentDateTime(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
  2370. */
  2371. /*!
  2372. \fn qint64 QDateTime::currentMSecsSinceEpoch()
  2373. \since 4.7
  2374. Returns the number of milliseconds since 1970-01-01T00:00:00 Universal
  2375. Coordinated Time. This number is like the POSIX time_t variable, but
  2376. expressed in milliseconds instead.
  2377. \sa currentDateTime(), currentDateTimeUtc(), toTime_t(), toTimeSpec()
  2378. */
  2379. static inline uint msecsFromDecomposed(int hour, int minute, int sec, int msec = 0)
  2380. {
  2381. return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute + 1000 * sec + msec;
  2382. }
  2383. #if defined(Q_OS_WIN)
  2384. QDate QDate::currentDate()
  2385. {
  2386. QDate d;
  2387. SYSTEMTIME st;
  2388. memset(&st, 0, sizeof(SYSTEMTIME));
  2389. GetLocalTime(&st);
  2390. d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
  2391. return d;
  2392. }
  2393. QTime QTime::currentTime()
  2394. {
  2395. QTime ct;
  2396. SYSTEMTIME st;
  2397. memset(&st, 0, sizeof(SYSTEMTIME));
  2398. GetLocalTime(&st);
  2399. ct.setHMS(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  2400. #if defined(Q_OS_WINCE)
  2401. ct.startTick = GetTickCount() % MSECS_PER_DAY;
  2402. #endif
  2403. return ct;
  2404. }
  2405. QDateTime QDateTime::currentDateTime()
  2406. {
  2407. QDate d;
  2408. QTime t;
  2409. SYSTEMTIME st;
  2410. memset(&st, 0, sizeof(SYSTEMTIME));
  2411. GetLocalTime(&st);
  2412. d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
  2413. t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  2414. return QDateTime(d, t);
  2415. }
  2416. QDateTime QDateTime::currentDateTimeUtc()
  2417. {
  2418. QDate d;
  2419. QTime t;
  2420. SYSTEMTIME st;
  2421. memset(&st, 0, sizeof(SYSTEMTIME));
  2422. GetSystemTime(&st);
  2423. d.jd = julianDayFromDate(st.wYear, st.wMonth, st.wDay);
  2424. t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  2425. return QDateTime(d, t, Qt::UTC);
  2426. }
  2427. qint64 QDateTime::currentMSecsSinceEpoch() Q_DECL_NOTHROW
  2428. {
  2429. QDate d;
  2430. QTime t;
  2431. SYSTEMTIME st;
  2432. memset(&st, 0, sizeof(SYSTEMTIME));
  2433. GetSystemTime(&st);
  2434. return msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds) +
  2435. qint64(julianDayFromDate(st.wYear, st.wMonth, st.wDay)
  2436. - julianDayFromDate(1970, 1, 1)) * Q_INT64_C(86400000);
  2437. }
  2438. #elif defined(Q_OS_UNIX)
  2439. QDate QDate::currentDate()
  2440. {
  2441. QDate d;
  2442. // posix compliant system
  2443. time_t ltime;
  2444. time(&ltime);
  2445. struct tm *t = 0;
  2446. #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  2447. // use the reentrant version of localtime() where available
  2448. tzset();
  2449. struct tm res;
  2450. t = localtime_r(&ltime, &res);
  2451. #else
  2452. t = localtime(&ltime);
  2453. #endif // !QT_NO_THREAD && _POSIX_THREAD_SAFE_FUNCTIONS
  2454. d.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
  2455. return d;
  2456. }
  2457. QTime QTime::currentTime()
  2458. {
  2459. QTime ct;
  2460. // posix compliant system
  2461. struct timeval tv;
  2462. gettimeofday(&tv, 0);
  2463. time_t ltime = tv.tv_sec;
  2464. struct tm *t = 0;
  2465. #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  2466. // use the reentrant version of localtime() where available
  2467. tzset();
  2468. struct tm res;
  2469. t = localtime_r(&ltime, &res);
  2470. #else
  2471. t = localtime(&ltime);
  2472. #endif
  2473. Q_CHECK_PTR(t);
  2474. ct.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
  2475. return ct;
  2476. }
  2477. QDateTime QDateTime::currentDateTime()
  2478. {
  2479. // posix compliant system
  2480. // we have milliseconds
  2481. struct timeval tv;
  2482. gettimeofday(&tv, 0);
  2483. time_t ltime = tv.tv_sec;
  2484. struct tm *t = 0;
  2485. #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  2486. // use the reentrant version of localtime() where available
  2487. tzset();
  2488. struct tm res;
  2489. t = localtime_r(&ltime, &res);
  2490. #else
  2491. t = localtime(&ltime);
  2492. #endif
  2493. QDateTime dt;
  2494. dt.d->time.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
  2495. dt.d->date.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
  2496. dt.d->spec = t->tm_isdst > 0 ? QDateTimePrivate::LocalDST :
  2497. t->tm_isdst == 0 ? QDateTimePrivate::LocalStandard :
  2498. QDateTimePrivate::LocalUnknown;
  2499. return dt;
  2500. }
  2501. QDateTime QDateTime::currentDateTimeUtc()
  2502. {
  2503. // posix compliant system
  2504. // we have milliseconds
  2505. struct timeval tv;
  2506. gettimeofday(&tv, 0);
  2507. time_t ltime = tv.tv_sec;
  2508. struct tm *t = 0;
  2509. #if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  2510. // use the reentrant version of localtime() where available
  2511. struct tm res;
  2512. t = gmtime_r(&ltime, &res);
  2513. #else
  2514. t = gmtime(&ltime);
  2515. #endif
  2516. QDateTime dt;
  2517. dt.d->time.mds = msecsFromDecomposed(t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000);
  2518. dt.d->date.jd = julianDayFromDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
  2519. dt.d->spec = QDateTimePrivate::UTC;
  2520. return dt;
  2521. }
  2522. qint64 QDateTime::currentMSecsSinceEpoch() Q_DECL_NOTHROW
  2523. {
  2524. // posix compliant system
  2525. // we have milliseconds
  2526. struct timeval tv;
  2527. gettimeofday(&tv, 0);
  2528. return qint64(tv.tv_sec) * Q_INT64_C(1000) + tv.tv_usec / 1000;
  2529. }
  2530. #else
  2531. #error "What system is this?"
  2532. #endif
  2533. /*!
  2534. \since 4.2
  2535. Returns a datetime whose date and time are the number of \a seconds
  2536. that have passed since 1970-01-01T00:00:00, Coordinated Universal
  2537. Time (Qt::UTC). On systems that do not support time zones, the time
  2538. will be set as if local time were Qt::UTC.
  2539. \sa toTime_t(), setTime_t()
  2540. */
  2541. QDateTime QDateTime::fromTime_t(uint seconds)
  2542. {
  2543. QDateTime d;
  2544. d.setTime_t(seconds);
  2545. return d;
  2546. }
  2547. /*!
  2548. \since 4.7
  2549. Returns a datetime whose date and time are the number of milliseconds, \a msecs,
  2550. that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
  2551. Time (Qt::UTC). On systems that do not support time zones, the time
  2552. will be set as if local time were Qt::UTC.
  2553. Note that there are possible values for \a msecs that lie outside the valid
  2554. range of QDateTime, both negative and positive. The behavior of this
  2555. function is undefined for those values.
  2556. \sa toTime_t(), setTime_t()
  2557. */
  2558. QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs)
  2559. {
  2560. QDateTime d;
  2561. d.setMSecsSinceEpoch(msecs);
  2562. return d;
  2563. }
  2564. /*!
  2565. \since 4.4
  2566. \internal
  2567. Sets the offset from UTC to \a seconds, and also sets timeSpec() to
  2568. Qt::OffsetFromUTC.
  2569. The maximum and minimum offset is 14 positive or negative hours. If
  2570. \a seconds is larger or smaller than that, the result is undefined.
  2571. 0 as offset is identical to UTC. Therefore, if \a seconds is 0, the
  2572. timeSpec() will be set to Qt::UTC. Hence the UTC offset always
  2573. relates to UTC, and can never relate to local time.
  2574. \sa isValid(), utcOffset()
  2575. */
  2576. void QDateTime::setUtcOffset(int seconds)
  2577. {
  2578. detach();
  2579. /* The motivation to also setting d->spec is to ensure that the QDateTime
  2580. * instance stays in well-defined states all the time; instead of that,
  2581. * we instruct the user to ensure it. */
  2582. if(seconds == 0)
  2583. d->spec = QDateTimePrivate::UTC;
  2584. else
  2585. d->spec = QDateTimePrivate::OffsetFromUTC;
  2586. /* Even if seconds is 0 we assign it to utcOffset. */
  2587. d->utcOffset = seconds;
  2588. }
  2589. /*!
  2590. \since 4.4
  2591. \internal
  2592. Returns the UTC offset in seconds. If the timeSpec() isn't
  2593. Qt::OffsetFromUTC, 0 is returned. However, since 0 is a valid UTC
  2594. offset, the return value of this function cannot be used to determine
  2595. whether a utcOffset() is used or is valid; in that case, timeSpec() must be
  2596. checked.
  2597. Likewise, if this QDateTime() is invalid or if timeSpec() isn't
  2598. Qt::OffsetFromUTC, 0 is returned.
  2599. The UTC offset only applies if the timeSpec() is Qt::OffsetFromUTC.
  2600. \sa isValid(), setUtcOffset()
  2601. */
  2602. int QDateTime::utcOffset() const
  2603. {
  2604. if(isValid() && d->spec == QDateTimePrivate::OffsetFromUTC)
  2605. return d->utcOffset;
  2606. else
  2607. return 0;
  2608. }
  2609. #ifndef QT_NO_DATESTRING
  2610. static int fromShortMonthName(const QString &monthName)
  2611. {
  2612. // Assume that English monthnames are the default
  2613. for (int i = 0; i < 12; ++i) {
  2614. if (monthName == QLatin1String(qt_shortMonthNames[i]))
  2615. return i + 1;
  2616. }
  2617. // If English names can't be found, search the localized ones
  2618. for (int i = 1; i <= 12; ++i) {
  2619. if (monthName == QDate::shortMonthName(i))
  2620. return i;
  2621. }
  2622. return -1;
  2623. }
  2624. /*!
  2625. \fn QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
  2626. Returns the QDateTime represented by the \a string, using the
  2627. \a format given, or an invalid datetime if this is not possible.
  2628. Note for Qt::TextDate: It is recommended that you use the
  2629. English short month names (e.g. "Jan"). Although localized month
  2630. names can also be used, they depend on the user's locale settings.
  2631. */
  2632. QDateTime QDateTime::fromString(const QString& s, Qt::DateFormat f)
  2633. {
  2634. if (s.isEmpty()) {
  2635. return QDateTime();
  2636. }
  2637. switch (f) {
  2638. case Qt::ISODate: {
  2639. QString tmp = s;
  2640. Qt::TimeSpec ts = Qt::LocalTime;
  2641. QDate date = QDate::fromString(tmp.left(10), Qt::ISODate);
  2642. if (tmp.size() == 10)
  2643. return QDateTime(date);
  2644. tmp = tmp.mid(11);
  2645. // Recognize UTC specifications
  2646. if (tmp.endsWith(QLatin1Char('Z'))) {
  2647. ts = Qt::UTC;
  2648. tmp.chop(1);
  2649. }
  2650. // Recognize timezone specifications
  2651. QRegExp rx(QLatin1String("[+-]"));
  2652. if (tmp.contains(rx)) {
  2653. int idx = tmp.indexOf(rx);
  2654. QString tmp2 = tmp.mid(idx);
  2655. tmp = tmp.left(idx);
  2656. bool ok = true;
  2657. int ntzhour = 1;
  2658. int ntzminute = 3;
  2659. if ( tmp2.indexOf(QLatin1Char(':')) == 3 )
  2660. ntzminute = 4;
  2661. const int tzhour(tmp2.mid(ntzhour, 2).toInt(&ok));
  2662. const int tzminute(tmp2.mid(ntzminute, 2).toInt(&ok));
  2663. QTime tzt(tzhour, tzminute);
  2664. int utcOffset = (tzt.hour() * 60 + tzt.minute()) * 60;
  2665. if ( utcOffset != 0 ) {
  2666. ts = Qt::OffsetFromUTC;
  2667. QDateTime dt(date, QTime::fromString(tmp, Qt::ISODate), ts);
  2668. dt.setUtcOffset( utcOffset * (tmp2.startsWith(QLatin1Char('-')) ? -1 : 1) );
  2669. return dt;
  2670. }
  2671. }
  2672. bool isMidnight24 = false;
  2673. // Might be end of day (24:00, including variants), which QTime considers invalid.
  2674. QTime time(fromStringImpl(tmp, Qt::ISODate, isMidnight24));
  2675. if (isMidnight24) {
  2676. // ISO 8601 (section 4.2.3) says that 24:00 is equivalent to 00:00 the next day.
  2677. date = date.addDays(1);
  2678. }
  2679. return QDateTime(date, time, ts);
  2680. }
  2681. case Qt::SystemLocaleDate:
  2682. case Qt::SystemLocaleShortDate:
  2683. case Qt::SystemLocaleLongDate:
  2684. return fromString(s, QLocale::system().dateTimeFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  2685. : QLocale::ShortFormat));
  2686. case Qt::LocaleDate:
  2687. case Qt::DefaultLocaleShortDate:
  2688. case Qt::DefaultLocaleLongDate:
  2689. return fromString(s, QLocale().dateTimeFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  2690. : QLocale::ShortFormat));
  2691. #if !defined(QT_NO_TEXTDATE)
  2692. case Qt::TextDate: {
  2693. QStringList parts = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
  2694. if ((parts.count() < 5) || (parts.count() > 6)) {
  2695. return QDateTime();
  2696. }
  2697. // Accept "Sun Dec 1 13:02:00 1974" and "Sun 1. Dec 13:02:00 1974"
  2698. int month = -1, day = -1;
  2699. bool ok;
  2700. month = fromShortMonthName(parts.at(1));
  2701. if (month != -1) {
  2702. day = parts.at(2).toInt(&ok);
  2703. if (!ok)
  2704. day = -1;
  2705. }
  2706. if (month == -1 || day == -1) {
  2707. // first variant failed, lets try the other
  2708. month = fromShortMonthName(parts.at(2));
  2709. if (month != -1) {
  2710. QString dayStr = parts.at(1);
  2711. if (dayStr.endsWith(QLatin1Char('.'))) {
  2712. dayStr.chop(1);
  2713. day = dayStr.toInt(&ok);
  2714. if (!ok)
  2715. day = -1;
  2716. } else {
  2717. day = -1;
  2718. }
  2719. }
  2720. }
  2721. if (month == -1 || day == -1) {
  2722. // both variants failed, give up
  2723. return QDateTime();
  2724. }
  2725. int year;
  2726. QStringList timeParts = parts.at(3).split(QLatin1Char(':'));
  2727. if ((timeParts.count() == 3) || (timeParts.count() == 2)) {
  2728. // Year is after time, e.g. "Sun Dec 1 13:02:00 1974"
  2729. year = parts.at(4).toInt(&ok);
  2730. if (!ok)
  2731. return QDateTime();
  2732. } else { // Year is before time, e.g. "Sun Dec 1 1974 13:02:00"
  2733. timeParts = parts.at(4).split(QLatin1Char(':'));
  2734. if ((timeParts.count() != 3) && (timeParts.count() != 2))
  2735. return QDateTime();
  2736. year = parts.at(3).toInt(&ok);
  2737. if (!ok)
  2738. return QDateTime();
  2739. }
  2740. int hour = timeParts.at(0).toInt(&ok);
  2741. if (!ok) {
  2742. return QDateTime();
  2743. }
  2744. int minute = timeParts.at(1).toInt(&ok);
  2745. if (!ok) {
  2746. return QDateTime();
  2747. }
  2748. int second = (timeParts.count() > 2) ? timeParts.at(2).toInt(&ok) : 0;
  2749. if (!ok) {
  2750. return QDateTime();
  2751. }
  2752. QDate date(year, month, day);
  2753. QTime time(hour, minute, second);
  2754. if (parts.count() == 5)
  2755. return QDateTime(date, time, Qt::LocalTime);
  2756. QString tz = parts.at(5);
  2757. if (!tz.startsWith(QLatin1String("GMT"), Qt::CaseInsensitive))
  2758. return QDateTime();
  2759. QDateTime dt(date, time, Qt::UTC);
  2760. if (tz.length() > 3) {
  2761. int tzoffset = 0;
  2762. QChar sign = tz.at(3);
  2763. if ((sign != QLatin1Char('+'))
  2764. && (sign != QLatin1Char('-'))) {
  2765. return QDateTime();
  2766. }
  2767. int tzhour = tz.mid(4, 2).toInt(&ok);
  2768. if (!ok)
  2769. return QDateTime();
  2770. int tzminute = tz.mid(6).toInt(&ok);
  2771. if (!ok)
  2772. return QDateTime();
  2773. tzoffset = (tzhour*60 + tzminute) * 60;
  2774. if (sign == QLatin1Char('-'))
  2775. tzoffset = -tzoffset;
  2776. dt.setUtcOffset(tzoffset);
  2777. }
  2778. return dt.toLocalTime();
  2779. }
  2780. #endif //QT_NO_TEXTDATE
  2781. }
  2782. return QDateTime();
  2783. }
  2784. /*!
  2785. \fn QDateTime::fromString(const QString &string, const QString &format)
  2786. Returns the QDateTime represented by the \a string, using the \a
  2787. format given, or an invalid datetime if the string cannot be parsed.
  2788. These expressions may be used for the date part of the format string:
  2789. \table
  2790. \header \li Expression \li Output
  2791. \row \li d \li the day as number without a leading zero (1 to 31)
  2792. \row \li dd \li the day as number with a leading zero (01 to 31)
  2793. \row \li ddd
  2794. \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
  2795. Uses QDate::shortDayName().
  2796. \row \li dddd
  2797. \li the long localized day name (e.g. 'Monday' to 'Sunday').
  2798. Uses QDate::longDayName().
  2799. \row \li M \li the month as number without a leading zero (1-12)
  2800. \row \li MM \li the month as number with a leading zero (01-12)
  2801. \row \li MMM
  2802. \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
  2803. Uses QDate::shortMonthName().
  2804. \row \li MMMM
  2805. \li the long localized month name (e.g. 'January' to 'December').
  2806. Uses QDate::longMonthName().
  2807. \row \li yy \li the year as two digit number (00-99)
  2808. \row \li yyyy \li the year as four digit number
  2809. \endtable
  2810. \note Unlike the other version of this function, day and month names must
  2811. be given in the user's local language. It is only possible to use the English
  2812. names if the user's language is English.
  2813. These expressions may be used for the time part of the format string:
  2814. \table
  2815. \header \li Expression \li Output
  2816. \row \li h
  2817. \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
  2818. \row \li hh
  2819. \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
  2820. \row \li H
  2821. \li the hour without a leading zero (0 to 23, even with AM/PM display)
  2822. \row \li HH
  2823. \li the hour with a leading zero (00 to 23, even with AM/PM display)
  2824. \row \li m \li the minute without a leading zero (0 to 59)
  2825. \row \li mm \li the minute with a leading zero (00 to 59)
  2826. \row \li s \li the second without a leading zero (0 to 59)
  2827. \row \li ss \li the second with a leading zero (00 to 59)
  2828. \row \li z \li the milliseconds without leading zeroes (0 to 999)
  2829. \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
  2830. \row \li AP or A
  2831. \li interpret as an AM/PM time. \e AP must be either "AM" or "PM".
  2832. \row \li ap or a
  2833. \li Interpret as an AM/PM time. \e ap must be either "am" or "pm".
  2834. \endtable
  2835. All other input characters will be treated as text. Any sequence
  2836. of characters that are enclosed in single quotes will also be
  2837. treated as text and not be used as an expression.
  2838. \snippet code/src_corelib_tools_qdatetime.cpp 12
  2839. If the format is not satisfied, an invalid QDateTime is returned.
  2840. The expressions that don't have leading zeroes (d, M, h, m, s, z) will be
  2841. greedy. This means that they will use two digits even if this will
  2842. put them outside the range and/or leave too few digits for other
  2843. sections.
  2844. \snippet code/src_corelib_tools_qdatetime.cpp 13
  2845. This could have meant 1 January 00:30.00 but the M will grab
  2846. two digits.
  2847. For any field that is not represented in the format, the following
  2848. defaults are used:
  2849. \table
  2850. \header \li Field \li Default value
  2851. \row \li Year \li 1900
  2852. \row \li Month \li 1 (January)
  2853. \row \li Day \li 1
  2854. \row \li Hour \li 0
  2855. \row \li Minute \li 0
  2856. \row \li Second \li 0
  2857. \endtable
  2858. For example:
  2859. \snippet code/src_corelib_tools_qdatetime.cpp 14
  2860. \sa QDate::fromString(), QTime::fromString(), QDate::toString(),
  2861. QDateTime::toString(), QTime::toString()
  2862. */
  2863. QDateTime QDateTime::fromString(const QString &string, const QString &format)
  2864. {
  2865. #ifndef QT_BOOTSTRAPPED
  2866. QTime time;
  2867. QDate date;
  2868. QDateTimeParser dt(QVariant::DateTime, QDateTimeParser::FromString);
  2869. if (dt.parseFormat(format) && dt.fromString(string, &date, &time))
  2870. return QDateTime(date, time);
  2871. #else
  2872. Q_UNUSED(string);
  2873. Q_UNUSED(format);
  2874. #endif
  2875. return QDateTime(QDate(), QTime(-1, -1, -1));
  2876. }
  2877. #endif // QT_NO_DATESTRING
  2878. /*!
  2879. \fn QDateTime QDateTime::toLocalTime() const
  2880. Returns a datetime containing the date and time information in
  2881. this datetime, but specified using the Qt::LocalTime definition.
  2882. Example:
  2883. \snippet code/src_corelib_tools_qdatetime.cpp 17
  2884. \sa toTimeSpec()
  2885. */
  2886. /*!
  2887. \fn QDateTime QDateTime::toUTC() const
  2888. Returns a datetime containing the date and time information in
  2889. this datetime, but specified using the Qt::UTC definition.
  2890. Example:
  2891. \snippet code/src_corelib_tools_qdatetime.cpp 18
  2892. \sa toTimeSpec()
  2893. */
  2894. /*!
  2895. \internal
  2896. */
  2897. void QDateTime::detach()
  2898. {
  2899. d.detach();
  2900. }
  2901. /*****************************************************************************
  2902. Date/time stream functions
  2903. *****************************************************************************/
  2904. #ifndef QT_NO_DATASTREAM
  2905. /*!
  2906. \relates QDate
  2907. Writes the \a date to stream \a out.
  2908. \sa {Serializing Qt Data Types}
  2909. */
  2910. QDataStream &operator<<(QDataStream &out, const QDate &date)
  2911. {
  2912. if (out.version() < QDataStream::Qt_5_0)
  2913. return out << quint32(date.jd);
  2914. else
  2915. return out << qint64(date.jd);
  2916. }
  2917. /*!
  2918. \relates QDate
  2919. Reads a date from stream \a in into the \a date.
  2920. \sa {Serializing Qt Data Types}
  2921. */
  2922. QDataStream &operator>>(QDataStream &in, QDate &date)
  2923. {
  2924. if (in.version() < QDataStream::Qt_5_0) {
  2925. quint32 jd;
  2926. in >> jd;
  2927. // Older versions consider 0 an invalid jd.
  2928. date.jd = (jd != 0 ? jd : QDate::nullJd());
  2929. } else {
  2930. qint64 jd;
  2931. in >> jd;
  2932. date.jd = jd;
  2933. }
  2934. return in;
  2935. }
  2936. /*!
  2937. \relates QTime
  2938. Writes \a time to stream \a out.
  2939. \sa {Serializing Qt Data Types}
  2940. */
  2941. QDataStream &operator<<(QDataStream &out, const QTime &time)
  2942. {
  2943. return out << quint32(time.mds);
  2944. }
  2945. /*!
  2946. \relates QTime
  2947. Reads a time from stream \a in into the given \a time.
  2948. \sa {Serializing Qt Data Types}
  2949. */
  2950. QDataStream &operator>>(QDataStream &in, QTime &time)
  2951. {
  2952. quint32 ds;
  2953. in >> ds;
  2954. time.mds = int(ds);
  2955. return in;
  2956. }
  2957. /*!
  2958. \relates QDateTime
  2959. Writes \a dateTime to the \a out stream.
  2960. \sa {Serializing Qt Data Types}
  2961. */
  2962. QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
  2963. {
  2964. if (out.version() >= 13) {
  2965. if (dateTime.isValid()) {
  2966. QDateTime asUTC = dateTime.toUTC();
  2967. out << asUTC.d->date << asUTC.d->time;
  2968. } else {
  2969. out << dateTime.d->date << dateTime.d->time;
  2970. }
  2971. out << (qint8)dateTime.timeSpec();
  2972. } else {
  2973. out << dateTime.d->date << dateTime.d->time;
  2974. if (out.version() >= 7)
  2975. out << (qint8)dateTime.d->spec;
  2976. }
  2977. return out;
  2978. }
  2979. /*!
  2980. \relates QDateTime
  2981. Reads a datetime from the stream \a in into \a dateTime.
  2982. \sa {Serializing Qt Data Types}
  2983. */
  2984. QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
  2985. {
  2986. dateTime.detach();
  2987. in >> dateTime.d->date >> dateTime.d->time;
  2988. if (in.version() >= 13) {
  2989. qint8 ts = 0;
  2990. in >> ts;
  2991. if (dateTime.isValid()) {
  2992. // We always store the datetime as UTC in 13 onwards.
  2993. dateTime.d->spec = QDateTimePrivate::UTC;
  2994. dateTime = dateTime.toTimeSpec(static_cast<Qt::TimeSpec>(ts));
  2995. }
  2996. } else {
  2997. qint8 ts = (qint8)QDateTimePrivate::LocalUnknown;
  2998. if (in.version() >= 7)
  2999. in >> ts;
  3000. dateTime.d->spec = (QDateTimePrivate::Spec)ts;
  3001. }
  3002. return in;
  3003. }
  3004. #endif // QT_NO_DATASTREAM
  3005. // checks if there is an unquoted 'AP' or 'ap' in the string
  3006. static bool hasUnquotedAP(const QString &f)
  3007. {
  3008. const QLatin1Char quote('\'');
  3009. bool inquote = false;
  3010. const int max = f.size();
  3011. for (int i=0; i<max; ++i) {
  3012. if (f.at(i) == quote) {
  3013. inquote = !inquote;
  3014. } else if (!inquote && f.at(i).toUpper() == QLatin1Char('A')
  3015. && i + 1 < max && f.at(i + 1).toUpper() == QLatin1Char('P')) {
  3016. return true;
  3017. }
  3018. }
  3019. return false;
  3020. }
  3021. #ifndef QT_NO_DATESTRING
  3022. /*****************************************************************************
  3023. Some static function used by QDate, QTime and QDateTime
  3024. *****************************************************************************/
  3025. // Replaces tokens by their value. See QDateTime::toString() for a list of valid tokens
  3026. static QString getFmtString(const QString& f, const QTime* dt = 0, const QDate* dd = 0, bool am_pm = false)
  3027. {
  3028. if (f.isEmpty())
  3029. return QString();
  3030. QString buf = f;
  3031. int removed = 0;
  3032. if (dt) {
  3033. if (f.startsWith(QLatin1String("hh")) || f.startsWith(QLatin1String("HH"))) {
  3034. const bool hour12 = f.at(0) == QLatin1Char('h') && am_pm;
  3035. if (hour12 && dt->hour() > 12)
  3036. buf = QString::number(dt->hour() - 12).rightJustified(2, QLatin1Char('0'), true);
  3037. else if (hour12 && dt->hour() == 0)
  3038. buf = QLatin1String("12");
  3039. else
  3040. buf = QString::number(dt->hour()).rightJustified(2, QLatin1Char('0'), true);
  3041. removed = 2;
  3042. } else if (f.at(0) == QLatin1Char('h') || f.at(0) == QLatin1Char('H')) {
  3043. const bool hour12 = f.at(0) == QLatin1Char('h') && am_pm;
  3044. if (hour12 && dt->hour() > 12)
  3045. buf = QString::number(dt->hour() - 12);
  3046. else if (hour12 && dt->hour() == 0)
  3047. buf = QLatin1String("12");
  3048. else
  3049. buf = QString::number(dt->hour());
  3050. removed = 1;
  3051. } else if (f.startsWith(QLatin1String("mm"))) {
  3052. buf = QString::number(dt->minute()).rightJustified(2, QLatin1Char('0'), true);
  3053. removed = 2;
  3054. } else if (f.at(0) == (QLatin1Char('m'))) {
  3055. buf = QString::number(dt->minute());
  3056. removed = 1;
  3057. } else if (f.startsWith(QLatin1String("ss"))) {
  3058. buf = QString::number(dt->second()).rightJustified(2, QLatin1Char('0'), true);
  3059. removed = 2;
  3060. } else if (f.at(0) == QLatin1Char('s')) {
  3061. buf = QString::number(dt->second());
  3062. } else if (f.startsWith(QLatin1String("zzz"))) {
  3063. buf = QString::number(dt->msec()).rightJustified(3, QLatin1Char('0'), true);
  3064. removed = 3;
  3065. } else if (f.at(0) == QLatin1Char('z')) {
  3066. buf = QString::number(dt->msec());
  3067. removed = 1;
  3068. } else if (f.at(0).toUpper() == QLatin1Char('A')) {
  3069. const bool upper = f.at(0) == QLatin1Char('A');
  3070. buf = dt->hour() < 12 ? QLatin1String("am") : QLatin1String("pm");
  3071. if (upper)
  3072. buf = buf.toUpper();
  3073. if (f.size() > 1 && f.at(1).toUpper() == QLatin1Char('P') &&
  3074. f.at(0).isUpper() == f.at(1).isUpper()) {
  3075. removed = 2;
  3076. } else {
  3077. removed = 1;
  3078. }
  3079. }
  3080. }
  3081. if (dd) {
  3082. if (f.startsWith(QLatin1String("dddd"))) {
  3083. buf = dd->longDayName(dd->dayOfWeek());
  3084. removed = 4;
  3085. } else if (f.startsWith(QLatin1String("ddd"))) {
  3086. buf = dd->shortDayName(dd->dayOfWeek());
  3087. removed = 3;
  3088. } else if (f.startsWith(QLatin1String("dd"))) {
  3089. buf = QString::number(dd->day()).rightJustified(2, QLatin1Char('0'), true);
  3090. removed = 2;
  3091. } else if (f.at(0) == QLatin1Char('d')) {
  3092. buf = QString::number(dd->day());
  3093. removed = 1;
  3094. } else if (f.startsWith(QLatin1String("MMMM"))) {
  3095. buf = dd->longMonthName(dd->month());
  3096. removed = 4;
  3097. } else if (f.startsWith(QLatin1String("MMM"))) {
  3098. buf = dd->shortMonthName(dd->month());
  3099. removed = 3;
  3100. } else if (f.startsWith(QLatin1String("MM"))) {
  3101. buf = QString::number(dd->month()).rightJustified(2, QLatin1Char('0'), true);
  3102. removed = 2;
  3103. } else if (f.at(0) == QLatin1Char('M')) {
  3104. buf = QString::number(dd->month());
  3105. removed = 1;
  3106. } else if (f.startsWith(QLatin1String("yyyy"))) {
  3107. const int year = dd->year();
  3108. buf = QString::number(qAbs(year)).rightJustified(4, QLatin1Char('0'));
  3109. if(year > 0)
  3110. removed = 4;
  3111. else
  3112. {
  3113. buf.prepend(QLatin1Char('-'));
  3114. removed = 5;
  3115. }
  3116. } else if (f.startsWith(QLatin1String("yy"))) {
  3117. buf = QString::number(dd->year()).right(2).rightJustified(2, QLatin1Char('0'));
  3118. removed = 2;
  3119. }
  3120. }
  3121. if (removed == 0 || removed >= f.size()) {
  3122. return buf;
  3123. }
  3124. return buf + getFmtString(f.mid(removed), dt, dd, am_pm);
  3125. }
  3126. // Parses the format string and uses getFmtString to get the values for the tokens. Ret
  3127. static QString fmtDateTime(const QString& f, const QTime* dt, const QDate* dd)
  3128. {
  3129. QString buf;
  3130. if (f.isEmpty())
  3131. return buf;
  3132. if (dt && !dt->isValid())
  3133. return buf;
  3134. if (dd && !dd->isValid())
  3135. return buf;
  3136. const bool ap = hasUnquotedAP(f);
  3137. QString frm;
  3138. uint status = '0';
  3139. for (int i = 0, n = f.length(); i < n; ++i) {
  3140. const QChar c = f.at(i);
  3141. const uint cc = c.unicode();
  3142. if (cc == '\'') {
  3143. if (status == cc) {
  3144. if (i > 0 && f.at(i - 1).unicode() == cc)
  3145. buf += c;
  3146. status = '0';
  3147. } else {
  3148. if (!frm.isEmpty()) {
  3149. buf += getFmtString(frm, dt, dd, ap);
  3150. frm.clear();
  3151. }
  3152. status = cc;
  3153. }
  3154. } else if (status == '\'') {
  3155. buf += c;
  3156. } else if (c == status) {
  3157. if (ap && (cc == 'P' || cc == 'p'))
  3158. status = '0';
  3159. frm += c;
  3160. } else {
  3161. buf += getFmtString(frm, dt, dd, ap);
  3162. frm.clear();
  3163. if (cc == 'h' || cc == 'm' || cc == 'H' || cc == 's' || cc == 'z') {
  3164. status = cc;
  3165. frm += c;
  3166. } else if (cc == 'd' || cc == 'M' || cc == 'y') {
  3167. status = cc;
  3168. frm += c;
  3169. } else if (ap && cc == 'A') {
  3170. status = 'P';
  3171. frm += c;
  3172. } else if (ap && cc == 'a') {
  3173. status = 'p';
  3174. frm += c;
  3175. } else {
  3176. buf += c;
  3177. status = '0';
  3178. }
  3179. }
  3180. }
  3181. buf += getFmtString(frm, dt, dd, ap);
  3182. return buf;
  3183. }
  3184. #endif // QT_NO_DATESTRING
  3185. #ifdef Q_OS_WIN
  3186. static const int LowerYear = 1980;
  3187. #else
  3188. static const int LowerYear = 1970;
  3189. #endif
  3190. static const int UpperYear = 2037;
  3191. static QDate adjustDate(QDate date)
  3192. {
  3193. QDate lowerLimit(LowerYear, 1, 2);
  3194. QDate upperLimit(UpperYear, 12, 30);
  3195. if (date > lowerLimit && date < upperLimit)
  3196. return date;
  3197. int month = date.month();
  3198. int day = date.day();
  3199. // neither 1970 nor 2037 are leap years, so make sure date isn't Feb 29
  3200. if (month == 2 && day == 29)
  3201. --day;
  3202. if (date < lowerLimit)
  3203. date.setDate(LowerYear, month, day);
  3204. else
  3205. date.setDate(UpperYear, month, day);
  3206. return date;
  3207. }
  3208. static QDateTimePrivate::Spec utcToLocal(QDate &date, QTime &time)
  3209. {
  3210. QDate fakeDate = adjustDate(date);
  3211. // won't overflow because of fakeDate
  3212. time_t secsSince1Jan1970UTC = toMSecsSinceEpoch_helper(fakeDate.toJulianDay(), QTime(0, 0, 0).msecsTo(time)) / 1000;
  3213. tm *brokenDown = 0;
  3214. #if defined(Q_OS_WINCE)
  3215. tm res;
  3216. FILETIME utcTime = time_tToFt(secsSince1Jan1970UTC);
  3217. FILETIME resultTime;
  3218. FileTimeToLocalFileTime(&utcTime , &resultTime);
  3219. SYSTEMTIME sysTime;
  3220. FileTimeToSystemTime(&resultTime , &sysTime);
  3221. res.tm_sec = sysTime.wSecond;
  3222. res.tm_min = sysTime.wMinute;
  3223. res.tm_hour = sysTime.wHour;
  3224. res.tm_mday = sysTime.wDay;
  3225. res.tm_mon = sysTime.wMonth - 1;
  3226. res.tm_year = sysTime.wYear - 1900;
  3227. brokenDown = &res;
  3228. #elif !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  3229. // use the reentrant version of localtime() where available
  3230. tzset();
  3231. tm res;
  3232. brokenDown = localtime_r(&secsSince1Jan1970UTC, &res);
  3233. #elif defined(_MSC_VER) && _MSC_VER >= 1400
  3234. tm res;
  3235. if (!_localtime64_s(&res, &secsSince1Jan1970UTC))
  3236. brokenDown = &res;
  3237. #else
  3238. brokenDown = localtime(&secsSince1Jan1970UTC);
  3239. #endif
  3240. if (!brokenDown) {
  3241. date = QDate(1970, 1, 1);
  3242. time = QTime();
  3243. return QDateTimePrivate::LocalUnknown;
  3244. } else {
  3245. int deltaDays = fakeDate.daysTo(date);
  3246. date = QDate(brokenDown->tm_year + 1900, brokenDown->tm_mon + 1, brokenDown->tm_mday);
  3247. time = QTime(brokenDown->tm_hour, brokenDown->tm_min, brokenDown->tm_sec, time.msec());
  3248. date = date.addDays(deltaDays);
  3249. if (brokenDown->tm_isdst > 0)
  3250. return QDateTimePrivate::LocalDST;
  3251. else if (brokenDown->tm_isdst < 0)
  3252. return QDateTimePrivate::LocalUnknown;
  3253. else
  3254. return QDateTimePrivate::LocalStandard;
  3255. }
  3256. }
  3257. static void localToUtc(QDate &date, QTime &time, int isdst)
  3258. {
  3259. if (!date.isValid())
  3260. return;
  3261. QDate fakeDate = adjustDate(date);
  3262. tm localTM;
  3263. localTM.tm_sec = time.second();
  3264. localTM.tm_min = time.minute();
  3265. localTM.tm_hour = time.hour();
  3266. localTM.tm_mday = fakeDate.day();
  3267. localTM.tm_mon = fakeDate.month() - 1;
  3268. localTM.tm_year = fakeDate.year() - 1900;
  3269. localTM.tm_isdst = (int)isdst;
  3270. #if defined(Q_OS_WINCE)
  3271. time_t secsSince1Jan1970UTC = (toMSecsSinceEpoch_helper(fakeDate.toJulianDay(), QTime().msecsTo(time)) / 1000);
  3272. #else
  3273. #if defined(Q_OS_WIN)
  3274. _tzset();
  3275. #endif
  3276. time_t secsSince1Jan1970UTC = mktime(&localTM);
  3277. #endif
  3278. tm *brokenDown = 0;
  3279. #if defined(Q_OS_WINCE)
  3280. tm res;
  3281. FILETIME localTime = time_tToFt(secsSince1Jan1970UTC);
  3282. SYSTEMTIME sysTime;
  3283. FileTimeToSystemTime(&localTime, &sysTime);
  3284. FILETIME resultTime;
  3285. LocalFileTimeToFileTime(&localTime , &resultTime);
  3286. FileTimeToSystemTime(&resultTime , &sysTime);
  3287. res.tm_sec = sysTime.wSecond;
  3288. res.tm_min = sysTime.wMinute;
  3289. res.tm_hour = sysTime.wHour;
  3290. res.tm_mday = sysTime.wDay;
  3291. res.tm_mon = sysTime.wMonth - 1;
  3292. res.tm_year = sysTime.wYear - 1900;
  3293. res.tm_isdst = (int)isdst;
  3294. brokenDown = &res;
  3295. #elif !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
  3296. // use the reentrant version of gmtime() where available
  3297. tm res;
  3298. brokenDown = gmtime_r(&secsSince1Jan1970UTC, &res);
  3299. #elif defined(_MSC_VER) && _MSC_VER >= 1400
  3300. tm res;
  3301. if (!_gmtime64_s(&res, &secsSince1Jan1970UTC))
  3302. brokenDown = &res;
  3303. #else
  3304. brokenDown = gmtime(&secsSince1Jan1970UTC);
  3305. #endif // !QT_NO_THREAD && _POSIX_THREAD_SAFE_FUNCTIONS
  3306. if (!brokenDown) {
  3307. date = QDate(1970, 1, 1);
  3308. time = QTime();
  3309. } else {
  3310. int deltaDays = fakeDate.daysTo(date);
  3311. date = QDate(brokenDown->tm_year + 1900, brokenDown->tm_mon + 1, brokenDown->tm_mday);
  3312. time = QTime(brokenDown->tm_hour, brokenDown->tm_min, brokenDown->tm_sec, time.msec());
  3313. date = date.addDays(deltaDays);
  3314. }
  3315. }
  3316. QDateTimePrivate::Spec QDateTimePrivate::getLocal(QDate &outDate, QTime &outTime) const
  3317. {
  3318. outDate = date;
  3319. outTime = time;
  3320. if (spec == QDateTimePrivate::UTC)
  3321. return utcToLocal(outDate, outTime);
  3322. return spec;
  3323. }
  3324. void QDateTimePrivate::getUTC(QDate &outDate, QTime &outTime) const
  3325. {
  3326. outDate = date;
  3327. outTime = time;
  3328. const bool isOffset = spec == QDateTimePrivate::OffsetFromUTC;
  3329. if (spec != QDateTimePrivate::UTC && !isOffset)
  3330. localToUtc(outDate, outTime, (int)spec);
  3331. if (isOffset)
  3332. addMSecs(outDate, outTime, -(qint64(utcOffset) * 1000));
  3333. }
  3334. #if !defined(QT_NO_DEBUG_STREAM) && !defined(QT_NO_DATESTRING)
  3335. QDebug operator<<(QDebug dbg, const QDate &date)
  3336. {
  3337. dbg.nospace() << "QDate(" << date.toString() << ')';
  3338. return dbg.space();
  3339. }
  3340. QDebug operator<<(QDebug dbg, const QTime &time)
  3341. {
  3342. dbg.nospace() << "QTime(" << time.toString() << ')';
  3343. return dbg.space();
  3344. }
  3345. QDebug operator<<(QDebug dbg, const QDateTime &date)
  3346. {
  3347. dbg.nospace() << "QDateTime(" << date.toString() << ')';
  3348. return dbg.space();
  3349. }
  3350. #endif
  3351. /*! \fn uint qHash(const QDateTime &key, uint seed = 0)
  3352. \relates QHash
  3353. \since 5.0
  3354. Returns the hash value for the \a key, using \a seed to seed the calculation.
  3355. */
  3356. uint qHash(const QDateTime &key, uint seed)
  3357. {
  3358. // Use to toMSecsSinceEpoch instead of individual qHash functions for
  3359. // QDate/QTime/spec/offset because QDateTime::operator== converts both arguments
  3360. // to the same timezone. If we don't, qHash would return different hashes for
  3361. // two QDateTimes that are equivalent once converted to the same timezone.
  3362. return qHash(key.toMSecsSinceEpoch(), seed);
  3363. }
  3364. /*! \fn uint qHash(const QDate &key, uint seed = 0)
  3365. \relates QHash
  3366. \since 5.0
  3367. Returns the hash value for the \a key, using \a seed to seed the calculation.
  3368. */
  3369. uint qHash(const QDate &key, uint seed) Q_DECL_NOTHROW
  3370. {
  3371. return qHash(key.toJulianDay(), seed);
  3372. }
  3373. /*! \fn uint qHash(const QTime &key, uint seed = 0)
  3374. \relates QHash
  3375. \since 5.0
  3376. Returns the hash value for the \a key, using \a seed to seed the calculation.
  3377. */
  3378. uint qHash(const QTime &key, uint seed) Q_DECL_NOTHROW
  3379. {
  3380. return qHash(QTime(0, 0, 0, 0).msecsTo(key), seed);
  3381. }
  3382. #ifndef QT_BOOTSTRAPPED
  3383. /*!
  3384. \internal
  3385. Gets the digit from a datetime. E.g.
  3386. QDateTime var(QDate(2004, 02, 02));
  3387. int digit = getDigit(var, Year);
  3388. // digit = 2004
  3389. */
  3390. int QDateTimeParser::getDigit(const QDateTime &t, int index) const
  3391. {
  3392. if (index < 0 || index >= sectionNodes.size()) {
  3393. #ifndef QT_NO_DATESTRING
  3394. qWarning("QDateTimeParser::getDigit() Internal error (%s %d)",
  3395. qPrintable(t.toString()), index);
  3396. #else
  3397. qWarning("QDateTimeParser::getDigit() Internal error (%d)", index);
  3398. #endif
  3399. return -1;
  3400. }
  3401. const SectionNode &node = sectionNodes.at(index);
  3402. switch (node.type) {
  3403. case Hour24Section: case Hour12Section: return t.time().hour();
  3404. case MinuteSection: return t.time().minute();
  3405. case SecondSection: return t.time().second();
  3406. case MSecSection: return t.time().msec();
  3407. case YearSection2Digits:
  3408. case YearSection: return t.date().year();
  3409. case MonthSection: return t.date().month();
  3410. case DaySection: return t.date().day();
  3411. case DayOfWeekSectionShort:
  3412. case DayOfWeekSectionLong: return t.date().day();
  3413. case AmPmSection: return t.time().hour() > 11 ? 1 : 0;
  3414. default: break;
  3415. }
  3416. #ifndef QT_NO_DATESTRING
  3417. qWarning("QDateTimeParser::getDigit() Internal error 2 (%s %d)",
  3418. qPrintable(t.toString()), index);
  3419. #else
  3420. qWarning("QDateTimeParser::getDigit() Internal error 2 (%d)", index);
  3421. #endif
  3422. return -1;
  3423. }
  3424. /*!
  3425. \internal
  3426. Sets a digit in a datetime. E.g.
  3427. QDateTime var(QDate(2004, 02, 02));
  3428. int digit = getDigit(var, Year);
  3429. // digit = 2004
  3430. setDigit(&var, Year, 2005);
  3431. digit = getDigit(var, Year);
  3432. // digit = 2005
  3433. */
  3434. bool QDateTimeParser::setDigit(QDateTime &v, int index, int newVal) const
  3435. {
  3436. if (index < 0 || index >= sectionNodes.size()) {
  3437. #ifndef QT_NO_DATESTRING
  3438. qWarning("QDateTimeParser::setDigit() Internal error (%s %d %d)",
  3439. qPrintable(v.toString()), index, newVal);
  3440. #else
  3441. qWarning("QDateTimeParser::setDigit() Internal error (%d %d)", index, newVal);
  3442. #endif
  3443. return false;
  3444. }
  3445. const SectionNode &node = sectionNodes.at(index);
  3446. int year, month, day, hour, minute, second, msec;
  3447. year = v.date().year();
  3448. month = v.date().month();
  3449. day = v.date().day();
  3450. hour = v.time().hour();
  3451. minute = v.time().minute();
  3452. second = v.time().second();
  3453. msec = v.time().msec();
  3454. switch (node.type) {
  3455. case Hour24Section: case Hour12Section: hour = newVal; break;
  3456. case MinuteSection: minute = newVal; break;
  3457. case SecondSection: second = newVal; break;
  3458. case MSecSection: msec = newVal; break;
  3459. case YearSection2Digits:
  3460. case YearSection: year = newVal; break;
  3461. case MonthSection: month = newVal; break;
  3462. case DaySection:
  3463. case DayOfWeekSectionShort:
  3464. case DayOfWeekSectionLong:
  3465. if (newVal > 31) {
  3466. // have to keep legacy behavior. setting the
  3467. // date to 32 should return false. Setting it
  3468. // to 31 for february should return true
  3469. return false;
  3470. }
  3471. day = newVal;
  3472. break;
  3473. case AmPmSection: hour = (newVal == 0 ? hour % 12 : (hour % 12) + 12); break;
  3474. default:
  3475. qWarning("QDateTimeParser::setDigit() Internal error (%s)",
  3476. qPrintable(sectionName(node.type)));
  3477. break;
  3478. }
  3479. if (!(node.type & (DaySection|DayOfWeekSectionShort|DayOfWeekSectionLong))) {
  3480. if (day < cachedDay)
  3481. day = cachedDay;
  3482. const int max = QDate(year, month, 1).daysInMonth();
  3483. if (day > max) {
  3484. day = max;
  3485. }
  3486. }
  3487. if (QDate::isValid(year, month, day) && QTime::isValid(hour, minute, second, msec)) {
  3488. v = QDateTime(QDate(year, month, day), QTime(hour, minute, second, msec), spec);
  3489. return true;
  3490. }
  3491. return false;
  3492. }
  3493. /*!
  3494. \
  3495. Returns the absolute maximum for a section
  3496. */
  3497. int QDateTimeParser::absoluteMax(int s, const QDateTime &cur) const
  3498. {
  3499. const SectionNode &sn = sectionNode(s);
  3500. switch (sn.type) {
  3501. case Hour24Section:
  3502. case Hour12Section: return 23; // this is special-cased in
  3503. // parseSection. We want it to be
  3504. // 23 for the stepBy case.
  3505. case MinuteSection:
  3506. case SecondSection: return 59;
  3507. case MSecSection: return 999;
  3508. case YearSection2Digits:
  3509. case YearSection: return 9999; // sectionMaxSize will prevent
  3510. // people from typing in a larger
  3511. // number in count == 2 sections.
  3512. // stepBy() will work on real years anyway
  3513. case MonthSection: return 12;
  3514. case DaySection:
  3515. case DayOfWeekSectionShort:
  3516. case DayOfWeekSectionLong: return cur.isValid() ? cur.date().daysInMonth() : 31;
  3517. case AmPmSection: return 1;
  3518. default: break;
  3519. }
  3520. qWarning("QDateTimeParser::absoluteMax() Internal error (%s)",
  3521. qPrintable(sectionName(sn.type)));
  3522. return -1;
  3523. }
  3524. /*!
  3525. \internal
  3526. Returns the absolute minimum for a section
  3527. */
  3528. int QDateTimeParser::absoluteMin(int s) const
  3529. {
  3530. const SectionNode &sn = sectionNode(s);
  3531. switch (sn.type) {
  3532. case Hour24Section:
  3533. case Hour12Section:
  3534. case MinuteSection:
  3535. case SecondSection:
  3536. case MSecSection:
  3537. case YearSection2Digits:
  3538. case YearSection: return 0;
  3539. case MonthSection:
  3540. case DaySection:
  3541. case DayOfWeekSectionShort:
  3542. case DayOfWeekSectionLong: return 1;
  3543. case AmPmSection: return 0;
  3544. default: break;
  3545. }
  3546. qWarning("QDateTimeParser::absoluteMin() Internal error (%s, %0x)",
  3547. qPrintable(sectionName(sn.type)), sn.type);
  3548. return -1;
  3549. }
  3550. /*!
  3551. \internal
  3552. Returns the sectionNode for the Section \a s.
  3553. */
  3554. const QDateTimeParser::SectionNode &QDateTimeParser::sectionNode(int sectionIndex) const
  3555. {
  3556. if (sectionIndex < 0) {
  3557. switch (sectionIndex) {
  3558. case FirstSectionIndex:
  3559. return first;
  3560. case LastSectionIndex:
  3561. return last;
  3562. case NoSectionIndex:
  3563. return none;
  3564. }
  3565. } else if (sectionIndex < sectionNodes.size()) {
  3566. return sectionNodes.at(sectionIndex);
  3567. }
  3568. qWarning("QDateTimeParser::sectionNode() Internal error (%d)",
  3569. sectionIndex);
  3570. return none;
  3571. }
  3572. QDateTimeParser::Section QDateTimeParser::sectionType(int sectionIndex) const
  3573. {
  3574. return sectionNode(sectionIndex).type;
  3575. }
  3576. /*!
  3577. \internal
  3578. Returns the starting position for section \a s.
  3579. */
  3580. int QDateTimeParser::sectionPos(int sectionIndex) const
  3581. {
  3582. return sectionPos(sectionNode(sectionIndex));
  3583. }
  3584. int QDateTimeParser::sectionPos(const SectionNode &sn) const
  3585. {
  3586. switch (sn.type) {
  3587. case FirstSection: return 0;
  3588. case LastSection: return displayText().size() - 1;
  3589. default: break;
  3590. }
  3591. if (sn.pos == -1) {
  3592. qWarning("QDateTimeParser::sectionPos Internal error (%s)", qPrintable(sectionName(sn.type)));
  3593. return -1;
  3594. }
  3595. return sn.pos;
  3596. }
  3597. /*!
  3598. \internal
  3599. helper function for parseFormat. removes quotes that are
  3600. not escaped and removes the escaping on those that are escaped
  3601. */
  3602. static QString unquote(const QString &str)
  3603. {
  3604. const QChar quote(QLatin1Char('\''));
  3605. const QChar slash(QLatin1Char('\\'));
  3606. const QChar zero(QLatin1Char('0'));
  3607. QString ret;
  3608. QChar status(zero);
  3609. const int max = str.size();
  3610. for (int i=0; i<max; ++i) {
  3611. if (str.at(i) == quote) {
  3612. if (status != quote) {
  3613. status = quote;
  3614. } else if (!ret.isEmpty() && str.at(i - 1) == slash) {
  3615. ret[ret.size() - 1] = quote;
  3616. } else {
  3617. status = zero;
  3618. }
  3619. } else {
  3620. ret += str.at(i);
  3621. }
  3622. }
  3623. return ret;
  3624. }
  3625. /*!
  3626. \internal
  3627. Parses the format \a newFormat. If successful, returns true and
  3628. sets up the format. Else keeps the old format and returns false.
  3629. */
  3630. static inline int countRepeat(const QString &str, int index, int maxCount)
  3631. {
  3632. int count = 1;
  3633. const QChar ch(str.at(index));
  3634. const int max = qMin(index + maxCount, str.size());
  3635. while (index + count < max && str.at(index + count) == ch) {
  3636. ++count;
  3637. }
  3638. return count;
  3639. }
  3640. static inline void appendSeparator(QStringList *list, const QString &string, int from, int size, int lastQuote)
  3641. {
  3642. QString str(string.mid(from, size));
  3643. if (lastQuote >= from)
  3644. str = unquote(str);
  3645. list->append(str);
  3646. }
  3647. bool QDateTimeParser::parseFormat(const QString &newFormat)
  3648. {
  3649. const QLatin1Char quote('\'');
  3650. const QLatin1Char slash('\\');
  3651. const QLatin1Char zero('0');
  3652. if (newFormat == displayFormat && !newFormat.isEmpty()) {
  3653. return true;
  3654. }
  3655. QDTPDEBUGN("parseFormat: %s", newFormat.toLatin1().constData());
  3656. QVector<SectionNode> newSectionNodes;
  3657. Sections newDisplay = 0;
  3658. QStringList newSeparators;
  3659. int i, index = 0;
  3660. int add = 0;
  3661. QChar status(zero);
  3662. const int max = newFormat.size();
  3663. int lastQuote = -1;
  3664. for (i = 0; i<max; ++i) {
  3665. if (newFormat.at(i) == quote) {
  3666. lastQuote = i;
  3667. ++add;
  3668. if (status != quote) {
  3669. status = quote;
  3670. } else if (newFormat.at(i - 1) != slash) {
  3671. status = zero;
  3672. }
  3673. } else if (status != quote) {
  3674. const char sect = newFormat.at(i).toLatin1();
  3675. switch (sect) {
  3676. case 'H':
  3677. case 'h':
  3678. if (parserType != QVariant::Date) {
  3679. const Section hour = (sect == 'h') ? Hour12Section : Hour24Section;
  3680. const SectionNode sn = { hour, i - add, countRepeat(newFormat, i, 2), 0 };
  3681. newSectionNodes.append(sn);
  3682. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3683. i += sn.count - 1;
  3684. index = i + 1;
  3685. newDisplay |= hour;
  3686. }
  3687. break;
  3688. case 'm':
  3689. if (parserType != QVariant::Date) {
  3690. const SectionNode sn = { MinuteSection, i - add, countRepeat(newFormat, i, 2), 0 };
  3691. newSectionNodes.append(sn);
  3692. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3693. i += sn.count - 1;
  3694. index = i + 1;
  3695. newDisplay |= MinuteSection;
  3696. }
  3697. break;
  3698. case 's':
  3699. if (parserType != QVariant::Date) {
  3700. const SectionNode sn = { SecondSection, i - add, countRepeat(newFormat, i, 2), 0 };
  3701. newSectionNodes.append(sn);
  3702. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3703. i += sn.count - 1;
  3704. index = i + 1;
  3705. newDisplay |= SecondSection;
  3706. }
  3707. break;
  3708. case 'z':
  3709. if (parserType != QVariant::Date) {
  3710. const SectionNode sn = { MSecSection, i - add, countRepeat(newFormat, i, 3) < 3 ? 1 : 3, 0 };
  3711. newSectionNodes.append(sn);
  3712. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3713. i += sn.count - 1;
  3714. index = i + 1;
  3715. newDisplay |= MSecSection;
  3716. }
  3717. break;
  3718. case 'A':
  3719. case 'a':
  3720. if (parserType != QVariant::Date) {
  3721. const bool cap = (sect == 'A');
  3722. const SectionNode sn = { AmPmSection, i - add, (cap ? 1 : 0), 0 };
  3723. newSectionNodes.append(sn);
  3724. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3725. newDisplay |= AmPmSection;
  3726. if (i + 1 < newFormat.size()
  3727. && newFormat.at(i+1) == (cap ? QLatin1Char('P') : QLatin1Char('p'))) {
  3728. ++i;
  3729. }
  3730. index = i + 1;
  3731. }
  3732. break;
  3733. case 'y':
  3734. if (parserType != QVariant::Time) {
  3735. const int repeat = countRepeat(newFormat, i, 4);
  3736. if (repeat >= 2) {
  3737. const SectionNode sn = { repeat == 4 ? YearSection : YearSection2Digits,
  3738. i - add, repeat == 4 ? 4 : 2, 0 };
  3739. newSectionNodes.append(sn);
  3740. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3741. i += sn.count - 1;
  3742. index = i + 1;
  3743. newDisplay |= sn.type;
  3744. }
  3745. }
  3746. break;
  3747. case 'M':
  3748. if (parserType != QVariant::Time) {
  3749. const SectionNode sn = { MonthSection, i - add, countRepeat(newFormat, i, 4), 0 };
  3750. newSectionNodes.append(sn);
  3751. newSeparators.append(unquote(newFormat.mid(index, i - index)));
  3752. i += sn.count - 1;
  3753. index = i + 1;
  3754. newDisplay |= MonthSection;
  3755. }
  3756. break;
  3757. case 'd':
  3758. if (parserType != QVariant::Time) {
  3759. const int repeat = countRepeat(newFormat, i, 4);
  3760. const Section sectionType = (repeat == 4 ? DayOfWeekSectionLong
  3761. : (repeat == 3 ? DayOfWeekSectionShort : DaySection));
  3762. const SectionNode sn = { sectionType, i - add, repeat, 0 };
  3763. newSectionNodes.append(sn);
  3764. appendSeparator(&newSeparators, newFormat, index, i - index, lastQuote);
  3765. i += sn.count - 1;
  3766. index = i + 1;
  3767. newDisplay |= sn.type;
  3768. }
  3769. break;
  3770. default:
  3771. break;
  3772. }
  3773. }
  3774. }
  3775. if (newSectionNodes.isEmpty() && context == DateTimeEdit) {
  3776. return false;
  3777. }
  3778. if ((newDisplay & (AmPmSection|Hour12Section)) == Hour12Section) {
  3779. const int max = newSectionNodes.size();
  3780. for (int i=0; i<max; ++i) {
  3781. SectionNode &node = newSectionNodes[i];
  3782. if (node.type == Hour12Section)
  3783. node.type = Hour24Section;
  3784. }
  3785. }
  3786. if (index < newFormat.size()) {
  3787. appendSeparator(&newSeparators, newFormat, index, index - max, lastQuote);
  3788. } else {
  3789. newSeparators.append(QString());
  3790. }
  3791. displayFormat = newFormat;
  3792. separators = newSeparators;
  3793. sectionNodes = newSectionNodes;
  3794. display = newDisplay;
  3795. last.pos = -1;
  3796. // for (int i=0; i<sectionNodes.size(); ++i) {
  3797. // QDTPDEBUG << sectionName(sectionNodes.at(i).type) << sectionNodes.at(i).count;
  3798. // }
  3799. QDTPDEBUG << newFormat << displayFormat;
  3800. QDTPDEBUGN("separators:\n'%s'", separators.join(QLatin1String("\n")).toLatin1().constData());
  3801. return true;
  3802. }
  3803. /*!
  3804. \internal
  3805. Returns the size of section \a s.
  3806. */
  3807. int QDateTimeParser::sectionSize(int sectionIndex) const
  3808. {
  3809. if (sectionIndex < 0)
  3810. return 0;
  3811. if (sectionIndex >= sectionNodes.size()) {
  3812. qWarning("QDateTimeParser::sectionSize Internal error (%d)", sectionIndex);
  3813. return -1;
  3814. }
  3815. if (sectionIndex == sectionNodes.size() - 1) {
  3816. // In some cases there is a difference between displayText() and text.
  3817. // e.g. when text is 2000/01/31 and displayText() is "2000/2/31" - text
  3818. // is the previous value and displayText() is the new value.
  3819. // The size difference is always due to leading zeroes.
  3820. int sizeAdjustment = 0;
  3821. if (displayText().size() != text.size()) {
  3822. // Any zeroes added before this section will affect our size.
  3823. int preceedingZeroesAdded = 0;
  3824. if (sectionNodes.size() > 1 && context == DateTimeEdit) {
  3825. for (QVector<SectionNode>::ConstIterator sectionIt = sectionNodes.constBegin();
  3826. sectionIt != sectionNodes.constBegin() + sectionIndex; ++sectionIt) {
  3827. preceedingZeroesAdded += sectionIt->zeroesAdded;
  3828. }
  3829. }
  3830. sizeAdjustment = preceedingZeroesAdded;
  3831. }
  3832. return displayText().size() + sizeAdjustment - sectionPos(sectionIndex) - separators.last().size();
  3833. } else {
  3834. return sectionPos(sectionIndex + 1) - sectionPos(sectionIndex)
  3835. - separators.at(sectionIndex + 1).size();
  3836. }
  3837. }
  3838. int QDateTimeParser::sectionMaxSize(Section s, int count) const
  3839. {
  3840. #ifndef QT_NO_TEXTDATE
  3841. int mcount = 12;
  3842. #endif
  3843. switch (s) {
  3844. case FirstSection:
  3845. case NoSection:
  3846. case LastSection: return 0;
  3847. case AmPmSection: {
  3848. const int lowerMax = qMin(getAmPmText(AmText, LowerCase).size(),
  3849. getAmPmText(PmText, LowerCase).size());
  3850. const int upperMax = qMin(getAmPmText(AmText, UpperCase).size(),
  3851. getAmPmText(PmText, UpperCase).size());
  3852. return qMin(4, qMin(lowerMax, upperMax));
  3853. }
  3854. case Hour24Section:
  3855. case Hour12Section:
  3856. case MinuteSection:
  3857. case SecondSection:
  3858. case DaySection: return 2;
  3859. case DayOfWeekSectionShort:
  3860. case DayOfWeekSectionLong:
  3861. #ifdef QT_NO_TEXTDATE
  3862. return 2;
  3863. #else
  3864. mcount = 7;
  3865. // fall through
  3866. #endif
  3867. case MonthSection:
  3868. if (count <= 2)
  3869. return 2;
  3870. #ifdef QT_NO_TEXTDATE
  3871. return 2;
  3872. #else
  3873. {
  3874. int ret = 0;
  3875. const QLocale l = locale();
  3876. for (int i=1; i<=mcount; ++i) {
  3877. const QString str = (s == MonthSection
  3878. ? l.monthName(i, count == 4 ? QLocale::LongFormat : QLocale::ShortFormat)
  3879. : l.dayName(i, count == 4 ? QLocale::LongFormat : QLocale::ShortFormat));
  3880. ret = qMax(str.size(), ret);
  3881. }
  3882. return ret;
  3883. }
  3884. #endif
  3885. case MSecSection: return 3;
  3886. case YearSection: return 4;
  3887. case YearSection2Digits: return 2;
  3888. case CalendarPopupSection:
  3889. case Internal:
  3890. case TimeSectionMask:
  3891. case DateSectionMask:
  3892. qWarning("QDateTimeParser::sectionMaxSize: Invalid section %s",
  3893. sectionName(s).toLatin1().constData());
  3894. case NoSectionIndex:
  3895. case FirstSectionIndex:
  3896. case LastSectionIndex:
  3897. case CalendarPopupIndex:
  3898. // these cases can't happen
  3899. break;
  3900. }
  3901. return -1;
  3902. }
  3903. int QDateTimeParser::sectionMaxSize(int index) const
  3904. {
  3905. const SectionNode &sn = sectionNode(index);
  3906. return sectionMaxSize(sn.type, sn.count);
  3907. }
  3908. /*!
  3909. \internal
  3910. Returns the text of section \a s. This function operates on the
  3911. arg text rather than edit->text().
  3912. */
  3913. QString QDateTimeParser::sectionText(const QString &text, int sectionIndex, int index) const
  3914. {
  3915. const SectionNode &sn = sectionNode(sectionIndex);
  3916. switch (sn.type) {
  3917. case NoSectionIndex:
  3918. case FirstSectionIndex:
  3919. case LastSectionIndex:
  3920. return QString();
  3921. default: break;
  3922. }
  3923. return text.mid(index, sectionSize(sectionIndex));
  3924. }
  3925. QString QDateTimeParser::sectionText(int sectionIndex) const
  3926. {
  3927. const SectionNode &sn = sectionNode(sectionIndex);
  3928. switch (sn.type) {
  3929. case NoSectionIndex:
  3930. case FirstSectionIndex:
  3931. case LastSectionIndex:
  3932. return QString();
  3933. default: break;
  3934. }
  3935. return displayText().mid(sn.pos, sectionSize(sectionIndex));
  3936. }
  3937. #ifndef QT_NO_TEXTDATE
  3938. /*!
  3939. \internal:skipToNextSection
  3940. Parses the part of \a text that corresponds to \a s and returns
  3941. the value of that field. Sets *stateptr to the right state if
  3942. stateptr != 0.
  3943. */
  3944. int QDateTimeParser::parseSection(const QDateTime &currentValue, int sectionIndex,
  3945. QString &text, int &cursorPosition, int index,
  3946. State &state, int *usedptr) const
  3947. {
  3948. state = Invalid;
  3949. int num = 0;
  3950. const SectionNode &sn = sectionNode(sectionIndex);
  3951. if ((sn.type & Internal) == Internal) {
  3952. qWarning("QDateTimeParser::parseSection Internal error (%s %d)",
  3953. qPrintable(sectionName(sn.type)), sectionIndex);
  3954. return -1;
  3955. }
  3956. const int sectionmaxsize = sectionMaxSize(sectionIndex);
  3957. QString sectiontext = text.mid(index, sectionmaxsize);
  3958. int sectiontextSize = sectiontext.size();
  3959. QDTPDEBUG << "sectionValue for" << sectionName(sn.type)
  3960. << "with text" << text << "and st" << sectiontext
  3961. << text.mid(index, sectionmaxsize)
  3962. << index;
  3963. int used = 0;
  3964. switch (sn.type) {
  3965. case AmPmSection: {
  3966. const int ampm = findAmPm(sectiontext, sectionIndex, &used);
  3967. switch (ampm) {
  3968. case AM: // sectiontext == AM
  3969. case PM: // sectiontext == PM
  3970. num = ampm;
  3971. state = Acceptable;
  3972. break;
  3973. case PossibleAM: // sectiontext => AM
  3974. case PossiblePM: // sectiontext => PM
  3975. num = ampm - 2;
  3976. state = Intermediate;
  3977. break;
  3978. case PossibleBoth: // sectiontext => AM|PM
  3979. num = 0;
  3980. state = Intermediate;
  3981. break;
  3982. case Neither:
  3983. state = Invalid;
  3984. QDTPDEBUG << "invalid because findAmPm(" << sectiontext << ") returned -1";
  3985. break;
  3986. default:
  3987. QDTPDEBUGN("This should never happen (findAmPm returned %d)", ampm);
  3988. break;
  3989. }
  3990. if (state != Invalid) {
  3991. QString str = text;
  3992. text.replace(index, used, sectiontext.left(used));
  3993. }
  3994. break; }
  3995. case MonthSection:
  3996. case DayOfWeekSectionShort:
  3997. case DayOfWeekSectionLong:
  3998. if (sn.count >= 3) {
  3999. if (sn.type == MonthSection) {
  4000. int min = 1;
  4001. const QDate minDate = getMinimum().date();
  4002. if (currentValue.date().year() == minDate.year()) {
  4003. min = minDate.month();
  4004. }
  4005. num = findMonth(sectiontext.toLower(), min, sectionIndex, &sectiontext, &used);
  4006. } else {
  4007. num = findDay(sectiontext.toLower(), 1, sectionIndex, &sectiontext, &used);
  4008. }
  4009. if (num != -1) {
  4010. state = (used == sectiontext.size() ? Acceptable : Intermediate);
  4011. QString str = text;
  4012. text.replace(index, used, sectiontext.left(used));
  4013. } else {
  4014. state = Intermediate;
  4015. }
  4016. break; }
  4017. // fall through
  4018. case DaySection:
  4019. case YearSection:
  4020. case YearSection2Digits:
  4021. case Hour12Section:
  4022. case Hour24Section:
  4023. case MinuteSection:
  4024. case SecondSection:
  4025. case MSecSection: {
  4026. if (sectiontextSize == 0) {
  4027. num = 0;
  4028. used = 0;
  4029. state = Intermediate;
  4030. } else {
  4031. const int absMax = absoluteMax(sectionIndex);
  4032. QLocale loc;
  4033. bool ok = true;
  4034. int last = -1;
  4035. used = -1;
  4036. QString digitsStr(sectiontext);
  4037. for (int i = 0; i < sectiontextSize; ++i) {
  4038. if (digitsStr.at(i).isSpace()) {
  4039. sectiontextSize = i;
  4040. break;
  4041. }
  4042. }
  4043. const int max = qMin(sectionmaxsize, sectiontextSize);
  4044. for (int digits = max; digits >= 1; --digits) {
  4045. digitsStr.truncate(digits);
  4046. int tmp = (int)loc.toUInt(digitsStr, &ok);
  4047. if (ok && sn.type == Hour12Section) {
  4048. if (tmp > 12) {
  4049. tmp = -1;
  4050. ok = false;
  4051. } else if (tmp == 12) {
  4052. tmp = 0;
  4053. }
  4054. }
  4055. if (ok && tmp <= absMax) {
  4056. QDTPDEBUG << sectiontext.left(digits) << tmp << digits;
  4057. last = tmp;
  4058. used = digits;
  4059. break;
  4060. }
  4061. }
  4062. if (last == -1) {
  4063. QChar first(sectiontext.at(0));
  4064. if (separators.at(sectionIndex + 1).startsWith(first)) {
  4065. used = 0;
  4066. state = Intermediate;
  4067. } else {
  4068. state = Invalid;
  4069. QDTPDEBUG << "invalid because" << sectiontext << "can't become a uint" << last << ok;
  4070. }
  4071. } else {
  4072. num += last;
  4073. const FieldInfo fi = fieldInfo(sectionIndex);
  4074. const bool done = (used == sectionmaxsize);
  4075. if (!done && fi & Fraction) { // typing 2 in a zzz field should be .200, not .002
  4076. for (int i=used; i<sectionmaxsize; ++i) {
  4077. num *= 10;
  4078. }
  4079. }
  4080. const int absMin = absoluteMin(sectionIndex);
  4081. if (num < absMin) {
  4082. state = done ? Invalid : Intermediate;
  4083. if (done)
  4084. QDTPDEBUG << "invalid because" << num << "is less than absoluteMin" << absMin;
  4085. } else if (num > absMax) {
  4086. state = Intermediate;
  4087. } else if (!done && (fi & (FixedWidth|Numeric)) == (FixedWidth|Numeric)) {
  4088. if (skipToNextSection(sectionIndex, currentValue, digitsStr)) {
  4089. state = Acceptable;
  4090. const int missingZeroes = sectionmaxsize - digitsStr.size();
  4091. text.insert(index, QString().fill(QLatin1Char('0'), missingZeroes));
  4092. used = sectionmaxsize;
  4093. cursorPosition += missingZeroes;
  4094. ++(const_cast<QDateTimeParser*>(this)->sectionNodes[sectionIndex].zeroesAdded);
  4095. } else {
  4096. state = Intermediate;;
  4097. }
  4098. } else {
  4099. state = Acceptable;
  4100. }
  4101. }
  4102. }
  4103. break; }
  4104. default:
  4105. qWarning("QDateTimeParser::parseSection Internal error (%s %d)",
  4106. qPrintable(sectionName(sn.type)), sectionIndex);
  4107. return -1;
  4108. }
  4109. if (usedptr)
  4110. *usedptr = used;
  4111. return (state != Invalid ? num : -1);
  4112. }
  4113. #endif // QT_NO_TEXTDATE
  4114. #ifndef QT_NO_DATESTRING
  4115. /*!
  4116. \internal
  4117. */
  4118. QDateTimeParser::StateNode QDateTimeParser::parse(QString &input, int &cursorPosition,
  4119. const QDateTime &currentValue, bool fixup) const
  4120. {
  4121. const QDateTime minimum = getMinimum();
  4122. const QDateTime maximum = getMaximum();
  4123. State state = Acceptable;
  4124. QDateTime newCurrentValue;
  4125. int pos = 0;
  4126. bool conflicts = false;
  4127. const int sectionNodesCount = sectionNodes.size();
  4128. QDTPDEBUG << "parse" << input;
  4129. {
  4130. int year, month, day, hour12, hour, minute, second, msec, ampm, dayofweek, year2digits;
  4131. getDateFromJulianDay(currentValue.date().toJulianDay(), &year, &month, &day);
  4132. year2digits = year % 100;
  4133. hour = currentValue.time().hour();
  4134. hour12 = -1;
  4135. minute = currentValue.time().minute();
  4136. second = currentValue.time().second();
  4137. msec = currentValue.time().msec();
  4138. dayofweek = currentValue.date().dayOfWeek();
  4139. ampm = -1;
  4140. Sections isSet = NoSection;
  4141. int num;
  4142. State tmpstate;
  4143. for (int index=0; state != Invalid && index<sectionNodesCount; ++index) {
  4144. if (QStringRef(&input, pos, separators.at(index).size()) != separators.at(index)) {
  4145. QDTPDEBUG << "invalid because" << input.mid(pos, separators.at(index).size())
  4146. << "!=" << separators.at(index)
  4147. << index << pos << currentSectionIndex;
  4148. state = Invalid;
  4149. goto end;
  4150. }
  4151. pos += separators.at(index).size();
  4152. sectionNodes[index].pos = pos;
  4153. int *current = 0;
  4154. const SectionNode sn = sectionNodes.at(index);
  4155. int used;
  4156. num = parseSection(currentValue, index, input, cursorPosition, pos, tmpstate, &used);
  4157. QDTPDEBUG << "sectionValue" << sectionName(sectionType(index)) << input
  4158. << "pos" << pos << "used" << used << stateName(tmpstate);
  4159. if (fixup && tmpstate == Intermediate && used < sn.count) {
  4160. const FieldInfo fi = fieldInfo(index);
  4161. if ((fi & (Numeric|FixedWidth)) == (Numeric|FixedWidth)) {
  4162. const QString newText = QString::fromLatin1("%1").arg(num, sn.count, 10, QLatin1Char('0'));
  4163. input.replace(pos, used, newText);
  4164. used = sn.count;
  4165. }
  4166. }
  4167. pos += qMax(0, used);
  4168. state = qMin<State>(state, tmpstate);
  4169. if (state == Intermediate && context == FromString) {
  4170. state = Invalid;
  4171. break;
  4172. }
  4173. QDTPDEBUG << index << sectionName(sectionType(index)) << "is set to"
  4174. << pos << "state is" << stateName(state);
  4175. if (state != Invalid) {
  4176. switch (sn.type) {
  4177. case Hour24Section: current = &hour; break;
  4178. case Hour12Section: current = &hour12; break;
  4179. case MinuteSection: current = &minute; break;
  4180. case SecondSection: current = &second; break;
  4181. case MSecSection: current = &msec; break;
  4182. case YearSection: current = &year; break;
  4183. case YearSection2Digits: current = &year2digits; break;
  4184. case MonthSection: current = &month; break;
  4185. case DayOfWeekSectionShort:
  4186. case DayOfWeekSectionLong: current = &dayofweek; break;
  4187. case DaySection: current = &day; num = qMax<int>(1, num); break;
  4188. case AmPmSection: current = &ampm; break;
  4189. default:
  4190. qWarning("QDateTimeParser::parse Internal error (%s)",
  4191. qPrintable(sectionName(sn.type)));
  4192. break;
  4193. }
  4194. if (!current) {
  4195. qWarning("QDateTimeParser::parse Internal error 2");
  4196. return StateNode();
  4197. }
  4198. if (isSet & sn.type && *current != num) {
  4199. QDTPDEBUG << "CONFLICT " << sectionName(sn.type) << *current << num;
  4200. conflicts = true;
  4201. if (index != currentSectionIndex || num == -1) {
  4202. continue;
  4203. }
  4204. }
  4205. if (num != -1)
  4206. *current = num;
  4207. isSet |= sn.type;
  4208. }
  4209. }
  4210. if (state != Invalid && QStringRef(&input, pos, input.size() - pos) != separators.last()) {
  4211. QDTPDEBUG << "invalid because" << input.mid(pos)
  4212. << "!=" << separators.last() << pos;
  4213. state = Invalid;
  4214. }
  4215. if (state != Invalid) {
  4216. if (parserType != QVariant::Time) {
  4217. if (year % 100 != year2digits) {
  4218. switch (isSet & (YearSection2Digits|YearSection)) {
  4219. case YearSection2Digits:
  4220. year = (year / 100) * 100;
  4221. year += year2digits;
  4222. break;
  4223. case ((uint)YearSection2Digits|(uint)YearSection): {
  4224. conflicts = true;
  4225. const SectionNode &sn = sectionNode(currentSectionIndex);
  4226. if (sn.type == YearSection2Digits) {
  4227. year = (year / 100) * 100;
  4228. year += year2digits;
  4229. }
  4230. break; }
  4231. default:
  4232. break;
  4233. }
  4234. }
  4235. const QDate date(year, month, day);
  4236. const int diff = dayofweek - date.dayOfWeek();
  4237. if (diff != 0 && state == Acceptable && isSet & (DayOfWeekSectionShort|DayOfWeekSectionLong)) {
  4238. conflicts = isSet & DaySection;
  4239. const SectionNode &sn = sectionNode(currentSectionIndex);
  4240. if (sn.type & (DayOfWeekSectionShort|DayOfWeekSectionLong) || currentSectionIndex == -1) {
  4241. // dayofweek should be preferred
  4242. day += diff;
  4243. if (day <= 0) {
  4244. day += 7;
  4245. } else if (day > date.daysInMonth()) {
  4246. day -= 7;
  4247. }
  4248. QDTPDEBUG << year << month << day << dayofweek
  4249. << diff << QDate(year, month, day).dayOfWeek();
  4250. }
  4251. }
  4252. bool needfixday = false;
  4253. if (sectionType(currentSectionIndex) & (DaySection|DayOfWeekSectionShort|DayOfWeekSectionLong)) {
  4254. cachedDay = day;
  4255. } else if (cachedDay > day) {
  4256. day = cachedDay;
  4257. needfixday = true;
  4258. }
  4259. if (!QDate::isValid(year, month, day)) {
  4260. if (day < 32) {
  4261. cachedDay = day;
  4262. }
  4263. if (day > 28 && QDate::isValid(year, month, 1)) {
  4264. needfixday = true;
  4265. }
  4266. }
  4267. if (needfixday) {
  4268. if (context == FromString) {
  4269. state = Invalid;
  4270. goto end;
  4271. }
  4272. if (state == Acceptable && fixday) {
  4273. day = qMin<int>(day, QDate(year, month, 1).daysInMonth());
  4274. const QLocale loc = locale();
  4275. for (int i=0; i<sectionNodesCount; ++i) {
  4276. const Section thisSectionType = sectionType(i);
  4277. if (thisSectionType & (DaySection)) {
  4278. input.replace(sectionPos(i), sectionSize(i), loc.toString(day));
  4279. } else if (thisSectionType & (DayOfWeekSectionShort|DayOfWeekSectionLong)) {
  4280. const int dayOfWeek = QDate(year, month, day).dayOfWeek();
  4281. const QLocale::FormatType dayFormat = (thisSectionType == DayOfWeekSectionShort
  4282. ? QLocale::ShortFormat : QLocale::LongFormat);
  4283. const QString dayName(loc.dayName(dayOfWeek, dayFormat));
  4284. input.replace(sectionPos(i), sectionSize(i), dayName);
  4285. }
  4286. }
  4287. } else {
  4288. state = qMin(Intermediate, state);
  4289. }
  4290. }
  4291. }
  4292. if (parserType != QVariant::Date) {
  4293. if (isSet & Hour12Section) {
  4294. const bool hasHour = isSet & Hour24Section;
  4295. if (ampm == -1) {
  4296. if (hasHour) {
  4297. ampm = (hour < 12 ? 0 : 1);
  4298. } else {
  4299. ampm = 0; // no way to tell if this is am or pm so I assume am
  4300. }
  4301. }
  4302. hour12 = (ampm == 0 ? hour12 % 12 : (hour12 % 12) + 12);
  4303. if (!hasHour) {
  4304. hour = hour12;
  4305. } else if (hour != hour12) {
  4306. conflicts = true;
  4307. }
  4308. } else if (ampm != -1) {
  4309. if (!(isSet & (Hour24Section))) {
  4310. hour = (12 * ampm); // special case. Only ap section
  4311. } else if ((ampm == 0) != (hour < 12)) {
  4312. conflicts = true;
  4313. }
  4314. }
  4315. }
  4316. newCurrentValue = QDateTime(QDate(year, month, day), QTime(hour, minute, second, msec), spec);
  4317. QDTPDEBUG << year << month << day << hour << minute << second << msec;
  4318. }
  4319. QDTPDEBUGN("'%s' => '%s'(%s)", input.toLatin1().constData(),
  4320. newCurrentValue.toString(QLatin1String("yyyy/MM/dd hh:mm:ss.zzz")).toLatin1().constData(),
  4321. stateName(state).toLatin1().constData());
  4322. }
  4323. end:
  4324. if (newCurrentValue.isValid()) {
  4325. if (context != FromString && state != Invalid && newCurrentValue < minimum) {
  4326. const QLatin1Char space(' ');
  4327. if (newCurrentValue >= minimum)
  4328. qWarning("QDateTimeParser::parse Internal error 3 (%s %s)",
  4329. qPrintable(newCurrentValue.toString()), qPrintable(minimum.toString()));
  4330. bool done = false;
  4331. state = Invalid;
  4332. for (int i=0; i<sectionNodesCount && !done; ++i) {
  4333. const SectionNode &sn = sectionNodes.at(i);
  4334. QString t = sectionText(input, i, sn.pos).toLower();
  4335. if ((t.size() < sectionMaxSize(i) && (((int)fieldInfo(i) & (FixedWidth|Numeric)) != Numeric))
  4336. || t.contains(space)) {
  4337. switch (sn.type) {
  4338. case AmPmSection:
  4339. switch (findAmPm(t, i)) {
  4340. case AM:
  4341. case PM:
  4342. state = Acceptable;
  4343. done = true;
  4344. break;
  4345. case Neither:
  4346. state = Invalid;
  4347. done = true;
  4348. break;
  4349. case PossibleAM:
  4350. case PossiblePM:
  4351. case PossibleBoth: {
  4352. const QDateTime copy(newCurrentValue.addSecs(12 * 60 * 60));
  4353. if (copy >= minimum && copy <= maximum) {
  4354. state = Intermediate;
  4355. done = true;
  4356. }
  4357. break; }
  4358. }
  4359. case MonthSection:
  4360. if (sn.count >= 3) {
  4361. int tmp = newCurrentValue.date().month();
  4362. // I know the first possible month makes the date too early
  4363. while ((tmp = findMonth(t, tmp + 1, i)) != -1) {
  4364. const QDateTime copy(newCurrentValue.addMonths(tmp - newCurrentValue.date().month()));
  4365. if (copy >= minimum && copy <= maximum)
  4366. break; // break out of while
  4367. }
  4368. if (tmp == -1) {
  4369. break;
  4370. }
  4371. state = Intermediate;
  4372. done = true;
  4373. break;
  4374. }
  4375. // fallthrough
  4376. default: {
  4377. int toMin;
  4378. int toMax;
  4379. if (sn.type & TimeSectionMask) {
  4380. if (newCurrentValue.daysTo(minimum) != 0) {
  4381. break;
  4382. }
  4383. toMin = newCurrentValue.time().msecsTo(minimum.time());
  4384. if (newCurrentValue.daysTo(maximum) > 0) {
  4385. toMax = -1; // can't get to max
  4386. } else {
  4387. toMax = newCurrentValue.time().msecsTo(maximum.time());
  4388. }
  4389. } else {
  4390. toMin = newCurrentValue.daysTo(minimum);
  4391. toMax = newCurrentValue.daysTo(maximum);
  4392. }
  4393. const int maxChange = QDateTimeParser::maxChange(i);
  4394. if (toMin > maxChange) {
  4395. QDTPDEBUG << "invalid because toMin > maxChange" << toMin
  4396. << maxChange << t << newCurrentValue << minimum;
  4397. state = Invalid;
  4398. done = true;
  4399. break;
  4400. } else if (toMax > maxChange) {
  4401. toMax = -1; // can't get to max
  4402. }
  4403. const int min = getDigit(minimum, i);
  4404. if (min == -1) {
  4405. qWarning("QDateTimeParser::parse Internal error 4 (%s)",
  4406. qPrintable(sectionName(sn.type)));
  4407. state = Invalid;
  4408. done = true;
  4409. break;
  4410. }
  4411. int max = toMax != -1 ? getDigit(maximum, i) : absoluteMax(i, newCurrentValue);
  4412. int pos = cursorPosition - sn.pos;
  4413. if (pos < 0 || pos >= t.size())
  4414. pos = -1;
  4415. if (!potentialValue(t.simplified(), min, max, i, newCurrentValue, pos)) {
  4416. QDTPDEBUG << "invalid because potentialValue(" << t.simplified() << min << max
  4417. << sectionName(sn.type) << "returned" << toMax << toMin << pos;
  4418. state = Invalid;
  4419. done = true;
  4420. break;
  4421. }
  4422. state = Intermediate;
  4423. done = true;
  4424. break; }
  4425. }
  4426. }
  4427. }
  4428. } else {
  4429. if (context == FromString) {
  4430. // optimization
  4431. Q_ASSERT(getMaximum().date().toJulianDay() == 4642999);
  4432. if (newCurrentValue.date().toJulianDay() > 4642999)
  4433. state = Invalid;
  4434. } else {
  4435. if (newCurrentValue > getMaximum())
  4436. state = Invalid;
  4437. }
  4438. QDTPDEBUG << "not checking intermediate because newCurrentValue is" << newCurrentValue << getMinimum() << getMaximum();
  4439. }
  4440. }
  4441. StateNode node;
  4442. node.input = input;
  4443. node.state = state;
  4444. node.conflicts = conflicts;
  4445. node.value = newCurrentValue.toTimeSpec(spec);
  4446. text = input;
  4447. return node;
  4448. }
  4449. #endif // QT_NO_DATESTRING
  4450. #ifndef QT_NO_TEXTDATE
  4451. /*!
  4452. \internal
  4453. finds the first possible monthname that \a str1 can
  4454. match. Starting from \a index; str should already by lowered
  4455. */
  4456. int QDateTimeParser::findMonth(const QString &str1, int startMonth, int sectionIndex,
  4457. QString *usedMonth, int *used) const
  4458. {
  4459. int bestMatch = -1;
  4460. int bestCount = 0;
  4461. if (!str1.isEmpty()) {
  4462. const SectionNode &sn = sectionNode(sectionIndex);
  4463. if (sn.type != MonthSection) {
  4464. qWarning("QDateTimeParser::findMonth Internal error");
  4465. return -1;
  4466. }
  4467. QLocale::FormatType type = sn.count == 3 ? QLocale::ShortFormat : QLocale::LongFormat;
  4468. QLocale l = locale();
  4469. for (int month=startMonth; month<=12; ++month) {
  4470. QString str2 = l.monthName(month, type).toLower();
  4471. if (str1.startsWith(str2)) {
  4472. if (used) {
  4473. QDTPDEBUG << "used is set to" << str2.size();
  4474. *used = str2.size();
  4475. }
  4476. if (usedMonth)
  4477. *usedMonth = l.monthName(month, type);
  4478. return month;
  4479. }
  4480. if (context == FromString)
  4481. continue;
  4482. const int limit = qMin(str1.size(), str2.size());
  4483. QDTPDEBUG << "limit is" << limit << str1 << str2;
  4484. bool equal = true;
  4485. for (int i=0; i<limit; ++i) {
  4486. if (str1.at(i) != str2.at(i)) {
  4487. equal = false;
  4488. if (i > bestCount) {
  4489. bestCount = i;
  4490. bestMatch = month;
  4491. }
  4492. break;
  4493. }
  4494. }
  4495. if (equal) {
  4496. if (used)
  4497. *used = limit;
  4498. if (usedMonth)
  4499. *usedMonth = l.monthName(month, type);
  4500. return month;
  4501. }
  4502. }
  4503. if (usedMonth && bestMatch != -1)
  4504. *usedMonth = l.monthName(bestMatch, type);
  4505. }
  4506. if (used) {
  4507. QDTPDEBUG << "used is set to" << bestCount;
  4508. *used = bestCount;
  4509. }
  4510. return bestMatch;
  4511. }
  4512. int QDateTimeParser::findDay(const QString &str1, int startDay, int sectionIndex, QString *usedDay, int *used) const
  4513. {
  4514. int bestMatch = -1;
  4515. int bestCount = 0;
  4516. if (!str1.isEmpty()) {
  4517. const SectionNode &sn = sectionNode(sectionIndex);
  4518. if (!(sn.type & (DaySection|DayOfWeekSectionShort|DayOfWeekSectionLong))) {
  4519. qWarning("QDateTimeParser::findDay Internal error");
  4520. return -1;
  4521. }
  4522. const QLocale l = locale();
  4523. for (int day=startDay; day<=7; ++day) {
  4524. const QString str2 = l.dayName(day, sn.count == 4 ? QLocale::LongFormat : QLocale::ShortFormat);
  4525. if (str1.startsWith(str2.toLower())) {
  4526. if (used)
  4527. *used = str2.size();
  4528. if (usedDay) {
  4529. *usedDay = str2;
  4530. }
  4531. return day;
  4532. }
  4533. if (context == FromString)
  4534. continue;
  4535. const int limit = qMin(str1.size(), str2.size());
  4536. bool found = true;
  4537. for (int i=0; i<limit; ++i) {
  4538. if (str1.at(i) != str2.at(i) && !str1.at(i).isSpace()) {
  4539. if (i > bestCount) {
  4540. bestCount = i;
  4541. bestMatch = day;
  4542. }
  4543. found = false;
  4544. break;
  4545. }
  4546. }
  4547. if (found) {
  4548. if (used)
  4549. *used = limit;
  4550. if (usedDay)
  4551. *usedDay = str2;
  4552. return day;
  4553. }
  4554. }
  4555. if (usedDay && bestMatch != -1) {
  4556. *usedDay = l.dayName(bestMatch, sn.count == 4 ? QLocale::LongFormat : QLocale::ShortFormat);
  4557. }
  4558. }
  4559. if (used)
  4560. *used = bestCount;
  4561. return bestMatch;
  4562. }
  4563. #endif // QT_NO_TEXTDATE
  4564. /*!
  4565. \internal
  4566. returns
  4567. 0 if str == QDateTimeEdit::tr("AM")
  4568. 1 if str == QDateTimeEdit::tr("PM")
  4569. 2 if str can become QDateTimeEdit::tr("AM")
  4570. 3 if str can become QDateTimeEdit::tr("PM")
  4571. 4 if str can become QDateTimeEdit::tr("PM") and can become QDateTimeEdit::tr("AM")
  4572. -1 can't become anything sensible
  4573. */
  4574. int QDateTimeParser::findAmPm(QString &str, int index, int *used) const
  4575. {
  4576. const SectionNode &s = sectionNode(index);
  4577. if (s.type != AmPmSection) {
  4578. qWarning("QDateTimeParser::findAmPm Internal error");
  4579. return -1;
  4580. }
  4581. if (used)
  4582. *used = str.size();
  4583. if (str.trimmed().isEmpty()) {
  4584. return PossibleBoth;
  4585. }
  4586. const QLatin1Char space(' ');
  4587. int size = sectionMaxSize(index);
  4588. enum {
  4589. amindex = 0,
  4590. pmindex = 1
  4591. };
  4592. QString ampm[2];
  4593. ampm[amindex] = getAmPmText(AmText, s.count == 1 ? UpperCase : LowerCase);
  4594. ampm[pmindex] = getAmPmText(PmText, s.count == 1 ? UpperCase : LowerCase);
  4595. for (int i=0; i<2; ++i)
  4596. ampm[i].truncate(size);
  4597. QDTPDEBUG << "findAmPm" << str << ampm[0] << ampm[1];
  4598. if (str.indexOf(ampm[amindex], 0, Qt::CaseInsensitive) == 0) {
  4599. str = ampm[amindex];
  4600. return AM;
  4601. } else if (str.indexOf(ampm[pmindex], 0, Qt::CaseInsensitive) == 0) {
  4602. str = ampm[pmindex];
  4603. return PM;
  4604. } else if (context == FromString || (str.count(space) == 0 && str.size() >= size)) {
  4605. return Neither;
  4606. }
  4607. size = qMin(size, str.size());
  4608. bool broken[2] = {false, false};
  4609. for (int i=0; i<size; ++i) {
  4610. if (str.at(i) != space) {
  4611. for (int j=0; j<2; ++j) {
  4612. if (!broken[j]) {
  4613. int index = ampm[j].indexOf(str.at(i));
  4614. QDTPDEBUG << "looking for" << str.at(i)
  4615. << "in" << ampm[j] << "and got" << index;
  4616. if (index == -1) {
  4617. if (str.at(i).category() == QChar::Letter_Uppercase) {
  4618. index = ampm[j].indexOf(str.at(i).toLower());
  4619. QDTPDEBUG << "trying with" << str.at(i).toLower()
  4620. << "in" << ampm[j] << "and got" << index;
  4621. } else if (str.at(i).category() == QChar::Letter_Lowercase) {
  4622. index = ampm[j].indexOf(str.at(i).toUpper());
  4623. QDTPDEBUG << "trying with" << str.at(i).toUpper()
  4624. << "in" << ampm[j] << "and got" << index;
  4625. }
  4626. if (index == -1) {
  4627. broken[j] = true;
  4628. if (broken[amindex] && broken[pmindex]) {
  4629. QDTPDEBUG << str << "didn't make it";
  4630. return Neither;
  4631. }
  4632. continue;
  4633. } else {
  4634. str[i] = ampm[j].at(index); // fix case
  4635. }
  4636. }
  4637. ampm[j].remove(index, 1);
  4638. }
  4639. }
  4640. }
  4641. }
  4642. if (!broken[pmindex] && !broken[amindex])
  4643. return PossibleBoth;
  4644. return (!broken[amindex] ? PossibleAM : PossiblePM);
  4645. }
  4646. /*!
  4647. \internal
  4648. Max number of units that can be changed by this section.
  4649. */
  4650. int QDateTimeParser::maxChange(int index) const
  4651. {
  4652. const SectionNode &sn = sectionNode(index);
  4653. switch (sn.type) {
  4654. // Time. unit is msec
  4655. case MSecSection: return 999;
  4656. case SecondSection: return 59 * 1000;
  4657. case MinuteSection: return 59 * 60 * 1000;
  4658. case Hour24Section: case Hour12Section: return 59 * 60 * 60 * 1000;
  4659. // Date. unit is day
  4660. case DayOfWeekSectionShort:
  4661. case DayOfWeekSectionLong: return 7;
  4662. case DaySection: return 30;
  4663. case MonthSection: return 365 - 31;
  4664. case YearSection: return 9999 * 365;
  4665. case YearSection2Digits: return 100 * 365;
  4666. default:
  4667. qWarning("QDateTimeParser::maxChange() Internal error (%s)",
  4668. qPrintable(sectionName(sectionType(index))));
  4669. }
  4670. return -1;
  4671. }
  4672. QDateTimeParser::FieldInfo QDateTimeParser::fieldInfo(int index) const
  4673. {
  4674. FieldInfo ret = 0;
  4675. const SectionNode &sn = sectionNode(index);
  4676. const Section s = sn.type;
  4677. switch (s) {
  4678. case MSecSection:
  4679. ret |= Fraction;
  4680. // fallthrough
  4681. case SecondSection:
  4682. case MinuteSection:
  4683. case Hour24Section:
  4684. case Hour12Section:
  4685. case YearSection:
  4686. case YearSection2Digits:
  4687. ret |= Numeric;
  4688. if (s != YearSection) {
  4689. ret |= AllowPartial;
  4690. }
  4691. if (sn.count != 1) {
  4692. ret |= FixedWidth;
  4693. }
  4694. break;
  4695. case MonthSection:
  4696. case DaySection:
  4697. switch (sn.count) {
  4698. case 2:
  4699. ret |= FixedWidth;
  4700. // fallthrough
  4701. case 1:
  4702. ret |= (Numeric|AllowPartial);
  4703. break;
  4704. }
  4705. break;
  4706. case DayOfWeekSectionShort:
  4707. case DayOfWeekSectionLong:
  4708. if (sn.count == 3)
  4709. ret |= FixedWidth;
  4710. break;
  4711. case AmPmSection:
  4712. ret |= FixedWidth;
  4713. break;
  4714. default:
  4715. qWarning("QDateTimeParser::fieldInfo Internal error 2 (%d %s %d)",
  4716. index, qPrintable(sectionName(sn.type)), sn.count);
  4717. break;
  4718. }
  4719. return ret;
  4720. }
  4721. /*!
  4722. \internal
  4723. Get a number that str can become which is between min
  4724. and max or -1 if this is not possible.
  4725. */
  4726. QString QDateTimeParser::sectionFormat(int index) const
  4727. {
  4728. const SectionNode &sn = sectionNode(index);
  4729. return sectionFormat(sn.type, sn.count);
  4730. }
  4731. QString QDateTimeParser::sectionFormat(Section s, int count) const
  4732. {
  4733. QChar fillChar;
  4734. switch (s) {
  4735. case AmPmSection: return count == 1 ? QLatin1String("AP") : QLatin1String("ap");
  4736. case MSecSection: fillChar = QLatin1Char('z'); break;
  4737. case SecondSection: fillChar = QLatin1Char('s'); break;
  4738. case MinuteSection: fillChar = QLatin1Char('m'); break;
  4739. case Hour24Section: fillChar = QLatin1Char('H'); break;
  4740. case Hour12Section: fillChar = QLatin1Char('h'); break;
  4741. case DayOfWeekSectionShort:
  4742. case DayOfWeekSectionLong:
  4743. case DaySection: fillChar = QLatin1Char('d'); break;
  4744. case MonthSection: fillChar = QLatin1Char('M'); break;
  4745. case YearSection2Digits:
  4746. case YearSection: fillChar = QLatin1Char('y'); break;
  4747. default:
  4748. qWarning("QDateTimeParser::sectionFormat Internal error (%s)",
  4749. qPrintable(sectionName(s)));
  4750. return QString();
  4751. }
  4752. if (fillChar.isNull()) {
  4753. qWarning("QDateTimeParser::sectionFormat Internal error 2");
  4754. return QString();
  4755. }
  4756. QString str;
  4757. str.fill(fillChar, count);
  4758. return str;
  4759. }
  4760. /*!
  4761. \internal
  4762. Returns true if str can be modified to represent a
  4763. number that is within min and max.
  4764. */
  4765. bool QDateTimeParser::potentialValue(const QString &str, int min, int max, int index,
  4766. const QDateTime &currentValue, int insert) const
  4767. {
  4768. if (str.isEmpty()) {
  4769. return true;
  4770. }
  4771. const int size = sectionMaxSize(index);
  4772. int val = (int)locale().toUInt(str);
  4773. const SectionNode &sn = sectionNode(index);
  4774. if (sn.type == YearSection2Digits) {
  4775. val += currentValue.date().year() - (currentValue.date().year() % 100);
  4776. }
  4777. if (val >= min && val <= max && str.size() == size) {
  4778. return true;
  4779. } else if (val > max) {
  4780. return false;
  4781. } else if (str.size() == size && val < min) {
  4782. return false;
  4783. }
  4784. const int len = size - str.size();
  4785. for (int i=0; i<len; ++i) {
  4786. for (int j=0; j<10; ++j) {
  4787. if (potentialValue(str + QLatin1Char('0' + j), min, max, index, currentValue, insert)) {
  4788. return true;
  4789. } else if (insert >= 0) {
  4790. QString tmp = str;
  4791. tmp.insert(insert, QLatin1Char('0' + j));
  4792. if (potentialValue(tmp, min, max, index, currentValue, insert))
  4793. return true;
  4794. }
  4795. }
  4796. }
  4797. return false;
  4798. }
  4799. bool QDateTimeParser::skipToNextSection(int index, const QDateTime &current, const QString &text) const
  4800. {
  4801. Q_ASSERT(current >= getMinimum() && current <= getMaximum());
  4802. const SectionNode &node = sectionNode(index);
  4803. Q_ASSERT(text.size() < sectionMaxSize(index));
  4804. const QDateTime maximum = getMaximum();
  4805. const QDateTime minimum = getMinimum();
  4806. QDateTime tmp = current;
  4807. int min = absoluteMin(index);
  4808. setDigit(tmp, index, min);
  4809. if (tmp < minimum) {
  4810. min = getDigit(minimum, index);
  4811. }
  4812. int max = absoluteMax(index, current);
  4813. setDigit(tmp, index, max);
  4814. if (tmp > maximum) {
  4815. max = getDigit(maximum, index);
  4816. }
  4817. int pos = cursorPosition() - node.pos;
  4818. if (pos < 0 || pos >= text.size())
  4819. pos = -1;
  4820. const bool potential = potentialValue(text, min, max, index, current, pos);
  4821. return !potential;
  4822. /* If the value potentially can become another valid entry we
  4823. * don't want to skip to the next. E.g. In a M field (month
  4824. * without leading 0 if you type 1 we don't want to autoskip but
  4825. * if you type 3 we do
  4826. */
  4827. }
  4828. /*!
  4829. \internal
  4830. For debugging. Returns the name of the section \a s.
  4831. */
  4832. QString QDateTimeParser::sectionName(int s) const
  4833. {
  4834. switch (s) {
  4835. case QDateTimeParser::AmPmSection: return QLatin1String("AmPmSection");
  4836. case QDateTimeParser::DaySection: return QLatin1String("DaySection");
  4837. case QDateTimeParser::DayOfWeekSectionShort: return QLatin1String("DayOfWeekSectionShort");
  4838. case QDateTimeParser::DayOfWeekSectionLong: return QLatin1String("DayOfWeekSectionLong");
  4839. case QDateTimeParser::Hour24Section: return QLatin1String("Hour24Section");
  4840. case QDateTimeParser::Hour12Section: return QLatin1String("Hour12Section");
  4841. case QDateTimeParser::MSecSection: return QLatin1String("MSecSection");
  4842. case QDateTimeParser::MinuteSection: return QLatin1String("MinuteSection");
  4843. case QDateTimeParser::MonthSection: return QLatin1String("MonthSection");
  4844. case QDateTimeParser::SecondSection: return QLatin1String("SecondSection");
  4845. case QDateTimeParser::YearSection: return QLatin1String("YearSection");
  4846. case QDateTimeParser::YearSection2Digits: return QLatin1String("YearSection2Digits");
  4847. case QDateTimeParser::NoSection: return QLatin1String("NoSection");
  4848. case QDateTimeParser::FirstSection: return QLatin1String("FirstSection");
  4849. case QDateTimeParser::LastSection: return QLatin1String("LastSection");
  4850. default: return QLatin1String("Unknown section ") + QString::number(s);
  4851. }
  4852. }
  4853. /*!
  4854. \internal
  4855. For debugging. Returns the name of the state \a s.
  4856. */
  4857. QString QDateTimeParser::stateName(int s) const
  4858. {
  4859. switch (s) {
  4860. case Invalid: return QLatin1String("Invalid");
  4861. case Intermediate: return QLatin1String("Intermediate");
  4862. case Acceptable: return QLatin1String("Acceptable");
  4863. default: return QLatin1String("Unknown state ") + QString::number(s);
  4864. }
  4865. }
  4866. #ifndef QT_NO_DATESTRING
  4867. bool QDateTimeParser::fromString(const QString &t, QDate *date, QTime *time) const
  4868. {
  4869. QDateTime val(QDate(1900, 1, 1), QDATETIMEEDIT_TIME_MIN);
  4870. QString text = t;
  4871. int copy = -1;
  4872. const StateNode tmp = parse(text, copy, val, false);
  4873. if (tmp.state != Acceptable || tmp.conflicts) {
  4874. return false;
  4875. }
  4876. if (time) {
  4877. const QTime t = tmp.value.time();
  4878. if (!t.isValid()) {
  4879. return false;
  4880. }
  4881. *time = t;
  4882. }
  4883. if (date) {
  4884. const QDate d = tmp.value.date();
  4885. if (!d.isValid()) {
  4886. return false;
  4887. }
  4888. *date = d;
  4889. }
  4890. return true;
  4891. }
  4892. #endif // QT_NO_DATESTRING
  4893. QDateTime QDateTimeParser::getMinimum() const
  4894. {
  4895. return QDateTime(QDATETIMEEDIT_DATE_MIN, QDATETIMEEDIT_TIME_MIN, spec);
  4896. }
  4897. QDateTime QDateTimeParser::getMaximum() const
  4898. {
  4899. return QDateTime(QDATETIMEEDIT_DATE_MAX, QDATETIMEEDIT_TIME_MAX, spec);
  4900. }
  4901. QString QDateTimeParser::getAmPmText(AmPm ap, Case cs) const
  4902. {
  4903. if (ap == AmText) {
  4904. return (cs == UpperCase ? QLatin1String("AM") : QLatin1String("am"));
  4905. } else {
  4906. return (cs == UpperCase ? QLatin1String("PM") : QLatin1String("pm"));
  4907. }
  4908. }
  4909. /*
  4910. \internal
  4911. I give arg2 preference because arg1 is always a QDateTime.
  4912. */
  4913. bool operator==(const QDateTimeParser::SectionNode &s1, const QDateTimeParser::SectionNode &s2)
  4914. {
  4915. return (s1.type == s2.type) && (s1.pos == s2.pos) && (s1.count == s2.count);
  4916. }
  4917. #endif // QT_BOOTSTRAPPED
  4918. QT_END_NAMESPACE