PageRenderTime 93ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 1ms

/src/corelib/tools/qdatetime.cpp

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