PageRenderTime 77ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 1ms

/src/corelib/tools/qdatetime.cpp

https://bitbucket.org/ottoshmidt/qtbase
C++ | 5865 lines | 3215 code | 551 blank | 2099 comment | 929 complexity | 048e1a64d4221eb88f15be8d614e9c94 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, CC0-1.0, LGPL-3.0, CC-BY-SA-4.0, GPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the QtCore module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and Digia. For licensing terms and
  14. ** conditions see http://qt.digia.com/licensing. For further information
  15. ** use the contact form at http://qt.digia.com/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 2.1 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 2.1 requirements
  23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24. **
  25. ** In addition, as a special exception, Digia gives you certain additional
  26. ** rights. These rights are described in the Digia Qt LGPL Exception
  27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28. **
  29. ** GNU General Public License Usage
  30. ** Alternatively, this file may be used under the terms of the GNU
  31. ** General Public License version 3.0 as published by the Free Software
  32. ** Foundation and appearing in the file LICENSE.GPL included in the
  33. ** packaging of this file. Please review the following information to
  34. ** ensure the GNU General Public License version 3.0 requirements will be
  35. ** met: http://www.gnu.org/copyleft/gpl.html.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qplatformdefs.h"
  42. #include "private/qdatetime_p.h"
  43. #include "qdatastream.h"
  44. #include "qset.h"
  45. #include "qlocale.h"
  46. #include "qdatetime.h"
  47. #include "qregexp.h"
  48. #include "qdebug.h"
  49. #ifndef Q_OS_WIN
  50. #include <locale.h>
  51. #endif
  52. #include <cmath>
  53. #include <time.h>
  54. #ifdef Q_OS_WIN
  55. # include <qt_windows.h>
  56. # ifdef Q_OS_WINCE
  57. # include "qfunctions_wince.h"
  58. # endif
  59. #endif
  60. //#define QDATETIMEPARSER_DEBUG
  61. #if defined (QDATETIMEPARSER_DEBUG) && !defined(QT_NO_DEBUG_STREAM)
  62. # define QDTPDEBUG qDebug() << QString("%1:%2").arg(__FILE__).arg(__LINE__)
  63. # define QDTPDEBUGN qDebug
  64. #else
  65. # define QDTPDEBUG if (false) qDebug()
  66. # define QDTPDEBUGN if (false) qDebug
  67. #endif
  68. #if defined(Q_OS_MAC)
  69. #include <private/qcore_mac_p.h>
  70. #endif
  71. QT_BEGIN_NAMESPACE
  72. enum {
  73. SECS_PER_DAY = 86400,
  74. MSECS_PER_DAY = 86400000,
  75. SECS_PER_HOUR = 3600,
  76. MSECS_PER_HOUR = 3600000,
  77. SECS_PER_MIN = 60,
  78. MSECS_PER_MIN = 60000,
  79. JULIAN_DAY_FOR_EPOCH = 2440588 // result of julianDayFromDate(1970, 1, 1)
  80. };
  81. static inline QDate fixedDate(int y, int m, int d)
  82. {
  83. QDate result(y, m, 1);
  84. result.setDate(y, m, qMin(d, result.daysInMonth()));
  85. return result;
  86. }
  87. static inline qint64 floordiv(qint64 a, qint64 b)
  88. {
  89. return (a - (a < 0 ? b-1 : 0)) / b;
  90. }
  91. static inline qint64 floordiv(qint64 a, int b)
  92. {
  93. return (a - (a < 0 ? b-1 : 0)) / b;
  94. }
  95. static inline int floordiv(int a, int b)
  96. {
  97. return (a - (a < 0 ? b-1 : 0)) / b;
  98. }
  99. static inline qint64 julianDayFromDate(int year, int month, int day)
  100. {
  101. // Adjust for no year 0
  102. if (year < 0)
  103. ++year;
  104. /*
  105. * Math from The Calendar FAQ at http://www.tondering.dk/claus/cal/julperiod.php
  106. * This formula is correct for all julian days, when using mathematical integer
  107. * division (round to negative infinity), not c++11 integer division (round to zero)
  108. */
  109. int a = floordiv(14 - month, 12);
  110. qint64 y = (qint64)year + 4800 - a;
  111. int m = month + 12 * a - 3;
  112. return day + floordiv(153 * m + 2, 5) + 365 * y + floordiv(y, 4) - floordiv(y, 100) + floordiv(y, 400) - 32045;
  113. }
  114. static void getDateFromJulianDay(qint64 julianDay, int *yearp, int *monthp, int *dayp)
  115. {
  116. /*
  117. * Math from The Calendar FAQ at http://www.tondering.dk/claus/cal/julperiod.php
  118. * This formula is correct for all julian days, when using mathematical integer
  119. * division (round to negative infinity), not c++11 integer division (round to zero)
  120. */
  121. qint64 a = julianDay + 32044;
  122. qint64 b = floordiv(4 * a + 3, 146097);
  123. int c = a - floordiv(146097 * b, 4);
  124. int d = floordiv(4 * c + 3, 1461);
  125. int e = c - floordiv(1461 * d, 4);
  126. int m = floordiv(5 * e + 2, 153);
  127. int day = e - floordiv(153 * m + 2, 5) + 1;
  128. int month = m + 3 - 12 * floordiv(m, 10);
  129. int year = 100 * b + d - 4800 + floordiv(m, 10);
  130. // Adjust for no year 0
  131. if (year <= 0)
  132. --year ;
  133. if (yearp)
  134. *yearp = year;
  135. if (monthp)
  136. *monthp = month;
  137. if (dayp)
  138. *dayp = day;
  139. }
  140. static const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  141. #ifndef QT_NO_TEXTDATE
  142. static const char * const qt_shortMonthNames[] = {
  143. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  144. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  145. #endif
  146. #ifndef QT_NO_DATESTRING
  147. static QString fmtDateTime(const QString& f, const QTime* dt = 0, const QDate* dd = 0);
  148. #endif
  149. /*****************************************************************************
  150. QDate member functions
  151. *****************************************************************************/
  152. /*!
  153. \since 4.5
  154. \enum QDate::MonthNameType
  155. This enum describes the types of the string representation used
  156. for the month name.
  157. \value DateFormat This type of name can be used for date-to-string formatting.
  158. \value StandaloneFormat This type is used when you need to enumerate months or weekdays.
  159. Usually standalone names are represented in singular forms with
  160. capitalized first letter.
  161. */
  162. /*!
  163. \class QDate
  164. \inmodule QtCore
  165. \reentrant
  166. \brief The QDate class provides date functions.
  167. A QDate object contains a calendar date, i.e. year, month, and day
  168. numbers, in the Gregorian calendar. It can read the current date
  169. from the system clock. It provides functions for comparing dates,
  170. and for manipulating dates. For example, it is possible to add
  171. and subtract days, months, and years to dates.
  172. A QDate object is typically created by giving the year,
  173. month, and day numbers explicitly. Note that QDate interprets two
  174. digit years as is, i.e., years 0 - 99. A QDate can also be
  175. constructed with the static function currentDate(), which creates
  176. a QDate object containing the system clock's date. An explicit
  177. date can also be set using setDate(). The fromString() function
  178. returns a QDate given a string and a date format which is used to
  179. interpret the date within the string.
  180. The year(), month(), and day() functions provide access to the
  181. year, month, and day numbers. Also, dayOfWeek() and dayOfYear()
  182. functions are provided. The same information is provided in
  183. textual format by the toString(), shortDayName(), longDayName(),
  184. shortMonthName(), and longMonthName() functions.
  185. QDate provides a full set of operators to compare two QDate
  186. objects where smaller means earlier, and larger means later.
  187. You can increment (or decrement) a date by a given number of days
  188. using addDays(). Similarly you can use addMonths() and addYears().
  189. The daysTo() function returns the number of days between two
  190. dates.
  191. The daysInMonth() and daysInYear() functions return how many days
  192. there are in this date's month and year, respectively. The
  193. isLeapYear() function indicates whether a date is in a leap year.
  194. \section1
  195. \section2 No Year 0
  196. There is no year 0. Dates in that year are considered invalid. The
  197. year -1 is the year "1 before Christ" or "1 before current era."
  198. The day before 1 January 1 CE is 31 December 1 BCE.
  199. \section2 Range of Valid Dates
  200. Dates are stored internally as a Julian Day number, an integer count of
  201. every day in a contiguous range, with 24 November 4714 BCE in the Gregorian
  202. calendar being Julian Day 0 (1 January 4713 BCE in the Julian calendar).
  203. As well as being an efficient and accurate way of storing an absolute date,
  204. it is suitable for converting a Date into other calendar systems such as
  205. Hebrew, Islamic or Chinese. The Julian Day number can be obtained using
  206. QDate::toJulianDay() and can be set using QDate::fromJulianDay().
  207. The range of dates able to be stored by QDate as a Julian Day number is
  208. for technical reasons limited to between -784350574879 and 784354017364,
  209. which means from before 2 billion BCE to after 2 billion CE.
  210. \sa QTime, QDateTime, QDateEdit, QDateTimeEdit, QCalendarWidget
  211. */
  212. /*!
  213. \fn QDate::QDate()
  214. Constructs a null date. Null dates are invalid.
  215. \sa isNull(), isValid()
  216. */
  217. /*!
  218. Constructs a date with year \a y, month \a m and day \a d.
  219. If the specified date is invalid, the date is not set and
  220. isValid() returns false.
  221. \warning Years 0 to 99 are interpreted as is, i.e., years
  222. 0-99.
  223. \sa isValid()
  224. */
  225. QDate::QDate(int y, int m, int d)
  226. {
  227. setDate(y, m, d);
  228. }
  229. /*!
  230. \fn bool QDate::isNull() const
  231. Returns true if the date is null; otherwise returns false. A null
  232. date is invalid.
  233. \note The behavior of this function is equivalent to isValid().
  234. \sa isValid()
  235. */
  236. /*!
  237. \fn bool QDate::isValid() const
  238. Returns true if this date is valid; otherwise returns false.
  239. \sa isNull()
  240. */
  241. /*!
  242. Returns the year of this date. Negative numbers indicate years
  243. before 1 CE, such that year -44 is 44 BCE.
  244. Returns 0 if the date is invalid.
  245. \sa month(), day()
  246. */
  247. int QDate::year() const
  248. {
  249. if (isNull())
  250. return 0;
  251. int y;
  252. getDateFromJulianDay(jd, &y, 0, 0);
  253. return y;
  254. }
  255. /*!
  256. Returns the number corresponding to the month of this date, using
  257. the following convention:
  258. \list
  259. \li 1 = "January"
  260. \li 2 = "February"
  261. \li 3 = "March"
  262. \li 4 = "April"
  263. \li 5 = "May"
  264. \li 6 = "June"
  265. \li 7 = "July"
  266. \li 8 = "August"
  267. \li 9 = "September"
  268. \li 10 = "October"
  269. \li 11 = "November"
  270. \li 12 = "December"
  271. \endlist
  272. Returns 0 if the date is invalid.
  273. \sa year(), day()
  274. */
  275. int QDate::month() const
  276. {
  277. if (isNull())
  278. return 0;
  279. int m;
  280. getDateFromJulianDay(jd, 0, &m, 0);
  281. return m;
  282. }
  283. /*!
  284. Returns the day of the month (1 to 31) of this date.
  285. Returns 0 if the date is invalid.
  286. \sa year(), month(), dayOfWeek()
  287. */
  288. int QDate::day() const
  289. {
  290. if (isNull())
  291. return 0;
  292. int d;
  293. getDateFromJulianDay(jd, 0, 0, &d);
  294. return d;
  295. }
  296. /*!
  297. Returns the weekday (1 = Monday to 7 = Sunday) for this date.
  298. Returns 0 if the date is invalid.
  299. \sa day(), dayOfYear(), Qt::DayOfWeek
  300. */
  301. int QDate::dayOfWeek() const
  302. {
  303. if (isNull())
  304. return 0;
  305. if (jd >= 0)
  306. return (jd % 7) + 1;
  307. else
  308. return ((jd + 1) % 7) + 7;
  309. }
  310. /*!
  311. Returns the day of the year (1 to 365 or 366 on leap years) for
  312. this date.
  313. Returns 0 if the date is invalid.
  314. \sa day(), dayOfWeek()
  315. */
  316. int QDate::dayOfYear() const
  317. {
  318. if (isNull())
  319. return 0;
  320. return jd - julianDayFromDate(year(), 1, 1) + 1;
  321. }
  322. /*!
  323. Returns the number of days in the month (28 to 31) for this date.
  324. Returns 0 if the date is invalid.
  325. \sa day(), daysInYear()
  326. */
  327. int QDate::daysInMonth() const
  328. {
  329. if (isNull())
  330. return 0;
  331. int y, m;
  332. getDateFromJulianDay(jd, &y, &m, 0);
  333. if (m == 2 && isLeapYear(y))
  334. return 29;
  335. else
  336. return monthDays[m];
  337. }
  338. /*!
  339. Returns the number of days in the year (365 or 366) for this date.
  340. Returns 0 if the date is invalid.
  341. \sa day(), daysInMonth()
  342. */
  343. int QDate::daysInYear() const
  344. {
  345. if (isNull())
  346. return 0;
  347. int y;
  348. getDateFromJulianDay(jd, &y, 0, 0);
  349. return isLeapYear(y) ? 366 : 365;
  350. }
  351. /*!
  352. Returns the week number (1 to 53), and stores the year in
  353. *\a{yearNumber} unless \a yearNumber is null (the default).
  354. Returns 0 if the date is invalid.
  355. In accordance with ISO 8601, weeks start on Monday and the first
  356. Thursday of a year is always in week 1 of that year. Most years
  357. have 52 weeks, but some have 53.
  358. *\a{yearNumber} is not always the same as year(). For example, 1
  359. January 2000 has week number 52 in the year 1999, and 31 December
  360. 2002 has week number 1 in the year 2003.
  361. \legalese
  362. Copyright (c) 1989 The Regents of the University of California.
  363. All rights reserved.
  364. Redistribution and use in source and binary forms are permitted
  365. provided that the above copyright notice and this paragraph are
  366. duplicated in all such forms and that any documentation,
  367. advertising materials, and other materials related to such
  368. distribution and use acknowledge that the software was developed
  369. by the University of California, Berkeley. The name of the
  370. University may not be used to endorse or promote products derived
  371. from this software without specific prior written permission.
  372. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
  373. IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  374. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  375. \sa isValid()
  376. */
  377. int QDate::weekNumber(int *yearNumber) const
  378. {
  379. if (!isValid())
  380. return 0;
  381. int year = QDate::year();
  382. int yday = dayOfYear() - 1;
  383. int wday = dayOfWeek();
  384. if (wday == 7)
  385. wday = 0;
  386. int w;
  387. for (;;) {
  388. int len;
  389. int bot;
  390. int top;
  391. len = isLeapYear(year) ? 366 : 365;
  392. /*
  393. ** What yday (-3 ... 3) does
  394. ** the ISO year begin on?
  395. */
  396. bot = ((yday + 11 - wday) % 7) - 3;
  397. /*
  398. ** What yday does the NEXT
  399. ** ISO year begin on?
  400. */
  401. top = bot - (len % 7);
  402. if (top < -3)
  403. top += 7;
  404. top += len;
  405. if (yday >= top) {
  406. ++year;
  407. w = 1;
  408. break;
  409. }
  410. if (yday >= bot) {
  411. w = 1 + ((yday - bot) / 7);
  412. break;
  413. }
  414. --year;
  415. yday += isLeapYear(year) ? 366 : 365;
  416. }
  417. if (yearNumber != 0)
  418. *yearNumber = year;
  419. return w;
  420. }
  421. #ifndef QT_NO_TEXTDATE
  422. /*!
  423. \since 4.5
  424. Returns the short name of the \a month for the representation specified
  425. by \a type.
  426. The months are enumerated using the following convention:
  427. \list
  428. \li 1 = "Jan"
  429. \li 2 = "Feb"
  430. \li 3 = "Mar"
  431. \li 4 = "Apr"
  432. \li 5 = "May"
  433. \li 6 = "Jun"
  434. \li 7 = "Jul"
  435. \li 8 = "Aug"
  436. \li 9 = "Sep"
  437. \li 10 = "Oct"
  438. \li 11 = "Nov"
  439. \li 12 = "Dec"
  440. \endlist
  441. The month names will be localized according to the system's locale
  442. settings.
  443. Returns an empty string if the date is invalid.
  444. \sa toString(), longMonthName(), shortDayName(), longDayName()
  445. */
  446. QString QDate::shortMonthName(int month, QDate::MonthNameType type)
  447. {
  448. if (month < 1 || month > 12)
  449. return QString();
  450. switch (type) {
  451. case QDate::DateFormat:
  452. return QLocale::system().monthName(month, QLocale::ShortFormat);
  453. case QDate::StandaloneFormat:
  454. return QLocale::system().standaloneMonthName(month, QLocale::ShortFormat);
  455. default:
  456. break;
  457. }
  458. return QString();
  459. }
  460. /*!
  461. \since 4.5
  462. Returns the long name of the \a month for the representation specified
  463. by \a type.
  464. The months are enumerated using the following convention:
  465. \list
  466. \li 1 = "January"
  467. \li 2 = "February"
  468. \li 3 = "March"
  469. \li 4 = "April"
  470. \li 5 = "May"
  471. \li 6 = "June"
  472. \li 7 = "July"
  473. \li 8 = "August"
  474. \li 9 = "September"
  475. \li 10 = "October"
  476. \li 11 = "November"
  477. \li 12 = "December"
  478. \endlist
  479. The month names will be localized according to the system's locale
  480. settings.
  481. Returns an empty string if the date is invalid.
  482. \sa toString(), shortMonthName(), shortDayName(), longDayName()
  483. */
  484. QString QDate::longMonthName(int month, MonthNameType type)
  485. {
  486. if (month < 1 || month > 12)
  487. return QString();
  488. switch (type) {
  489. case QDate::DateFormat:
  490. return QLocale::system().monthName(month, QLocale::LongFormat);
  491. case QDate::StandaloneFormat:
  492. return QLocale::system().standaloneMonthName(month, QLocale::LongFormat);
  493. default:
  494. break;
  495. }
  496. return QString();
  497. }
  498. /*!
  499. \since 4.5
  500. Returns the short name of the \a weekday for the representation specified
  501. by \a type.
  502. The days are enumerated using the following convention:
  503. \list
  504. \li 1 = "Mon"
  505. \li 2 = "Tue"
  506. \li 3 = "Wed"
  507. \li 4 = "Thu"
  508. \li 5 = "Fri"
  509. \li 6 = "Sat"
  510. \li 7 = "Sun"
  511. \endlist
  512. The day names will be localized according to the system's locale
  513. settings.
  514. Returns an empty string if the date is invalid.
  515. \sa toString(), shortMonthName(), longMonthName(), longDayName()
  516. */
  517. QString QDate::shortDayName(int weekday, MonthNameType type)
  518. {
  519. if (weekday < 1 || weekday > 7)
  520. return QString();
  521. switch (type) {
  522. case QDate::DateFormat:
  523. return QLocale::system().dayName(weekday, QLocale::ShortFormat);
  524. case QDate::StandaloneFormat:
  525. return QLocale::system().standaloneDayName(weekday, QLocale::ShortFormat);
  526. default:
  527. break;
  528. }
  529. return QString();
  530. }
  531. /*!
  532. \since 4.5
  533. Returns the long name of the \a weekday for the representation specified
  534. by \a type.
  535. The days are enumerated using the following convention:
  536. \list
  537. \li 1 = "Monday"
  538. \li 2 = "Tuesday"
  539. \li 3 = "Wednesday"
  540. \li 4 = "Thursday"
  541. \li 5 = "Friday"
  542. \li 6 = "Saturday"
  543. \li 7 = "Sunday"
  544. \endlist
  545. The day names will be localized according to the system's locale
  546. settings.
  547. Returns an empty string if the date is invalid.
  548. \sa toString(), shortDayName(), shortMonthName(), longMonthName()
  549. */
  550. QString QDate::longDayName(int weekday, MonthNameType type)
  551. {
  552. if (weekday < 1 || weekday > 7)
  553. return QString();
  554. switch (type) {
  555. case QDate::DateFormat:
  556. return QLocale::system().dayName(weekday, QLocale::LongFormat);
  557. case QDate::StandaloneFormat:
  558. return QLocale::system().standaloneDayName(weekday, QLocale::LongFormat);
  559. default:
  560. break;
  561. }
  562. return QLocale::system().dayName(weekday, QLocale::LongFormat);
  563. }
  564. #endif //QT_NO_TEXTDATE
  565. #ifndef QT_NO_DATESTRING
  566. /*!
  567. \fn QString QDate::toString(Qt::DateFormat format) const
  568. \overload
  569. Returns the date as a string. The \a format parameter determines
  570. the format of the string.
  571. If the \a format is Qt::TextDate, the string is formatted in
  572. the default way. QDate::shortDayName() and QDate::shortMonthName()
  573. are used to generate the string, so the day and month names will
  574. be localized names. An example of this formatting is
  575. "Sat May 20 1995".
  576. If the \a format is Qt::ISODate, the string format corresponds
  577. to the ISO 8601 extended specification for representations of
  578. dates and times, taking the form YYYY-MM-DD, where YYYY is the
  579. year, MM is the month of the year (between 01 and 12), and DD is
  580. the day of the month between 01 and 31.
  581. If the \a format is Qt::SystemLocaleShortDate or
  582. Qt::SystemLocaleLongDate, the string format depends on the locale
  583. settings of the system. Identical to calling
  584. QLocale::system().toString(date, QLocale::ShortFormat) or
  585. QLocale::system().toString(date, QLocale::LongFormat).
  586. If the \a format is Qt::DefaultLocaleShortDate or
  587. Qt::DefaultLocaleLongDate, the string format depends on the
  588. default application locale. This is the locale set with
  589. QLocale::setDefault(), or the system locale if no default locale
  590. has been set. Identical to calling QLocale().toString(date,
  591. QLocale::ShortFormat) or QLocale().toString(date,
  592. QLocale::LongFormat).
  593. If the date is invalid, an empty string will be returned.
  594. \warning The Qt::ISODate format is only valid for years in the
  595. range 0 to 9999. This restriction may apply to locale-aware
  596. formats as well, depending on the locale settings.
  597. \sa shortDayName(), shortMonthName()
  598. */
  599. QString QDate::toString(Qt::DateFormat f) const
  600. {
  601. if (!isValid())
  602. return QString();
  603. int y, m, d;
  604. getDateFromJulianDay(jd, &y, &m, &d);
  605. switch (f) {
  606. case Qt::SystemLocaleDate:
  607. case Qt::SystemLocaleShortDate:
  608. case Qt::SystemLocaleLongDate:
  609. return QLocale::system().toString(*this, f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  610. : QLocale::ShortFormat);
  611. case Qt::LocaleDate:
  612. case Qt::DefaultLocaleShortDate:
  613. case Qt::DefaultLocaleLongDate:
  614. return QLocale().toString(*this, f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  615. : QLocale::ShortFormat);
  616. default:
  617. #ifndef QT_NO_TEXTDATE
  618. case Qt::TextDate:
  619. {
  620. return QString::fromLatin1("%0 %1 %2 %3")
  621. .arg(shortDayName(dayOfWeek()))
  622. .arg(shortMonthName(m))
  623. .arg(d)
  624. .arg(y);
  625. }
  626. #endif
  627. case Qt::ISODate:
  628. {
  629. if (year() < 0 || year() > 9999)
  630. return QString();
  631. QString year(QString::number(y).rightJustified(4, QLatin1Char('0')));
  632. QString month(QString::number(m).rightJustified(2, QLatin1Char('0')));
  633. QString day(QString::number(d).rightJustified(2, QLatin1Char('0')));
  634. return year + QLatin1Char('-') + month + QLatin1Char('-') + day;
  635. }
  636. }
  637. }
  638. /*!
  639. Returns the date as a string. The \a format parameter determines
  640. the format of the result string.
  641. These expressions may be used:
  642. \table
  643. \header \li Expression \li Output
  644. \row \li d \li the day as number without a leading zero (1 to 31)
  645. \row \li dd \li the day as number with a leading zero (01 to 31)
  646. \row \li ddd
  647. \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
  648. Uses QDate::shortDayName().
  649. \row \li dddd
  650. \li the long localized day name (e.g. 'Monday' to 'Sunday').
  651. Uses QDate::longDayName().
  652. \row \li M \li the month as number without a leading zero (1 to 12)
  653. \row \li MM \li the month as number with a leading zero (01 to 12)
  654. \row \li MMM
  655. \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
  656. Uses QDate::shortMonthName().
  657. \row \li MMMM
  658. \li the long localized month name (e.g. 'January' to 'December').
  659. Uses QDate::longMonthName().
  660. \row \li yy \li the year as two digit number (00 to 99)
  661. \row \li yyyy \li the year as four digit number. If the year is negative,
  662. a minus sign is prepended in addition.
  663. \endtable
  664. All other input characters will be ignored. Any sequence of characters that
  665. are enclosed in single quotes will be treated as text and not be used as an
  666. expression. Two consecutive single quotes ("''") are replaced by a singlequote
  667. in the output. Formats without separators (e.g. "ddMM") are currently not supported.
  668. Example format strings (assuming that the QDate is the 20 July
  669. 1969):
  670. \table
  671. \header \li Format \li Result
  672. \row \li dd.MM.yyyy \li 20.07.1969
  673. \row \li ddd MMMM d yy \li Sun July 20 69
  674. \row \li 'The day is' dddd \li The day is Sunday
  675. \endtable
  676. If the datetime is invalid, an empty string will be returned.
  677. \warning The Qt::ISODate format is only valid for years in the
  678. range 0 to 9999. This restriction may apply to locale-aware
  679. formats as well, depending on the locale settings.
  680. \sa QDateTime::toString(), QTime::toString()
  681. */
  682. QString QDate::toString(const QString& format) const
  683. {
  684. if (year() > 9999)
  685. return QString();
  686. return fmtDateTime(format, 0, this);
  687. }
  688. #endif //QT_NO_DATESTRING
  689. /*!
  690. \fn bool QDate::setYMD(int y, int m, int d)
  691. \deprecated in 5.0, use setDate() instead.
  692. Sets the date's year \a y, month \a m, and day \a d.
  693. If \a y is in the range 0 to 99, it is interpreted as 1900 to
  694. 1999.
  695. Returns \c false if the date is invalid.
  696. Use setDate() instead.
  697. */
  698. /*!
  699. \since 4.2
  700. Sets the date's \a year, \a month, and \a day. Returns true if
  701. the date is valid; otherwise returns false.
  702. If the specified date is invalid, the QDate object is set to be
  703. invalid.
  704. \sa isValid()
  705. */
  706. bool QDate::setDate(int year, int month, int day)
  707. {
  708. if (isValid(year, month, day))
  709. jd = julianDayFromDate(year, month, day);
  710. else
  711. jd = nullJd();
  712. return isValid();
  713. }
  714. /*!
  715. \since 4.5
  716. Extracts the date's year, month, and day, and assigns them to
  717. *\a year, *\a month, and *\a day. The pointers may be null.
  718. Returns 0 if the date is invalid.
  719. \sa year(), month(), day(), isValid()
  720. */
  721. void QDate::getDate(int *year, int *month, int *day)
  722. {
  723. if (isValid()) {
  724. getDateFromJulianDay(jd, year, month, day);
  725. } else {
  726. if (year)
  727. *year = 0;
  728. if (month)
  729. *month = 0;
  730. if (day)
  731. *day = 0;
  732. }
  733. }
  734. /*!
  735. Returns a QDate object containing a date \a ndays later than the
  736. date of this object (or earlier if \a ndays is negative).
  737. Returns a null date if the current date is invalid or the new date is
  738. out of range.
  739. \sa addMonths(), addYears(), daysTo()
  740. */
  741. QDate QDate::addDays(qint64 ndays) const
  742. {
  743. if (isNull())
  744. return QDate();
  745. // Due to limits on minJd() and maxJd() we know that any overflow
  746. // will be invalid and caught by fromJulianDay().
  747. return fromJulianDay(jd + ndays);
  748. }
  749. /*!
  750. Returns a QDate object containing a date \a nmonths later than the
  751. date of this object (or earlier if \a nmonths is negative).
  752. \note If the ending day/month combination does not exist in the
  753. resulting month/year, this function will return a date that is the
  754. latest valid date.
  755. \sa addDays(), addYears()
  756. */
  757. QDate QDate::addMonths(int nmonths) const
  758. {
  759. if (!isValid())
  760. return QDate();
  761. if (!nmonths)
  762. return *this;
  763. int old_y, y, m, d;
  764. getDateFromJulianDay(jd, &y, &m, &d);
  765. old_y = y;
  766. bool increasing = nmonths > 0;
  767. while (nmonths != 0) {
  768. if (nmonths < 0 && nmonths + 12 <= 0) {
  769. y--;
  770. nmonths+=12;
  771. } else if (nmonths < 0) {
  772. m+= nmonths;
  773. nmonths = 0;
  774. if (m <= 0) {
  775. --y;
  776. m += 12;
  777. }
  778. } else if (nmonths - 12 >= 0) {
  779. y++;
  780. nmonths -= 12;
  781. } else if (m == 12) {
  782. y++;
  783. m = 0;
  784. } else {
  785. m += nmonths;
  786. nmonths = 0;
  787. if (m > 12) {
  788. ++y;
  789. m -= 12;
  790. }
  791. }
  792. }
  793. // was there a sign change?
  794. if ((old_y > 0 && y <= 0) ||
  795. (old_y < 0 && y >= 0))
  796. // yes, adjust the date by +1 or -1 years
  797. y += increasing ? +1 : -1;
  798. return fixedDate(y, m, d);
  799. }
  800. /*!
  801. Returns a QDate object containing a date \a nyears later than the
  802. date of this object (or earlier if \a nyears is negative).
  803. \note If the ending day/month combination does not exist in the
  804. resulting year (i.e., if the date was Feb 29 and the final year is
  805. not a leap year), this function will return a date that is the
  806. latest valid date (that is, Feb 28).
  807. \sa addDays(), addMonths()
  808. */
  809. QDate QDate::addYears(int nyears) const
  810. {
  811. if (!isValid())
  812. return QDate();
  813. int y, m, d;
  814. getDateFromJulianDay(jd, &y, &m, &d);
  815. int old_y = y;
  816. y += nyears;
  817. // was there a sign change?
  818. if ((old_y > 0 && y <= 0) ||
  819. (old_y < 0 && y >= 0))
  820. // yes, adjust the date by +1 or -1 years
  821. y += nyears > 0 ? +1 : -1;
  822. return fixedDate(y, m, d);
  823. }
  824. /*!
  825. Returns the number of days from this date to \a d (which is
  826. negative if \a d is earlier than this date).
  827. Returns 0 if either date is invalid.
  828. Example:
  829. \snippet code/src_corelib_tools_qdatetime.cpp 0
  830. \sa addDays()
  831. */
  832. qint64 QDate::daysTo(const QDate &d) const
  833. {
  834. if (isNull() || d.isNull())
  835. return 0;
  836. // Due to limits on minJd() and maxJd() we know this will never overflow
  837. return d.jd - jd;
  838. }
  839. /*!
  840. \fn bool QDate::operator==(const QDate &d) const
  841. Returns true if this date is equal to \a d; otherwise returns
  842. false.
  843. */
  844. /*!
  845. \fn bool QDate::operator!=(const QDate &d) const
  846. Returns true if this date is different from \a d; otherwise
  847. returns false.
  848. */
  849. /*!
  850. \fn bool QDate::operator<(const QDate &d) const
  851. Returns true if this date is earlier than \a d; otherwise returns
  852. false.
  853. */
  854. /*!
  855. \fn bool QDate::operator<=(const QDate &d) const
  856. Returns true if this date is earlier than or equal to \a d;
  857. otherwise returns false.
  858. */
  859. /*!
  860. \fn bool QDate::operator>(const QDate &d) const
  861. Returns true if this date is later than \a d; otherwise returns
  862. false.
  863. */
  864. /*!
  865. \fn bool QDate::operator>=(const QDate &d) const
  866. Returns true if this date is later than or equal to \a d;
  867. otherwise returns false.
  868. */
  869. /*!
  870. \fn QDate::currentDate()
  871. Returns the current date, as reported by the system clock.
  872. \sa QTime::currentTime(), QDateTime::currentDateTime()
  873. */
  874. #ifndef QT_NO_DATESTRING
  875. /*!
  876. \fn QDate QDate::fromString(const QString &string, Qt::DateFormat format)
  877. Returns the QDate represented by the \a string, using the
  878. \a format given, or an invalid date if the string cannot be
  879. parsed.
  880. Note for Qt::TextDate: It is recommended that you use the
  881. English short month names (e.g. "Jan"). Although localized month
  882. names can also be used, they depend on the user's locale settings.
  883. */
  884. QDate QDate::fromString(const QString& s, Qt::DateFormat f)
  885. {
  886. if (s.isEmpty())
  887. return QDate();
  888. switch (f) {
  889. case Qt::ISODate:
  890. {
  891. int year(s.mid(0, 4).toInt());
  892. int month(s.mid(5, 2).toInt());
  893. int day(s.mid(8, 2).toInt());
  894. if (year && month && day)
  895. return QDate(year, month, day);
  896. }
  897. break;
  898. case Qt::SystemLocaleDate:
  899. case Qt::SystemLocaleShortDate:
  900. case Qt::SystemLocaleLongDate:
  901. return fromString(s, QLocale::system().dateFormat(f == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  902. : QLocale::ShortFormat));
  903. case Qt::LocaleDate:
  904. case Qt::DefaultLocaleShortDate:
  905. case Qt::DefaultLocaleLongDate:
  906. return fromString(s, QLocale().dateFormat(f == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  907. : QLocale::ShortFormat));
  908. default:
  909. #ifndef QT_NO_TEXTDATE
  910. case Qt::TextDate: {
  911. QStringList parts = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
  912. if (parts.count() != 4) {
  913. return QDate();
  914. }
  915. QString monthName = parts.at(1);
  916. int month = -1;
  917. // Assume that English monthnames are the default
  918. for (int i = 0; i < 12; ++i) {
  919. if (monthName == QLatin1String(qt_shortMonthNames[i])) {
  920. month = i + 1;
  921. break;
  922. }
  923. }
  924. // If English names can't be found, search the localized ones
  925. if (month == -1) {
  926. for (int i = 1; i <= 12; ++i) {
  927. if (monthName == QDate::shortMonthName(i)) {
  928. month = i;
  929. break;
  930. }
  931. }
  932. if (month == -1) {
  933. // Month name matches neither English nor other localised name.
  934. return QDate();
  935. }
  936. }
  937. bool ok;
  938. int day = parts.at(2).toInt(&ok);
  939. if (!ok) {
  940. return QDate();
  941. }
  942. int year = parts.at(3).toInt(&ok);
  943. if (!ok) {
  944. return QDate();
  945. }
  946. return QDate(year, month, day);
  947. }
  948. #else
  949. break;
  950. #endif
  951. }
  952. return QDate();
  953. }
  954. /*!
  955. \fn QDate::fromString(const QString &string, const QString &format)
  956. Returns the QDate represented by the \a string, using the \a
  957. format given, or an invalid date if the string cannot be parsed.
  958. These expressions may be used for the format:
  959. \table
  960. \header \li Expression \li Output
  961. \row \li d \li The day as a number without a leading zero (1 to 31)
  962. \row \li dd \li The day as a number with a leading zero (01 to 31)
  963. \row \li ddd
  964. \li The abbreviated localized day name (e.g. 'Mon' to 'Sun').
  965. Uses QDate::shortDayName().
  966. \row \li dddd
  967. \li The long localized day name (e.g. 'Monday' to 'Sunday').
  968. Uses QDate::longDayName().
  969. \row \li M \li The month as a number without a leading zero (1 to 12)
  970. \row \li MM \li The month as a number with a leading zero (01 to 12)
  971. \row \li MMM
  972. \li The abbreviated localized month name (e.g. 'Jan' to 'Dec').
  973. Uses QDate::shortMonthName().
  974. \row \li MMMM
  975. \li The long localized month name (e.g. 'January' to 'December').
  976. Uses QDate::longMonthName().
  977. \row \li yy \li The year as two digit number (00 to 99)
  978. \row \li yyyy \li The year as four digit number. If the year is negative,
  979. a minus sign is prepended in addition.
  980. \endtable
  981. All other input characters will be treated as text. Any sequence
  982. of characters that are enclosed in single quotes will also be
  983. treated as text and will not be used as an expression. For example:
  984. \snippet code/src_corelib_tools_qdatetime.cpp 1
  985. If the format is not satisfied, an invalid QDate is returned. The
  986. expressions that don't expect leading zeroes (d, M) will be
  987. greedy. This means that they will use two digits even if this
  988. will put them outside the accepted range of values and leaves too
  989. few digits for other sections. For example, the following format
  990. string could have meant January 30 but the M will grab two
  991. digits, resulting in an invalid date:
  992. \snippet code/src_corelib_tools_qdatetime.cpp 2
  993. For any field that is not represented in the format the following
  994. defaults are used:
  995. \table
  996. \header \li Field \li Default value
  997. \row \li Year \li 1900
  998. \row \li Month \li 1
  999. \row \li Day \li 1
  1000. \endtable
  1001. The following examples demonstrate the default values:
  1002. \snippet code/src_corelib_tools_qdatetime.cpp 3
  1003. \sa QDateTime::fromString(), QTime::fromString(), QDate::toString(),
  1004. QDateTime::toString(), QTime::toString()
  1005. */
  1006. QDate QDate::fromString(const QString &string, const QString &format)
  1007. {
  1008. QDate date;
  1009. #ifndef QT_BOOTSTRAPPED
  1010. QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString);
  1011. if (dt.parseFormat(format))
  1012. dt.fromString(string, &date, 0);
  1013. #else
  1014. Q_UNUSED(string);
  1015. Q_UNUSED(format);
  1016. #endif
  1017. return date;
  1018. }
  1019. #endif // QT_NO_DATESTRING
  1020. /*!
  1021. \overload
  1022. Returns true if the specified date (\a year, \a month, and \a
  1023. day) is valid; otherwise returns false.
  1024. Example:
  1025. \snippet code/src_corelib_tools_qdatetime.cpp 4
  1026. \sa isNull(), setDate()
  1027. */
  1028. bool QDate::isValid(int year, int month, int day)
  1029. {
  1030. // there is no year 0 in the Gregorian calendar
  1031. if (year == 0)
  1032. return false;
  1033. return (day > 0 && month > 0 && month <= 12) &&
  1034. (day <= monthDays[month] || (day == 29 && month == 2 && isLeapYear(year)));
  1035. }
  1036. /*!
  1037. \fn bool QDate::isLeapYear(int year)
  1038. Returns true if the specified \a year is a leap year; otherwise
  1039. returns false.
  1040. */
  1041. bool QDate::isLeapYear(int y)
  1042. {
  1043. // No year 0 in Gregorian calendar, so -1, -5, -9 etc are leap years
  1044. if ( y < 1)
  1045. ++y;
  1046. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  1047. }
  1048. /*! \fn static QDate QDate::fromJulianDay(qint64 jd)
  1049. Converts the Julian day \a jd to a QDate.
  1050. \sa toJulianDay()
  1051. */
  1052. /*! \fn int QDate::toJulianDay() const
  1053. Converts the date to a Julian day.
  1054. \sa fromJulianDay()
  1055. */
  1056. /*****************************************************************************
  1057. QTime member functions
  1058. *****************************************************************************/
  1059. /*!
  1060. \class QTime
  1061. \inmodule QtCore
  1062. \reentrant
  1063. \brief The QTime class provides clock time functions.
  1064. A QTime object contains a clock time, i.e. the number of hours,
  1065. minutes, seconds, and milliseconds since midnight. It can read the
  1066. current time from the system clock and measure a span of elapsed
  1067. time. It provides functions for comparing times and for
  1068. manipulating a time by adding a number of milliseconds.
  1069. QTime uses the 24-hour clock format; it has no concept of AM/PM.
  1070. Unlike QDateTime, QTime knows nothing about time zones or
  1071. daylight savings time (DST).
  1072. A QTime object is typically created either by giving the number
  1073. of hours, minutes, seconds, and milliseconds explicitly, or by
  1074. using the static function currentTime(), which creates a QTime
  1075. object that contains the system's local time. Note that the
  1076. accuracy depends on the accuracy of the underlying operating
  1077. system; not all systems provide 1-millisecond accuracy.
  1078. The hour(), minute(), second(), and msec() functions provide
  1079. access to the number of hours, minutes, seconds, and milliseconds
  1080. of the time. The same information is provided in textual format by
  1081. the toString() function.
  1082. QTime provides a full set of operators to compare two QTime
  1083. objects. QTime A is considered smaller than QTime B if A is
  1084. earlier than B.
  1085. The addSecs() and addMSecs() functions provide the time a given
  1086. number of seconds or milliseconds later than a given time.
  1087. Correspondingly, the number of seconds or milliseconds
  1088. between two times can be found using secsTo() or msecsTo().
  1089. QTime can be used to measure a span of elapsed time using the
  1090. start(), restart(), and elapsed() functions.
  1091. \sa QDate, QDateTime
  1092. */
  1093. /*!
  1094. \fn QTime::QTime()
  1095. Constructs a null time object. A null time can be a QTime(0, 0, 0, 0)
  1096. (i.e., midnight) object, except that isNull() returns true and isValid()
  1097. returns false.
  1098. \sa isNull(), isValid()
  1099. */
  1100. /*!
  1101. Constructs a time with hour \a h, minute \a m, seconds \a s and
  1102. milliseconds \a ms.
  1103. \a h must be in the range 0 to 23, \a m and \a s must be in the
  1104. range 0 to 59, and \a ms must be in the range 0 to 999.
  1105. \sa isValid()
  1106. */
  1107. QTime::QTime(int h, int m, int s, int ms)
  1108. {
  1109. setHMS(h, m, s, ms);
  1110. }
  1111. /*!
  1112. \fn bool QTime::isNull() const
  1113. Returns true if the time is null (i.e., the QTime object was
  1114. constructed using the default constructor); otherwise returns
  1115. false. A null time is also an invalid time.
  1116. \sa isValid()
  1117. */
  1118. /*!
  1119. Returns true if the time is valid; otherwise returns false. For example,
  1120. the time 23:30:55.746 is valid, but 24:12:30 is invalid.
  1121. \sa isNull()
  1122. */
  1123. bool QTime::isValid() const
  1124. {
  1125. return mds > NullTime && mds < MSECS_PER_DAY;
  1126. }
  1127. /*!
  1128. Returns the hour part (0 to 23) of the time.
  1129. Returns -1 if the time is invalid.
  1130. \sa minute(), second(), msec()
  1131. */
  1132. int QTime::hour() const
  1133. {
  1134. if (!isValid())
  1135. return -1;
  1136. return ds() / MSECS_PER_HOUR;
  1137. }
  1138. /*!
  1139. Returns the minute part (0 to 59) of the time.
  1140. Returns -1 if the time is invalid.
  1141. \sa hour(), second(), msec()
  1142. */
  1143. int QTime::minute() const
  1144. {
  1145. if (!isValid())
  1146. return -1;
  1147. return (ds() % MSECS_PER_HOUR) / MSECS_PER_MIN;
  1148. }
  1149. /*!
  1150. Returns the second part (0 to 59) of the time.
  1151. Returns -1 if the time is invalid.
  1152. \sa hour(), minute(), msec()
  1153. */
  1154. int QTime::second() const
  1155. {
  1156. if (!isValid())
  1157. return -1;
  1158. return (ds() / 1000)%SECS_PER_MIN;
  1159. }
  1160. /*!
  1161. Returns the millisecond part (0 to 999) of the time.
  1162. Returns -1 if the time is invalid.
  1163. \sa hour(), minute(), second()
  1164. */
  1165. int QTime::msec() const
  1166. {
  1167. if (!isValid())
  1168. return -1;
  1169. return ds() % 1000;
  1170. }
  1171. #ifndef QT_NO_DATESTRING
  1172. /*!
  1173. \overload
  1174. Returns the time as a string. Milliseconds are not included. The
  1175. \a format parameter determines the format of the string.
  1176. If \a format is Qt::TextDate, the string format is HH:MM:SS; e.g. 1
  1177. second before midnight would be "23:59:59".
  1178. If \a format is Qt::ISODate, the string format corresponds to the
  1179. ISO 8601 extended specification for representations of dates,
  1180. which is also HH:MM:SS. (However, contrary to ISO 8601, dates
  1181. before 15 October 1582 are handled as Julian dates, not Gregorian
  1182. dates. See \l{QDate G and J} {Use of Gregorian and Julian
  1183. Calendars}. This might change in a future version of Qt.)
  1184. If the \a format is Qt::SystemLocaleShortDate or
  1185. Qt::SystemLocaleLongDate, the string format depends on the locale
  1186. settings of the system. Identical to calling
  1187. QLocale::system().toString(time, QLocale::ShortFormat) or
  1188. QLocale::system().toString(time, QLocale::LongFormat).
  1189. If the \a format is Qt::DefaultLocaleShortDate or
  1190. Qt::DefaultLocaleLongDate, the string format depends on the
  1191. default application locale. This is the locale set with
  1192. QLocale::setDefault(), or the system locale if no default locale
  1193. has been set. Identical to calling QLocale().toString(time,
  1194. QLocale::ShortFormat) or QLocale().toString(time,
  1195. QLocale::LongFormat).
  1196. If the time is invalid, an empty string will be returned.
  1197. */
  1198. QString QTime::toString(Qt::DateFormat format) const
  1199. {
  1200. if (!isValid())
  1201. return QString();
  1202. switch (format) {
  1203. case Qt::SystemLocaleDate:
  1204. case Qt::SystemLocaleShortDate:
  1205. case Qt::SystemLocaleLongDate:
  1206. return QLocale::system().toString(*this, format == Qt::SystemLocaleLongDate ? QLocale::LongFormat
  1207. : QLocale::ShortFormat);
  1208. case Qt::LocaleDate:
  1209. case Qt::DefaultLocaleShortDate:
  1210. case Qt::DefaultLocaleLongDate:
  1211. return QLocale().toString(*this, format == Qt::DefaultLocaleLongDate ? QLocale::LongFormat
  1212. : QLocale::ShortFormat);
  1213. default:
  1214. case Qt::ISODate:
  1215. case Qt::TextDate:
  1216. return QString::fromLatin1("%1:%2:%3")
  1217. .arg(hour(), 2, 10, QLatin1Char('0'))
  1218. .arg(minute(), 2, 10, QLatin1Char('0'))
  1219. .arg(second(), 2, 10, QLatin1Char('0'));
  1220. }
  1221. }
  1222. /*!
  1223. Returns the time as a string. The \a format parameter determines
  1224. the format of the result string.
  1225. These expressions may be used:
  1226. \table
  1227. \header \li Expression \li Output
  1228. \row \li h
  1229. \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
  1230. \row \li hh
  1231. \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
  1232. \row \li H
  1233. \li the hour without a leading zero (0 to 23, even with AM/PM display)
  1234. \row \li HH
  1235. \li the hour with a leading zero (00 to 23, even with AM/PM display)
  1236. \row \li m \li the minute without a leading zero (0 to 59)
  1237. \row \li mm \li the minute with a leading zero (00 to 59)
  1238. \row \li s \li the second without a leading zero (0 to 59)
  1239. \row \li ss \li the second with a leading zero (00 to 59)
  1240. \row \li z \li the milliseconds without leading zeroes (0 to 999)
  1241. \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
  1242. \row \li AP or A
  1243. \li use AM/PM display. \e AP will be replaced by either "AM" or "PM".
  1244. \row \li ap or a
  1245. \li use am/pm display. \e ap will be replaced by either "am" or "pm".
  1246. \row \li t \li the timezone (for example "CEST")
  1247. \endtable
  1248. All other input characters will be ignored. Any sequence of characters that
  1249. are enclosed in single quotes will be treated as text and not be used as an
  1250. expression. Two consecutive single quotes ("''") are replaced by a singlequote
  1251. in the output. Formats without separators (e.g. "HHmm") are currently not supported.
  1252. Example format strings (assuming that the QTime is 14:13:09.042)
  1253. \table
  1254. \header \li Format \li Result
  1255. \row \li hh:mm:ss.zzz \li 14:13:09.042
  1256. \row \li h:m:s ap \li 2:13:9 pm
  1257. \row \li H:m:s a \li 14:13:9 pm
  1258. \endtable
  1259. If the time is invalid, an empty string will be returned.
  1260. If \a format is empty, the default format "hh:mm:ss" is used.
  1261. \sa QDate::toString(), QDateTime::toString()
  1262. */
  1263. QString QTime::toString(const QString& format) const
  1264. {
  1265. return fmtDateTime(format, this, 0);
  1266. }
  1267. #endif //QT_NO_DATESTRING
  1268. /*!
  1269. Sets the time to hour \a h, minute \a m, seconds \a s and
  1270. milliseconds \a ms.
  1271. \a h must be in the range 0 to 23, \a m and \a s must be in the
  1272. range 0 to 59, and \a ms must be in the range 0 to 999.
  1273. Returns true if the set time is valid; otherwise returns false.
  1274. \sa isValid()
  1275. */
  1276. bool QTime::setHMS(int h, int m, int s, int ms)
  1277. {
  1278. #if defined(Q_OS_WINCE)
  1279. startTick = NullTime;
  1280. #endif
  1281. if (!isValid(h,m,s,ms)) {
  1282. mds = NullTime; // make this invalid
  1283. return false;
  1284. }
  1285. mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
  1286. return true;
  1287. }
  1288. /*!
  1289. Returns a QTime object containing a time \a s seconds later
  1290. than the time of this object (or earlier if \a s is negative).
  1291. Note that the time will wrap if it passes midnight.
  1292. Returns a null time if this time is invalid.
  1293. Example:
  1294. \snippet code/src_corelib_tools_qdatetime.cpp 5
  1295. \sa addMSecs(), secsTo(), QDateTime::addSecs()
  1296. */
  1297. QTime QTime::addSecs(int s) const
  1298. {
  1299. return addMSecs(s * 1000);
  1300. }
  1301. /*!
  1302. Returns the number of seconds from this time to \a t.
  1303. If \a t is earlier than this time, the number of seconds returned
  1304. is negative.
  1305. Because QTime measures time within a day and there are 86400
  1306. seconds in a day, the result is always between -86400 and 86400.
  1307. secsTo() does not take into account any milliseconds.
  1308. Returns 0 if either time is invalid.
  1309. \sa addSecs(), QDateTime::secsTo()
  1310. */
  1311. int QTime::secsTo(const QTime &t) const
  1312. {
  1313. if (!isValid() || !t.isValid())
  1314. return 0;
  1315. // Truncate milliseconds as we do not want to consider them.
  1316. int ourSeconds = ds() / 1000;
  1317. int theirSeconds = t.ds() / 1000;
  1318. return theirSeconds - ourSeconds;
  1319. }
  1320. /*!
  1321. Returns a QTime object containing a time \a ms milliseconds later
  1322. than the time of this object (or earlier if \a ms is negative).
  1323. Note that the time will wrap if it passes midnight. See addSecs()
  1324. for an example.
  1325. Returns a null time if this time is invalid.
  1326. \sa addSecs(), msecsTo(), QDateTime::addMSecs()
  1327. */
  1328. QTime QTime::addMSecs(int ms) const
  1329. {
  1330. QTime t;
  1331. if (isValid()) {
  1332. if (ms < 0) {
  1333. // % not well-defined for -ve, but / is.
  1334. int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
  1335. t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
  1336. } else {
  1337. t.mds = (ds() + ms) % MSECS_PER_DAY;
  1338. }
  1339. }
  1340. #if defined(Q_OS_WINCE)
  1341. if (startTick > NullTime)
  1342. t.startTick = (startTick + ms) % MSECS_PER_DAY;
  1343. #endif
  1344. return t;
  1345. }
  1346. /*!
  1347. Returns the number of milliseconds from this time to \a t.
  1348. If \a t is earlier than this time, the number of milliseconds returned
  1349. is negative.
  1350. Because QTime measures time within a day and there are 86400
  1351. seconds in a day, the result is always between -86400000 and
  1352. 86400000 ms.
  1353. Returns 0 if either time is invalid.
  1354. \sa secsTo(), addMSecs(), QDateTime::msecsTo()
  1355. */
  1356. int QTime::msecsTo(const QTime &t) const
  1357. {
  1358. if (!isValid() || !t.isValid())
  1359. return 0;
  1360. #if defined(Q_OS_WINCE)
  1361. // GetLocalTime() for Windows CE has no milliseconds resolution
  1362. if (t.startTick > NullTime && startTick > NullTime)
  1363. return t.startTick - startTick;
  1364. else
  1365. #endif
  1366. return t.ds() - ds();
  1367. }
  1368. /*!
  1369. \fn bool QTime::operator==(const QTime &t) const
  1370. Returns true if this time is equal to \a t; otherwise returns false.
  1371. */
  1372. /*!
  1373. \fn bool QTime::operator!=(const QTime &t) const
  1374. Returns true if this time is different from \a t; otherwise returns false.
  1375. */
  1376. /*!
  1377. \fn bool QTime::operator<(const QTime &t) const
  1378. Returns true if this time is earlier than \a t; otherwise returns false.
  1379. */
  1380. /*!
  1381. \fn bool QTime::operator<=(const QTime &t) const
  1382. Returns true if this time is earlier than or equal to \a t;
  1383. otherwise returns false.
  1384. */
  1385. /*!
  1386. \fn bool QTime::operator>(const QTime &t) const
  1387. Returns true if this time is later than \a t; otherwise returns false.
  1388. */
  1389. /*!
  1390. \fn bool QTime::operator>=(const QTime &t) const
  1391. Returns true if this time is later than or equal to \a t;
  1392. otherwise returns false.
  1393. */
  1394. /*!
  1395. \fn QTime::currentTime()
  1396. Returns the current time as reported by the system clock.
  1397. Note that the accuracy depends on the accuracy of the underlying
  1398. operating system; not all systems provide 1-millisecond accuracy.
  1399. */
  1400. #ifndef QT_NO_DATESTRING
  1401. // These anonymous functions tidy up QDateTime::fromString()
  1402. // and avoid confusion of responsibility between it and QTime::fromString().
  1403. namespace {
  1404. inline bool isMidnight(int hour, int minute, int second, int msec)
  1405. {
  1406. return hour == 24 && minute == 0 && second == 0 && msec == 0;
  1407. }
  1408. QTime fromStringImpl(const QString &s, Qt::DateFormat f, bool &isMidnight24)
  1409. {
  1410. if (s.isEmpty()) {
  1411. // Return a null time.
  1412. return QTime();
  1413. }

Large files files are truncated, but you can click here to view the full file