source: vendor/trolltech/current/src/tools/qdatetime.cpp

Last change on this file was 2, checked in by dmik, 20 years ago

Imported xplatform parts of the official release 3.3.1 from Trolltech

  • Property svn:keywords set to Id
File size: 67.9 KB
Line 
1/****************************************************************************
2** $Id: qdatetime.cpp 2 2005-11-16 15:49:26Z dmik $
3**
4** Implementation of date and time classes
5**
6** Created : 940124
7**
8** Copyright (C) 1992-2002 Trolltech AS. All rights reserved.
9**
10** This file is part of the tools module of the Qt GUI Toolkit.
11**
12** This file may be distributed under the terms of the Q Public License
13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file.
15**
16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file.
20**
21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22** licenses may use this file in accordance with the Qt Commercial License
23** Agreement provided with the Software.
24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32**
33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you.
35**
36**********************************************************************/
37
38#include "qplatformdefs.h"
39
40#include "qdatetime.h"
41#include "qdatastream.h"
42#include "qregexp.h"
43
44#include <stdio.h>
45#ifndef Q_OS_TEMP
46#include <time.h>
47#endif
48
49#if defined(Q_OS_WIN32)
50#include <windows.h>
51#endif
52
53static const uint FIRST_DAY = 2361222; // Julian day for 1752-09-14
54static const int FIRST_YEAR = 1752; // ### wrong for many countries
55static const uint SECS_PER_DAY = 86400;
56static const uint MSECS_PER_DAY = 86400000;
57static const uint SECS_PER_HOUR = 3600;
58static const uint MSECS_PER_HOUR= 3600000;
59static const uint SECS_PER_MIN = 60;
60static const uint MSECS_PER_MIN = 60000;
61
62static const short monthDays[] = {
63 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
64
65static const char * const qt_shortMonthNames[] = {
66 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
67 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
68
69#ifndef QT_NO_DATESTRING
70/*****************************************************************************
71 Some static function used by QDate, QTime and QDateTime
72 *****************************************************************************/
73
74// Replaces tokens by their value. See QDateTime::toString() for a list of valid tokens
75static QString getFmtString( const QString& f, const QTime* dt = 0, const QDate* dd = 0, bool am_pm = FALSE )
76{
77 if ( f.isEmpty() )
78 return QString::null;
79
80 QString buf = f;
81
82 if ( dt ) {
83 if ( f == "h" ) {
84 if ( ( am_pm ) && ( dt->hour() > 12 ) )
85 buf = QString::number( dt->hour() - 12 );
86 else if ( ( am_pm ) && ( dt->hour() == 0 ) )
87 buf = "12";
88 else
89 buf = QString::number( dt->hour() );
90 } else if ( f == "hh" ) {
91 if ( ( am_pm ) && ( dt->hour() > 12 ) )
92 buf = QString::number( dt->hour() - 12 ).rightJustify( 2, '0', TRUE );
93 else if ( ( am_pm ) && ( dt->hour() == 0 ) )
94 buf = "12";
95 else
96 buf = QString::number( dt->hour() ).rightJustify( 2, '0', TRUE );
97 } else if ( f == "m" ) {
98 buf = QString::number( dt->minute() );
99 } else if ( f == "mm" ) {
100 buf = QString::number( dt->minute() ).rightJustify( 2, '0', TRUE );
101 } else if ( f == "s" ) {
102 buf = QString::number( dt->second() );
103 } else if ( f == "ss" ) {
104 buf = QString::number( dt->second() ).rightJustify( 2, '0', TRUE );
105 } else if ( f == "z" ) {
106 buf = QString::number( dt->msec() );
107 } else if ( f == "zzz" ) {
108 buf = QString::number( dt->msec() ).rightJustify( 3, '0', TRUE );
109 } else if ( f == "ap" ) {
110 buf = dt->hour() < 12 ? "am" : "pm";
111 } else if ( f == "AP" ) {
112 buf = dt->hour() < 12 ? "AM" : "PM";
113 }
114 }
115
116 if ( dd ) {
117 if ( f == "d" ) {
118 buf = QString::number( dd->day() );
119 } else if ( f == "dd" ) {
120 buf = QString::number( dd->day() ).rightJustify( 2, '0', TRUE );
121 } else if ( f == "M" ) {
122 buf = QString::number( dd->month() );
123 } else if ( f == "MM" ) {
124 buf = QString::number( dd->month() ).rightJustify( 2, '0', TRUE );
125#ifndef QT_NO_TEXTDATE
126 } else if ( f == "ddd" ) {
127 buf = dd->shortDayName( dd->dayOfWeek() );
128 } else if ( f == "dddd" ) {
129 buf = dd->longDayName( dd->dayOfWeek() );
130 } else if ( f == "MMM" ) {
131 buf = dd->shortMonthName( dd->month() );
132 } else if ( f == "MMMM" ) {
133 buf = dd->longMonthName( dd->month() );
134#endif
135 } else if ( f == "yy" ) {
136 buf = QString::number( dd->year() ).right( 2 );
137 } else if ( f == "yyyy" ) {
138 buf = QString::number( dd->year() );
139 }
140 }
141
142 return buf;
143}
144
145// Parses the format string and uses getFmtString to get the values for the tokens. Ret
146static QString fmtDateTime( const QString& f, const QTime* dt = 0, const QDate* dd = 0 )
147{
148 if ( f.isEmpty() ) {
149 return QString::null;
150 }
151
152 if ( dt && !dt->isValid() )
153 return QString::null;
154 if ( dd && !dd->isValid() )
155 return QString::null;
156
157 bool ap = ( f.contains( "AP" ) || f.contains( "ap" ) );
158
159 QString buf;
160 QString frm;
161 QChar status = '0';
162
163 for ( int i = 0; i < (int)f.length(); ++i ) {
164
165 if ( f[ i ] == status ) {
166 if ( ( ap ) && ( ( f[ i ] == 'P' ) || ( f[ i ] == 'p' ) ) )
167 status = '0';
168 frm += f[ i ];
169 } else {
170 buf += getFmtString( frm, dt, dd, ap );
171 frm = QString::null;
172 if ( ( f[ i ] == 'h' ) || ( f[ i ] == 'm' ) || ( f[ i ] == 's' ) || ( f[ i ] == 'z' ) ) {
173 status = f[ i ];
174 frm += f[ i ];
175 } else if ( ( f[ i ] == 'd' ) || ( f[ i ] == 'M' ) || ( f[ i ] == 'y' ) ) {
176 status = f[ i ];
177 frm += f[ i ];
178 } else if ( ( ap ) && ( f[ i ] == 'A' ) ) {
179 status = 'P';
180 frm += f[ i ];
181 } else if( ( ap ) && ( f[ i ] == 'a' ) ) {
182 status = 'p';
183 frm += f[ i ];
184 } else {
185 buf += f[ i ];
186 status = '0';
187 }
188 }
189 }
190
191 buf += getFmtString( frm, dt, dd, ap );
192
193 return buf;
194}
195#endif // QT_NO_DATESTRING
196
197/*****************************************************************************
198 QDate member functions
199 *****************************************************************************/
200
201/*!
202 \class QDate qdatetime.h
203 \reentrant
204 \brief The QDate class provides date functions.
205
206 \ingroup time
207 \mainclass
208
209 A QDate object contains a calendar date, i.e. year, month, and day
210 numbers, in the modern Western (Gregorian) calendar. It can read
211 the current date from the system clock. It provides functions for
212 comparing dates and for manipulating dates, e.g. by adding a
213 number of days or months or years.
214
215 A QDate object is typically created either by giving the year,
216 month and day numbers explicitly, or by using the static function
217 currentDate(), which creates a QDate object containing the system
218 clock's date. An explicit date can also be set using setYMD(). The
219 fromString() function returns a QDate given a string and a date
220 format which is used to interpret the date within the string.
221
222 The year(), month(), and day() functions provide access to the
223 year, month, and day numbers. Also, dayOfWeek() and dayOfYear()
224 functions are provided. The same information is provided in
225 textual format by the toString(), shortDayName(), longDayName(),
226 shortMonthName() and longMonthName() functions.
227
228 QDate provides a full set of operators to compare two QDate
229 objects where smaller means earlier and larger means later.
230
231 You can increment (or decrement) a date by a given number of days
232 using addDays(). Similarly you can use addMonths() and addYears().
233 The daysTo() function returns the number of days between two
234 dates.
235
236 The daysInMonth() and daysInYear() functions return how many days
237 there are in this date's month and year, respectively. The
238 leapYear() function indicates whether this date is in a leap year.
239
240 Note that QDate should not be used for date calculations for dates
241 prior to the introduction of the Gregorian calendar. This calendar
242 was adopted by England from the 14<sup><small>th</small></sup>
243 September 1752 (hence this is the earliest valid QDate), and
244 subsequently by most other Western countries, until 1923.
245
246 The end of time is reached around the year 8000, by which time we
247 expect Qt to be obsolete.
248
249 \sa QTime QDateTime QDateEdit QDateTimeEdit
250*/
251
252/*!
253 \enum Qt::DateFormat
254
255 \value TextDate (default) Qt format
256 \value ISODate ISO 8601 extended format (YYYY-MM-DD, or with time,
257 YYYY-MM-DDTHH:MM:SS)
258 \value LocalDate locale dependent format
259*/
260
261
262/*!
263 \enum Qt::TimeSpec
264
265 \value LocalTime Locale dependent time (Timezones and Daylight Savings Time)
266 \value UTC Coordinated Universal Time, replaces Greenwich Time
267*/
268
269/*!
270 \fn QDate::QDate()
271
272 Constructs a null date. Null dates are invalid.
273
274 \sa isNull(), isValid()
275*/
276
277
278/*!
279 Constructs a date with year \a y, month \a m and day \a d.
280
281 \a y must be in the range 1752..8000, \a m must be in the range
282 1..12, and \a d must be in the range 1..31.
283
284 \warning If \a y is in the range 0..99, it is interpreted as
285 1900..1999.
286
287 \sa isValid()
288*/
289
290QDate::QDate( int y, int m, int d )
291{
292 jd = 0;
293 setYMD( y, m, d );
294}
295
296
297/*!
298 \fn bool QDate::isNull() const
299
300 Returns TRUE if the date is null; otherwise returns FALSE. A null
301 date is invalid.
302
303 \sa isValid()
304*/
305
306
307/*!
308 Returns TRUE if this date is valid; otherwise returns FALSE.
309
310 \sa isNull()
311*/
312
313bool QDate::isValid() const
314{
315 return jd >= FIRST_DAY;
316}
317
318
319/*!
320 Returns the year (1752..8000) of this date.
321
322 \sa month(), day()
323*/
324
325int QDate::year() const
326{
327 int y, m, d;
328 julianToGregorian( jd, y, m, d );
329 return y;
330}
331
332/*!
333 Returns the month (January=1..December=12) of this date.
334
335 \sa year(), day()
336*/
337
338int QDate::month() const
339{
340 int y, m, d;
341 julianToGregorian( jd, y, m, d );
342 return m;
343}
344
345/*!
346 Returns the day of the month (1..31) of this date.
347
348 \sa year(), month(), dayOfWeek()
349*/
350
351int QDate::day() const
352{
353 int y, m, d;
354 julianToGregorian( jd, y, m, d );
355 return d;
356}
357
358/*!
359 Returns the weekday (Monday=1..Sunday=7) for this date.
360
361 \sa day(), dayOfYear()
362*/
363
364int QDate::dayOfWeek() const
365{
366 return ( jd % 7 ) + 1;
367}
368
369/*!
370 Returns the day of the year (1..365) for this date.
371
372 \sa day(), dayOfWeek()
373*/
374
375int QDate::dayOfYear() const
376{
377 return jd - gregorianToJulian(year(), 1, 1) + 1;
378}
379
380/*!
381 Returns the number of days in the month (28..31) for this date.
382
383 \sa day(), daysInYear()
384*/
385
386int QDate::daysInMonth() const
387{
388 int y, m, d;
389 julianToGregorian( jd, y, m, d );
390 if ( m == 2 && leapYear(y) )
391 return 29;
392 else
393 return monthDays[m];
394}
395
396/*!
397 Returns the number of days in the year (365 or 366) for this date.
398
399 \sa day(), daysInMonth()
400*/
401
402int QDate::daysInYear() const
403{
404 int y, m, d;
405 julianToGregorian( jd, y, m, d );
406 return leapYear( y ) ? 366 : 365;
407}
408
409/*!
410 Returns the week number (1 to 53), and stores the year in \a
411 *yearNumber unless \a yearNumber is null (the default).
412
413 Returns 0 if the date is invalid.
414
415 In accordance with ISO 8601, weeks start on Monday and the first
416 Thursday of a year is always in week 1 of that year. Most years
417 have 52 weeks, but some have 53.
418
419 \a *yearNumber is not always the same as year(). For example, 1
420 January 2000 has week number 52 in the year 1999, and 31 December
421 2002 has week number 1 in the year 2003.
422
423 \legalese
424
425 Copyright (c) 1989 The Regents of the University of California.
426 All rights reserved.
427
428 Redistribution and use in source and binary forms are permitted
429 provided that the above copyright notice and this paragraph are
430 duplicated in all such forms and that any documentation,
431 advertising materials, and other materials related to such
432 distribution and use acknowledge that the software was developed
433 by the University of California, Berkeley. The name of the
434 University may not be used to endorse or promote products derived
435 from this software without specific prior written permission.
436 THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
437 IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
438 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
439
440 \sa isValid()
441*/
442
443int QDate::weekNumber( int *yearNumber ) const
444{
445 if ( !isValid() )
446 return 0;
447
448 int year = QDate::year();
449 int yday = dayOfYear() - 1;
450 int wday = dayOfWeek();
451 if (wday == 7)
452 wday = 0;
453 int w;
454
455 for (;;) {
456 int len;
457 int bot;
458 int top;
459
460 len = leapYear(year) ? 366 : 365;
461 /*
462 ** What yday (-3 ... 3) does
463 ** the ISO year begin on?
464 */
465 bot = ((yday + 11 - wday) % 7) - 3;
466 /*
467 ** What yday does the NEXT
468 ** ISO year begin on?
469 */
470 top = bot - (len % 7);
471 if (top < -3)
472 top += 7;
473 top += len;
474 if (yday >= top) {
475 ++year;
476 w = 1;
477 break;
478 }
479 if (yday >= bot) {
480 w = 1 + ((yday - bot) / 7);
481 break;
482 }
483 --year;
484 yday += leapYear(year) ? 366 : 365;
485 }
486 if (yearNumber != 0)
487 *yearNumber = year;
488 return w;
489}
490
491/*!
492 \fn QString QDate::monthName( int month )
493 \obsolete
494
495 Use shortMonthName() instead.
496*/
497#ifndef QT_NO_TEXTDATE
498/*!
499 Returns the name of the \a month.
500
501 1 = "Jan", 2 = "Feb", ... 12 = "Dec"
502
503 The month names will be localized according to the system's locale
504 settings.
505
506 \sa toString(), longMonthName(), shortDayName(), longDayName()
507*/
508
509QString QDate::shortMonthName( int month )
510{
511#if defined(QT_CHECK_RANGE)
512 if ( month < 1 || month > 12 ) {
513 qWarning( "QDate::shortMonthName: Parameter out ouf range" );
514 month = 1;
515 }
516#endif
517#ifndef Q_WS_WIN
518 char buffer[255];
519 tm tt;
520 memset( &tt, 0, sizeof( tm ) );
521 tt.tm_mon = month - 1;
522 if ( strftime( buffer, sizeof( buffer ), "%b", &tt ) )
523 return QString::fromLocal8Bit( buffer );
524#else
525 SYSTEMTIME st;
526 memset( &st, 0, sizeof(SYSTEMTIME) );
527 st.wYear = 2000;
528 st.wMonth = month;
529 st.wDay = 1;
530 const wchar_t mmm_t[] = L"MMM"; // workaround for Borland
531 QT_WA( {
532 TCHAR buf[255];
533 if ( GetDateFormat( LOCALE_USER_DEFAULT, 0, &st, mmm_t, buf, 255 ) )
534 return QString::fromUcs2( (ushort*)buf );
535 } , {
536 char buf[255];
537 if ( GetDateFormatA( LOCALE_USER_DEFAULT, 0, &st, "MMM", (char*)&buf, 255 ) )
538 return QString::fromLocal8Bit( buf );
539 } );
540#endif
541 return QString::null;
542}
543
544/*!
545 Returns the long name of the \a month.
546
547 1 = "January", 2 = "February", ... 12 = "December"
548
549 The month names will be localized according to the system's locale
550 settings.
551
552 \sa toString(), shortMonthName(), shortDayName(), longDayName()
553*/
554
555QString QDate::longMonthName( int month )
556{
557#if defined(QT_CHECK_RANGE)
558 if ( month < 1 || month > 12 ) {
559 qWarning( "QDate::longMonthName: Parameter out ouf range" );
560 month = 1;
561 }
562#endif
563#ifndef Q_WS_WIN
564 char buffer[255];
565 tm tt;
566 memset( &tt, 0, sizeof( tm ) );
567 tt.tm_mon = month - 1;
568 if ( strftime( buffer, sizeof( buffer ), "%B", &tt ) )
569 return QString::fromLocal8Bit( buffer );
570#else
571 SYSTEMTIME st;
572 memset( &st, 0, sizeof(SYSTEMTIME) );
573 st.wYear = 2000;
574 st.wMonth = month;
575 st.wDay = 1 ;
576 const wchar_t mmmm_t[] = L"MMMM"; // workaround for Borland
577 QT_WA( {
578 TCHAR buf[255];
579 if ( GetDateFormat( LOCALE_USER_DEFAULT, 0, &st, mmmm_t, buf, 255 ) )
580 return QString::fromUcs2( (ushort*)buf );
581 } , {
582 char buf[255];
583 if ( GetDateFormatA( LOCALE_USER_DEFAULT, 0, &st, "MMMM", (char*)&buf, 255 ) )
584 return QString::fromLocal8Bit( buf );
585 } )
586#endif
587
588 return QString::null;
589}
590
591/*!
592 \fn QString QDate::dayName( int weekday )
593 \obsolete
594
595 Use shortDayName() instead.
596*/
597
598/*!
599 Returns the name of the \a weekday.
600
601 1 = "Mon", 2 = "Tue", ... 7 = "Sun"
602
603 The day names will be localized according to the system's locale
604 settings.
605
606 \sa toString(), shortMonthName(), longMonthName(), longDayName()
607*/
608
609QString QDate::shortDayName( int weekday )
610{
611#if defined(QT_CHECK_RANGE)
612 if ( weekday < 1 || weekday > 7 ) {
613 qWarning( "QDate::shortDayName: Parameter out of range" );
614 weekday = 1;
615 }
616#endif
617#ifndef Q_WS_WIN
618 char buffer[255];
619 tm tt;
620 memset( &tt, 0, sizeof( tm ) );
621 tt.tm_wday = ( weekday == 7 ) ? 0 : weekday;
622 if ( strftime( buffer, sizeof( buffer ), "%a", &tt ) )
623 return QString::fromLocal8Bit( buffer );
624#else
625 SYSTEMTIME st;
626 memset( &st, 0, sizeof(SYSTEMTIME) );
627 st.wYear = 2001;
628 st.wMonth = 10;
629 st.wDayOfWeek = ( weekday == 7 ) ? 0 : weekday;
630 st.wDay = 21 + st.wDayOfWeek;
631 const wchar_t ddd_t[] = L"ddd"; // workaround for Borland
632 QT_WA( {
633 TCHAR buf[255];
634 if ( GetDateFormat( LOCALE_USER_DEFAULT, 0, &st, ddd_t, buf, 255 ) )
635 return QString::fromUcs2( (ushort*)buf );
636 } , {
637 char buf[255];
638 if ( GetDateFormatA( LOCALE_USER_DEFAULT, 0, &st, "ddd", (char*)&buf, 255 ) )
639 return QString::fromLocal8Bit( buf );
640 } );
641#endif
642
643 return QString::null;
644}
645
646/*!
647 Returns the long name of the \a weekday.
648
649 1 = "Monday", 2 = "Tuesday", ... 7 = "Sunday"
650
651 The day names will be localized according to the system's locale
652 settings.
653
654 \sa toString(), shortDayName(), shortMonthName(), longMonthName()
655*/
656
657QString QDate::longDayName( int weekday )
658{
659#if defined(QT_CHECK_RANGE)
660 if ( weekday < 1 || weekday > 7 ) {
661 qWarning( "QDate::longDayName: Parameter out of range" );
662 weekday = 1;
663 }
664#endif
665#ifndef Q_WS_WIN
666 char buffer[255];
667 tm tt;
668 memset( &tt, 0, sizeof( tm ) );
669 tt.tm_wday = ( weekday == 7 ) ? 0 : weekday;
670 if ( strftime( buffer, sizeof( buffer ), "%A", &tt ) )
671 return QString::fromLocal8Bit( buffer );
672#else
673 SYSTEMTIME st;
674 memset( &st, 0, sizeof(SYSTEMTIME) );
675 st.wYear = 2001;
676 st.wMonth = 10;
677 st.wDayOfWeek = ( weekday == 7 ) ? 0 : weekday;
678 st.wDay = 21 + st.wDayOfWeek;
679 const wchar_t dddd_t[] = L"dddd"; // workaround for Borland
680 QT_WA( {
681 TCHAR buf[255];
682 if ( GetDateFormat( LOCALE_USER_DEFAULT, 0, &st, dddd_t, buf, 255 ) )
683 return QString::fromUcs2( (ushort*)buf );
684 } , {
685 char buf[255];
686 if ( GetDateFormatA( LOCALE_USER_DEFAULT, 0, &st, "dddd", (char*)&buf, 255 ) )
687 return QString::fromLocal8Bit( buf );
688 } );
689#endif
690
691 return QString::null;
692}
693#endif //QT_NO_TEXTDATE
694
695#ifndef QT_NO_DATESTRING
696
697#if !defined(QT_NO_SPRINTF)
698/*!
699 \overload
700
701 Returns the date as a string. The \a f parameter determines the
702 format of the string.
703
704 If \a f is \c Qt::TextDate, the string format is "Sat May 20 1995"
705 (using the shortDayName() and shortMonthName() functions to
706 generate the string, so the day and month names are locale
707 specific).
708
709 If \a f is \c Qt::ISODate, the string format corresponds to the
710 ISO 8601 specification for representations of dates, which is
711 YYYY-MM-DD where YYYY is the year, MM is the month of the year
712 (between 01 and 12), and DD is the day of the month between 01 and
713 31.
714
715 If \a f is \c Qt::LocalDate, the string format depends on the
716 locale settings of the system.
717
718 If the date is an invalid date, then QString::null will be returned.
719
720 \sa shortDayName(), shortMonthName()
721*/
722QString QDate::toString( Qt::DateFormat f ) const
723{
724 if ( !isValid() )
725 return QString::null;
726 int y, m, d;
727 julianToGregorian( jd, y, m, d );
728 switch ( f ) {
729 case Qt::LocalDate:
730 {
731#ifndef Q_WS_WIN
732 tm tt;
733 memset( &tt, 0, sizeof( tm ) );
734 char buf[255];
735 tt.tm_mday = day();
736 tt.tm_mon = month() - 1;
737 tt.tm_year = year() - 1900;
738
739 static const char * avoidEgcsWarning = "%x";
740 if ( strftime( buf, sizeof(buf), avoidEgcsWarning, &tt ) )
741 return QString::fromLocal8Bit( buf );
742#else
743 SYSTEMTIME st;
744 memset( &st, 0, sizeof(SYSTEMTIME) );
745 st.wYear = year();
746 st.wMonth = month();
747 st.wDay = day();
748 QT_WA( {
749 TCHAR buf[255];
750 if ( GetDateFormat( LOCALE_USER_DEFAULT, 0, &st, 0, buf, 255 ) )
751 return QString::fromUcs2( (ushort*)buf );
752 } , {
753 char buf[255];
754 if ( GetDateFormatA( LOCALE_USER_DEFAULT, 0, &st, 0, (char*)&buf, 255 ) )
755 return QString::fromLocal8Bit( buf );
756 } );
757#endif
758 return QString::null;
759 }
760 default:
761#ifndef QT_NO_TEXTDATE
762 case Qt::TextDate:
763 {
764 QString buf = shortDayName( dayOfWeek() );
765 buf += ' ';
766 buf += shortMonthName( m );
767 QString t;
768 t.sprintf( " %d %d", d, y );
769 buf += t;
770 return buf;
771 }
772#endif
773 case Qt::ISODate:
774 {
775 QString month( QString::number( m ).rightJustify( 2, '0' ) );
776 QString day( QString::number( d ).rightJustify( 2, '0' ) );
777 return QString::number( y ) + "-" + month + "-" + day;
778 }
779 }
780}
781#endif //QT_NO_SPRINTF
782
783/*!
784 Returns the date as a string. The \a format parameter determines
785 the format of the result string.
786
787 These expressions may be used:
788
789 \table
790 \header \i Expression \i Output
791 \row \i d \i the day as number without a leading zero (1-31)
792 \row \i dd \i the day as number with a leading zero (01-31)
793 \row \i ddd
794 \i the abbreviated localized day name (e.g. 'Mon'..'Sun').
795 Uses QDate::shortDayName().
796 \row \i dddd
797 \i the long localized day name (e.g. 'Monday'..'Sunday').
798 Uses QDate::longDayName().
799 \row \i M \i the month as number without a leading zero (1-12)
800 \row \i MM \i the month as number with a leading zero (01-12)
801 \row \i MMM
802 \i the abbreviated localized month name (e.g. 'Jan'..'Dec').
803 Uses QDate::shortMonthName().
804 \row \i MMMM
805 \i the long localized month name (e.g. 'January'..'December').
806 Uses QDate::longMonthName().
807 \row \i yy \i the year as two digit number (00-99)
808 \row \i yyyy \i the year as four digit number (1752-8000)
809 \endtable
810
811 All other input characters will be ignored.
812
813 Example format strings (assuming that the QDate is the
814 20<sup><small>th</small></sup> July 1969):
815 \table
816 \header \i Format \i Result
817 \row \i dd.MM.yyyy \i11 20.07.1969
818 \row \i ddd MMMM d yy \i11 Sun July 20 69
819 \endtable
820
821 If the date is an invalid date, then QString::null will be returned.
822
823 \sa QDateTime::toString() QTime::toString()
824
825*/
826QString QDate::toString( const QString& format ) const
827{
828 return fmtDateTime( format, 0, this );
829}
830#endif //QT_NO_DATESTRING
831
832/*!
833 Sets the date's year \a y, month \a m and day \a d.
834
835 \a y must be in the range 1752..8000, \a m must be in the range
836 1..12, and \a d must be in the range 1..31.
837
838 \warning If \a y is in the range 0..99, it is interpreted as
839 1900..1999.
840
841 Returns TRUE if the date is valid; otherwise returns FALSE.
842*/
843
844bool QDate::setYMD( int y, int m, int d )
845{
846 if ( year() == y && month() == m && day() == d )
847 return isValid();
848 if ( !isValid(y,m,d) ) {
849#if defined(QT_CHECK_RANGE)
850 qWarning( "QDate::setYMD: Invalid date %04d-%02d-%02d", y, m, d );
851#endif
852 return FALSE;
853 }
854 jd = gregorianToJulian( y, m, d );
855 return TRUE;
856}
857
858/*!
859 Returns a QDate object containing a date \a ndays later than the
860 date of this object (or earlier if \a ndays is negative).
861
862 \sa addMonths() addYears() daysTo()
863*/
864
865QDate QDate::addDays( int ndays ) const
866{
867 QDate d;
868 d.jd = jd + ndays;
869 return d;
870}
871
872/*!
873 Returns a QDate object containing a date \a nmonths later than the
874 date of this object (or earlier if \a nmonths is negative).
875
876 \sa addDays() addYears()
877*/
878
879QDate QDate::addMonths( int nmonths ) const
880{
881 int y, m, d;
882 julianToGregorian( jd, y, m, d );
883
884 while ( nmonths != 0 ) {
885 if ( nmonths < 0 && nmonths + 12 <= 0 ) {
886 y--;
887 nmonths+=12;
888 } else if ( nmonths < 0 ) {
889 m+= nmonths;
890 nmonths = 0;
891 if ( m <= 0 ) {
892 --y;
893 m+=12;
894 }
895 } else if ( nmonths - 12 >= 0 ) {
896 y++;
897 nmonths-=12;
898 } else if ( m == 12 ) {
899 y++;
900 m = 0;
901 } else {
902 m+= nmonths;
903 nmonths = 0;
904 if ( m > 12 ) {
905 ++y;
906 m -= 12;
907 }
908 }
909 }
910
911 QDate tmp(y,m,1);
912
913 if( d > tmp.daysInMonth() )
914 d = tmp.daysInMonth();
915
916 QDate date(y, m, d);
917 return date;
918
919}
920
921/*!
922 Returns a QDate object containing a date \a nyears later than the
923 date of this object (or earlier if \a nyears is negative).
924
925 \sa addDays(), addMonths()
926*/
927
928QDate QDate::addYears( int nyears ) const
929{
930 int y, m, d;
931 julianToGregorian( jd, y, m, d );
932 y += nyears;
933
934 QDate tmp(y,m,1);
935
936 if( d > tmp.daysInMonth() )
937 d = tmp.daysInMonth();
938
939 QDate date(y, m, d);
940 return date;
941}
942
943
944
945/*!
946 Returns the number of days from this date to \a d (which is
947 negative if \a d is earlier than this date).
948
949 Example:
950 \code
951 QDate d1( 1995, 5, 17 ); // May 17th 1995
952 QDate d2( 1995, 5, 20 ); // May 20th 1995
953 d1.daysTo( d2 ); // returns 3
954 d2.daysTo( d1 ); // returns -3
955 \endcode
956
957 \sa addDays()
958*/
959
960int QDate::daysTo( const QDate &d ) const
961{
962 return d.jd - jd;
963}
964
965
966/*!
967 \fn bool QDate::operator==( const QDate &d ) const
968
969 Returns TRUE if this date is equal to \a d; otherwise returns FALSE.
970*/
971
972/*!
973 \fn bool QDate::operator!=( const QDate &d ) const
974
975 Returns TRUE if this date is different from \a d; otherwise returns FALSE.
976*/
977
978/*!
979 \fn bool QDate::operator<( const QDate &d ) const
980
981 Returns TRUE if this date is earlier than \a d, otherwise returns FALSE.
982*/
983
984/*!
985 \fn bool QDate::operator<=( const QDate &d ) const
986
987 Returns TRUE if this date is earlier than or equal to \a d,
988 otherwise returns FALSE.
989*/
990
991/*!
992 \fn bool QDate::operator>( const QDate &d ) const
993
994 Returns TRUE if this date is later than \a d, otherwise returns FALSE.
995*/
996
997/*!
998 \fn bool QDate::operator>=( const QDate &d ) const
999
1000 Returns TRUE if this date is later than or equal to \a d,
1001 otherwise returns FALSE.
1002*/
1003
1004/*!
1005 \overload
1006 Returns the current date, as reported by the system clock.
1007
1008 \sa QTime::currentTime(), QDateTime::currentDateTime()
1009*/
1010
1011QDate QDate::currentDate()
1012{
1013 return currentDate( Qt::LocalTime );
1014}
1015
1016/*!
1017 Returns the current date, as reported by the system clock, for the
1018 TimeSpec \a ts. The default TimeSpec is LocalTime.
1019
1020 \sa QTime::currentTime(), QDateTime::currentDateTime(), Qt::TimeSpec
1021*/
1022QDate QDate::currentDate( Qt::TimeSpec ts )
1023{
1024 QDate d;
1025#if defined(Q_OS_WIN32)
1026 SYSTEMTIME t;
1027 memset( &t, 0, sizeof(SYSTEMTIME) );
1028 if ( ts == Qt::LocalTime )
1029 GetLocalTime( &t );
1030 else
1031 GetSystemTime( &t );
1032 d.jd = gregorianToJulian( t.wYear, t.wMonth, t.wDay );
1033#else
1034 // posix compliant system
1035 time_t ltime;
1036 time( &ltime );
1037 tm *t;
1038
1039# if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
1040 // use the reentrant versions of localtime() and gmtime() where available
1041 tm res;
1042 if ( ts == Qt::LocalTime )
1043 t = localtime_r( &ltime, &res );
1044 else
1045 t = gmtime_r( &ltime, &res );
1046# else
1047 if ( ts == Qt::LocalTime )
1048 t = localtime( &ltime );
1049 else
1050 t = gmtime( &ltime );
1051# endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
1052
1053 d.jd = gregorianToJulian( t->tm_year + 1900, t->tm_mon + 1, t->tm_mday );
1054#endif
1055 return d;
1056}
1057
1058#ifndef QT_NO_DATESTRING
1059/*!
1060 Returns the QDate represented by the string \a s, using the format
1061 \a f, or an invalid date if the string cannot be parsed.
1062
1063 Note for \c Qt::TextDate: It is recommended that you use the
1064 English short month names (e.g. "Jan"). Although localized month
1065 names can also be used, they depend on the user's locale settings.
1066
1067 \warning \c Qt::LocalDate cannot be used here.
1068*/
1069QDate QDate::fromString( const QString& s, Qt::DateFormat f )
1070{
1071 if ( ( s.isEmpty() ) || ( f == Qt::LocalDate ) ) {
1072#if defined(QT_CHECK_RANGE)
1073 qWarning( "QDate::fromString: Parameter out of range" );
1074#endif
1075 QDate d;
1076 d.jd = 0;
1077 return d;
1078 }
1079 switch ( f ) {
1080 case Qt::ISODate:
1081 {
1082 int year( s.mid( 0, 4 ).toInt() );
1083 int month( s.mid( 5, 2 ).toInt() );
1084 int day( s.mid( 8, 2 ).toInt() );
1085 if ( year && month && day )
1086 return QDate( year, month, day );
1087 }
1088 break;
1089 default:
1090#ifndef QT_NO_TEXTDATE
1091 case Qt::TextDate:
1092 {
1093 /*
1094 This will fail gracefully if the input string doesn't
1095 contain any space.
1096 */
1097 int monthPos = s.find( ' ' ) + 1;
1098 int dayPos = s.find( ' ', monthPos ) + 1;
1099
1100 QString monthName( s.mid(monthPos, dayPos - monthPos - 1) );
1101 int month = -1;
1102
1103 // try English names first
1104 for ( int i = 0; i < 12; i++ ) {
1105 if ( monthName == qt_shortMonthNames[i] ) {
1106 month = i + 1;
1107 break;
1108 }
1109 }
1110
1111 // try the localized names
1112 if ( month == -1 ) {
1113 for ( int i = 0; i < 12; i++ ) {
1114 if ( monthName == shortMonthName( i + 1 ) ) {
1115 month = i + 1;
1116 break;
1117 }
1118 }
1119 }
1120#if defined(QT_CHECK_RANGE)
1121 if ( month < 1 || month > 12 ) {
1122 qWarning( "QDate::fromString: Parameter out of range" );
1123 QDate d;
1124 d.jd = 0;
1125 return d;
1126 }
1127#endif
1128 int day = s.mid( dayPos, 2 ).stripWhiteSpace().toInt();
1129 int year = s.right( 4 ).toInt();
1130 return QDate( year, month, day );
1131 }
1132#else
1133 break;
1134#endif
1135 }
1136 return QDate();
1137}
1138#endif //QT_NO_DATESTRING
1139
1140/*!
1141 \overload
1142
1143 Returns TRUE if the specified date (year \a y, month \a m and day
1144 \a d) is valid; otherwise returns FALSE.
1145
1146 Example:
1147 \code
1148 QDate::isValid( 2002, 5, 17 ); // TRUE May 17th 2002 is valid
1149 QDate::isValid( 2002, 2, 30 ); // FALSE Feb 30th does not exist
1150 QDate::isValid( 2004, 2, 29 ); // TRUE 2004 is a leap year
1151 QDate::isValid( 1202, 6, 6 ); // FALSE 1202 is pre-Gregorian
1152 \endcode
1153
1154 \warning A \a y value in the range 00..99 is interpreted as
1155 1900..1999.
1156
1157 \sa isNull(), setYMD()
1158*/
1159
1160bool QDate::isValid( int y, int m, int d )
1161{
1162 if ( y >= 0 && y <= 99 )
1163 y += 1900;
1164 else if ( y < FIRST_YEAR || (y == FIRST_YEAR && (m < 9 ||
1165 (m == 9 && d < 14))) )
1166 return FALSE;
1167 return (d > 0 && m > 0 && m <= 12) &&
1168 (d <= monthDays[m] || (d == 29 && m == 2 && leapYear(y)));
1169}
1170
1171/*!
1172 Returns TRUE if the specified year \a y is a leap year; otherwise
1173 returns FALSE.
1174*/
1175
1176bool QDate::leapYear( int y )
1177{
1178 return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
1179}
1180
1181/*!
1182 \internal
1183 Converts a Gregorian date to a Julian day.
1184 This algorithm is taken from Communications of the ACM, Vol 6, No 8.
1185 \sa julianToGregorian()
1186*/
1187
1188uint QDate::gregorianToJulian( int y, int m, int d )
1189{
1190 uint c, ya;
1191 if ( y <= 99 )
1192 y += 1900;
1193 if ( m > 2 ) {
1194 m -= 3;
1195 } else {
1196 m += 9;
1197 y--;
1198 }
1199 c = y; // NOTE: Sym C++ 6.0 bug
1200 c /= 100;
1201 ya = y - 100*c;
1202 return 1721119 + d + (146097*c)/4 + (1461*ya)/4 + (153*m+2)/5;
1203}
1204
1205/*!
1206 \internal
1207 Converts a Julian day to a Gregorian date.
1208 This algorithm is taken from Communications of the ACM, Vol 6, No 8.
1209 \sa gregorianToJulian()
1210*/
1211
1212void QDate::julianToGregorian( uint jd, int &y, int &m, int &d )
1213{
1214 uint x;
1215 uint j = jd - 1721119;
1216 y = (j*4 - 1)/146097;
1217 j = j*4 - 146097*y - 1;
1218 x = j/4;
1219 j = (x*4 + 3) / 1461;
1220 y = 100*y + j;
1221 x = (x*4) + 3 - 1461*j;
1222 x = (x + 4)/4;
1223 m = (5*x - 3)/153;
1224 x = 5*x - 3 - 153*m;
1225 d = (x + 5)/5;
1226 if ( m < 10 ) {
1227 m += 3;
1228 } else {
1229 m -= 9;
1230 y++;
1231 }
1232}
1233
1234
1235/*****************************************************************************
1236 QTime member functions
1237 *****************************************************************************/
1238
1239/*!
1240 \class QTime qdatetime.h
1241 \reentrant
1242
1243 \brief The QTime class provides clock time functions.
1244
1245 \ingroup time
1246 \mainclass
1247
1248 A QTime object contains a clock time, i.e. the number of hours,
1249 minutes, seconds, and milliseconds since midnight. It can read the
1250 current time from the system clock and measure a span of elapsed
1251 time. It provides functions for comparing times and for
1252 manipulating a time by adding a number of (milli)seconds.
1253
1254 QTime uses the 24-hour clock format; it has no concept of AM/PM.
1255 It operates in local time; it knows nothing about time zones or
1256 daylight savings time.
1257
1258 A QTime object is typically created either by giving the number of
1259 hours, minutes, seconds, and milliseconds explicitly, or by using
1260 the static function currentTime(), which creates a QTime object
1261 that contains the system's clock time. Note that the accuracy
1262 depends on the accuracy of the underlying operating system; not
1263 all systems provide 1-millisecond accuracy.
1264
1265 The hour(), minute(), second(), and msec() functions provide
1266 access to the number of hours, minutes, seconds, and milliseconds
1267 of the time. The same information is provided in textual format by
1268 the toString() function.
1269
1270 QTime provides a full set of operators to compare two QTime
1271 objects. One time is considered smaller than another if it is
1272 earlier than the other.
1273
1274 The time a given number of seconds or milliseconds later than a
1275 given time can be found using the addSecs() or addMSecs()
1276 functions. Correspondingly, the number of (milli)seconds between
1277 two times can be found using the secsTo() or msecsTo() functions.
1278
1279 QTime can be used to measure a span of elapsed time using the
1280 start(), restart(), and elapsed() functions.
1281
1282 \sa QDate, QDateTime
1283*/
1284
1285/*!
1286 \fn QTime::QTime()
1287
1288 Constructs the time 0 hours, minutes, seconds and milliseconds,
1289 i.e. 00:00:00.000 (midnight). This is a valid time.
1290
1291 \sa isValid()
1292*/
1293
1294/*!
1295 Constructs a time with hour \a h, minute \a m, seconds \a s and
1296 milliseconds \a ms.
1297
1298 \a h must be in the range 0..23, \a m and \a s must be in the
1299 range 0..59, and \a ms must be in the range 0..999.
1300
1301 \sa isValid()
1302*/
1303
1304QTime::QTime( int h, int m, int s, int ms )
1305{
1306 setHMS( h, m, s, ms );
1307}
1308
1309
1310/*!
1311 \fn bool QTime::isNull() const
1312
1313 Returns TRUE if the time is equal to 00:00:00.000; otherwise
1314 returns FALSE. A null time is valid.
1315
1316 \sa isValid()
1317*/
1318
1319/*!
1320 Returns TRUE if the time is valid; otherwise returns FALSE. The
1321 time 23:30:55.746 is valid, whereas 24:12:30 is invalid.
1322
1323 \sa isNull()
1324*/
1325
1326bool QTime::isValid() const
1327{
1328 return ds < MSECS_PER_DAY;
1329}
1330
1331
1332/*!
1333 Returns the hour part (0..23) of the time.
1334*/
1335
1336int QTime::hour() const
1337{
1338 return ds / MSECS_PER_HOUR;
1339}
1340
1341/*!
1342 Returns the minute part (0..59) of the time.
1343*/
1344
1345int QTime::minute() const
1346{
1347 return (ds % MSECS_PER_HOUR)/MSECS_PER_MIN;
1348}
1349
1350/*!
1351 Returns the second part (0..59) of the time.
1352*/
1353
1354int QTime::second() const
1355{
1356 return (ds / 1000)%SECS_PER_MIN;
1357}
1358
1359/*!
1360 Returns the millisecond part (0..999) of the time.
1361*/
1362
1363int QTime::msec() const
1364{
1365 return ds % 1000;
1366}
1367
1368#ifndef QT_NO_DATESTRING
1369#ifndef QT_NO_SPRINTF
1370/*!
1371 \overload
1372
1373 Returns the time as a string. Milliseconds are not included. The
1374 \a f parameter determines the format of the string.
1375
1376 If \a f is \c Qt::TextDate, the string format is HH:MM:SS; e.g. 1
1377 second before midnight would be "23:59:59".
1378
1379 If \a f is \c Qt::ISODate, the string format corresponds to the
1380 ISO 8601 extended specification for representations of dates,
1381 which is also HH:MM:SS.
1382
1383 If \a f is Qt::LocalDate, the string format depends on the locale
1384 settings of the system.
1385
1386 If the time is an invalid time, then QString::null will be returned.
1387*/
1388
1389QString QTime::toString( Qt::DateFormat f ) const
1390{
1391 if ( !isValid() )
1392 return QString::null;
1393
1394 switch ( f ) {
1395 case Qt::LocalDate:
1396 {
1397#ifndef Q_WS_WIN
1398 tm tt;
1399 memset( &tt, 0, sizeof( tm ) );
1400 char buf[255];
1401 tt.tm_sec = second();
1402 tt.tm_min = minute();
1403 tt.tm_hour = hour();
1404 if ( strftime( buf, sizeof(buf), "%X", &tt ) )
1405 return QString::fromLocal8Bit( buf );
1406#else
1407 SYSTEMTIME st;
1408 memset( &st, 0, sizeof(SYSTEMTIME) );
1409 st.wHour = hour();
1410 st.wMinute = minute();
1411 st.wSecond = second();
1412 st.wMilliseconds = 0;
1413 QT_WA( {
1414 TCHAR buf[255];
1415 if ( GetTimeFormat( LOCALE_USER_DEFAULT, 0, &st, 0, buf, 255 ) )
1416 return QString::fromUcs2( (ushort*)buf );
1417 } , {
1418 char buf[255];
1419 if ( GetTimeFormatA( LOCALE_USER_DEFAULT, 0, &st, 0, (char*)&buf, 255 ) )
1420 return QString::fromLocal8Bit( buf );
1421 } );
1422#endif
1423 return QString::null;
1424 }
1425 default:
1426 case Qt::ISODate:
1427 case Qt::TextDate:
1428 QString buf;
1429 buf.sprintf( "%.2d:%.2d:%.2d", hour(), minute(), second() );
1430 return buf;
1431 }
1432}
1433#endif
1434
1435/*!
1436 Returns the time as a string. The \a format parameter determines
1437 the format of the result string.
1438
1439 These expressions may be used:
1440
1441 \table
1442 \header \i Expression \i Output
1443 \row \i h
1444 \i the hour without a leading zero (0..23 or 1..12 if AM/PM display)
1445 \row \i hh
1446 \i the hour with a leading zero (00..23 or 01..12 if AM/PM display)
1447 \row \i m \i the minute without a leading zero (0..59)
1448 \row \i mm \i the minute with a leading zero (00..59)
1449 \row \i s \i the second whithout a leading zero (0..59)
1450 \row \i ss \i the second whith a leading zero (00..59)
1451 \row \i z \i the milliseconds without leading zeroes (0..999)
1452 \row \i zzz \i the milliseconds with leading zeroes (000..999)
1453 \row \i AP
1454 \i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
1455 \row \i ap
1456 \i use am/pm display. \e ap will be replaced by either "am" or "pm".
1457 \endtable
1458
1459 All other input characters will be ignored.
1460
1461 Example format strings (assuming that the QTime is 14:13:09.042)
1462
1463 \table
1464 \header \i Format \i Result
1465 \row \i hh:mm:ss.zzz \i11 14:13:09.042
1466 \row \i h:m:s ap \i11 2:13:9 pm
1467 \endtable
1468
1469 If the time is an invalid time, then QString::null will be returned.
1470
1471 \sa QDate::toString() QDateTime::toString()
1472*/
1473QString QTime::toString( const QString& format ) const
1474{
1475 return fmtDateTime( format, this, 0 );
1476}
1477#endif //QT_NO_DATESTRING
1478/*!
1479 Sets the time to hour \a h, minute \a m, seconds \a s and
1480 milliseconds \a ms.
1481
1482 \a h must be in the range 0..23, \a m and \a s must be in the
1483 range 0..59, and \a ms must be in the range 0..999. Returns TRUE
1484 if the set time is valid; otherwise returns FALSE.
1485
1486 \sa isValid()
1487*/
1488
1489bool QTime::setHMS( int h, int m, int s, int ms )
1490{
1491 if ( !isValid(h,m,s,ms) ) {
1492#if defined(QT_CHECK_RANGE)
1493 qWarning( "QTime::setHMS Invalid time %02d:%02d:%02d.%03d", h, m, s,
1494 ms );
1495#endif
1496 ds = MSECS_PER_DAY; // make this invalid
1497 return FALSE;
1498 }
1499 ds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
1500 return TRUE;
1501}
1502
1503/*!
1504 Returns a QTime object containing a time \a nsecs seconds later
1505 than the time of this object (or earlier if \a nsecs is negative).
1506
1507 Note that the time will wrap if it passes midnight.
1508
1509 Example:
1510 \code
1511 QTime n( 14, 0, 0 ); // n == 14:00:00
1512 QTime t;
1513 t = n.addSecs( 70 ); // t == 14:01:10
1514 t = n.addSecs( -70 ); // t == 13:58:50
1515 t = n.addSecs( 10*60*60 + 5 ); // t == 00:00:05
1516 t = n.addSecs( -15*60*60 ); // t == 23:00:00
1517 \endcode
1518
1519 \sa addMSecs(), secsTo(), QDateTime::addSecs()
1520*/
1521
1522QTime QTime::addSecs( int nsecs ) const
1523{
1524 return addMSecs( nsecs * 1000 );
1525}
1526
1527/*!
1528 Returns the number of seconds from this time to \a t (which is
1529 negative if \a t is earlier than this time).
1530
1531 Because QTime measures time within a day and there are 86400
1532 seconds in a day, the result is always between -86400 and 86400.
1533
1534 \sa addSecs() QDateTime::secsTo()
1535*/
1536
1537int QTime::secsTo( const QTime &t ) const
1538{
1539 return ((int)t.ds - (int)ds)/1000;
1540}
1541
1542/*!
1543 Returns a QTime object containing a time \a ms milliseconds later
1544 than the time of this object (or earlier if \a ms is negative).
1545
1546 Note that the time will wrap if it passes midnight. See addSecs()
1547 for an example.
1548
1549 \sa addSecs(), msecsTo()
1550*/
1551
1552QTime QTime::addMSecs( int ms ) const
1553{
1554 QTime t;
1555 if ( ms < 0 ) {
1556 // % not well-defined for -ve, but / is.
1557 int negdays = (MSECS_PER_DAY-ms) / MSECS_PER_DAY;
1558 t.ds = ((int)ds + ms + negdays*MSECS_PER_DAY)
1559 % MSECS_PER_DAY;
1560 } else {
1561 t.ds = ((int)ds + ms) % MSECS_PER_DAY;
1562 }
1563 return t;
1564}
1565
1566/*!
1567 Returns the number of milliseconds from this time to \a t (which
1568 is negative if \a t is earlier than this time).
1569
1570 Because QTime measures time within a day and there are 86400
1571 seconds in a day, the result is always between -86400000 and
1572 86400000 msec.
1573
1574 \sa secsTo()
1575*/
1576
1577int QTime::msecsTo( const QTime &t ) const
1578{
1579 return (int)t.ds - (int)ds;
1580}
1581
1582
1583/*!
1584 \fn bool QTime::operator==( const QTime &t ) const
1585
1586 Returns TRUE if this time is equal to \a t; otherwise returns FALSE.
1587*/
1588
1589/*!
1590 \fn bool QTime::operator!=( const QTime &t ) const
1591
1592 Returns TRUE if this time is different from \a t; otherwise returns FALSE.
1593*/
1594
1595/*!
1596 \fn bool QTime::operator<( const QTime &t ) const
1597
1598 Returns TRUE if this time is earlier than \a t; otherwise returns FALSE.
1599*/
1600
1601/*!
1602 \fn bool QTime::operator<=( const QTime &t ) const
1603
1604 Returns TRUE if this time is earlier than or equal to \a t;
1605 otherwise returns FALSE.
1606*/
1607
1608/*!
1609 \fn bool QTime::operator>( const QTime &t ) const
1610
1611 Returns TRUE if this time is later than \a t; otherwise returns FALSE.
1612*/
1613
1614/*!
1615 \fn bool QTime::operator>=( const QTime &t ) const
1616
1617 Returns TRUE if this time is later than or equal to \a t;
1618 otherwise returns FALSE.
1619*/
1620
1621
1622
1623/*!
1624 \overload
1625
1626 Returns the current time as reported by the system clock.
1627
1628 Note that the accuracy depends on the accuracy of the underlying
1629 operating system; not all systems provide 1-millisecond accuracy.
1630*/
1631
1632QTime QTime::currentTime()
1633{
1634 return currentTime( Qt::LocalTime );
1635}
1636
1637/*!
1638 Returns the current time as reported by the system clock, for the
1639 TimeSpec \a ts. The default TimeSpec is LocalTime.
1640
1641 Note that the accuracy depends on the accuracy of the underlying
1642 operating system; not all systems provide 1-millisecond accuracy.
1643
1644 \sa Qt::TimeSpec
1645*/
1646QTime QTime::currentTime( Qt::TimeSpec ts )
1647{
1648 QTime t;
1649 currentTime( &t, ts );
1650 return t;
1651}
1652
1653#ifndef QT_NO_DATESTRING
1654/*!
1655 Returns the representation \a s as a QTime using the format \a f,
1656 or an invalid time if this is not possible.
1657
1658 \warning Note that \c Qt::LocalDate cannot be used here.
1659*/
1660QTime QTime::fromString( const QString& s, Qt::DateFormat f )
1661{
1662 if ( ( s.isEmpty() ) || ( f == Qt::LocalDate ) ) {
1663#if defined(QT_CHECK_RANGE)
1664 qWarning( "QTime::fromString: Parameter out of range" );
1665#endif
1666 QTime t;
1667 t.ds = MSECS_PER_DAY;
1668 return t;
1669 }
1670
1671 int hour( s.mid( 0, 2 ).toInt() );
1672 int minute( s.mid( 3, 2 ).toInt() );
1673 int second( s.mid( 6, 2 ).toInt() );
1674 int msec( s.mid( 9, 3 ).toInt() );
1675 return QTime( hour, minute, second, msec );
1676}
1677#endif
1678
1679/*!
1680 \internal
1681 \obsolete
1682
1683 Fetches the current time and returns TRUE if the time is within one
1684 minute after midnight, otherwise FALSE. The return value is used by
1685 QDateTime::currentDateTime() to ensure that the date there is correct.
1686*/
1687
1688bool QTime::currentTime( QTime *ct )
1689{
1690 return currentTime( ct, Qt::LocalTime );
1691}
1692
1693
1694/*!
1695 \internal
1696
1697 Fetches the current time, for the TimeSpec \a ts, and returns TRUE
1698 if the time is within one minute after midnight, otherwise FALSE. The
1699 return value is used by QDateTime::currentDateTime() to ensure that
1700 the date there is correct. The default TimeSpec is LocalTime.
1701
1702 \sa Qt::TimeSpec
1703*/
1704bool QTime::currentTime( QTime *ct, Qt::TimeSpec ts )
1705{
1706 if ( !ct ) {
1707#if defined(QT_CHECK_NULL)
1708 qWarning( "QTime::currentTime(QTime *): Null pointer not allowed" );
1709#endif
1710 return FALSE;
1711 }
1712
1713#if defined(Q_OS_WIN32)
1714 SYSTEMTIME t;
1715 if ( ts == Qt::LocalTime ) {
1716 GetLocalTime( &t );
1717 } else {
1718 GetSystemTime( &t );
1719 }
1720 ct->ds = (uint)( MSECS_PER_HOUR*t.wHour + MSECS_PER_MIN*t.wMinute +
1721 1000*t.wSecond + t.wMilliseconds );
1722#elif defined(Q_OS_UNIX)
1723 // posix compliant system
1724 struct timeval tv;
1725 gettimeofday( &tv, 0 );
1726 time_t ltime = tv.tv_sec;
1727 tm *t;
1728
1729# if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
1730 // use the reentrant versions of localtime() and gmtime() where available
1731 tm res;
1732 if ( ts == Qt::LocalTime )
1733 t = localtime_r( &ltime, &res );
1734 else
1735 t = gmtime_r( &ltime, &res );
1736# else
1737 if ( ts == Qt::LocalTime )
1738 t = localtime( &ltime );
1739 else
1740 t = gmtime( &ltime );
1741# endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
1742
1743 ct->ds = (uint)( MSECS_PER_HOUR * t->tm_hour + MSECS_PER_MIN * t->tm_min +
1744 1000 * t->tm_sec + tv.tv_usec / 1000 );
1745#else
1746 time_t ltime; // no millisecond resolution
1747 ::time( &ltime );
1748 tm *t;
1749 if ( ts == Qt::LocalTime )
1750 localtime( &ltime );
1751 else
1752 gmtime( &ltime );
1753 ct->ds = (uint) ( MSECS_PER_HOUR * t->tm_hour + MSECS_PER_MIN * t->tm_min +
1754 1000 * t->tm_sec );
1755#endif
1756 // 00:00.00 to 00:00.59.999 is considered as "midnight or right after"
1757 return ct->ds < (uint) MSECS_PER_MIN;
1758}
1759
1760/*!
1761 \overload
1762
1763 Returns TRUE if the specified time is valid; otherwise returns
1764 FALSE.
1765
1766 The time is valid if \a h is in the range 0..23, \a m and \a s are
1767 in the range 0..59, and \a ms is in the range 0..999.
1768
1769 Example:
1770 \code
1771 QTime::isValid(21, 10, 30); // returns TRUE
1772 QTime::isValid(22, 5, 62); // returns FALSE
1773 \endcode
1774*/
1775
1776bool QTime::isValid( int h, int m, int s, int ms )
1777{
1778 return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
1779}
1780
1781
1782/*!
1783 Sets this time to the current time. This is practical for timing:
1784
1785 \code
1786 QTime t;
1787 t.start();
1788 some_lengthy_task();
1789 qDebug( "Time elapsed: %d ms", t.elapsed() );
1790 \endcode
1791
1792 \sa restart(), elapsed(), currentTime()
1793*/
1794
1795void QTime::start()
1796{
1797 *this = currentTime();
1798}
1799
1800/*!
1801 Sets this time to the current time and returns the number of
1802 milliseconds that have elapsed since the last time start() or
1803 restart() was called.
1804
1805 This function is guaranteed to be atomic and is thus very handy
1806 for repeated measurements. Call start() to start the first
1807 measurement and then restart() for each later measurement.
1808
1809 Note that the counter wraps to zero 24 hours after the last call
1810 to start() or restart().
1811
1812 \warning If the system's clock setting has been changed since the
1813 last time start() or restart() was called, the result is
1814 undefined. This can happen when daylight savings time is turned on
1815 or off.
1816
1817 \sa start(), elapsed(), currentTime()
1818*/
1819
1820int QTime::restart()
1821{
1822 QTime t = currentTime();
1823 int n = msecsTo( t );
1824 if ( n < 0 ) // passed midnight
1825 n += 86400*1000;
1826 *this = t;
1827 return n;
1828}
1829
1830/*!
1831 Returns the number of milliseconds that have elapsed since the
1832 last time start() or restart() was called.
1833
1834 Note that the counter wraps to zero 24 hours after the last call
1835 to start() or restart.
1836
1837 Note that the accuracy depends on the accuracy of the underlying
1838 operating system; not all systems provide 1-millisecond accuracy.
1839
1840 \warning If the system's clock setting has been changed since the
1841 last time start() or restart() was called, the result is
1842 undefined. This can happen when daylight savings time is turned on
1843 or off.
1844
1845 \sa start(), restart()
1846*/
1847
1848int QTime::elapsed() const
1849{
1850 int n = msecsTo( currentTime() );
1851 if ( n < 0 ) // passed midnight
1852 n += 86400*1000;
1853 return n;
1854}
1855
1856
1857/*****************************************************************************
1858 QDateTime member functions
1859 *****************************************************************************/
1860
1861/*!
1862 \class QDateTime qdatetime.h
1863 \reentrant
1864 \brief The QDateTime class provides date and time functions.
1865
1866 \ingroup time
1867 \mainclass
1868
1869 A QDateTime object contains a calendar date and a clock time (a
1870 "datetime"). It is a combination of the QDate and QTime classes.
1871 It can read the current datetime from the system clock. It
1872 provides functions for comparing datetimes and for manipulating a
1873 datetime by adding a number of seconds, days, months or years.
1874
1875 A QDateTime object is typically created either by giving a date
1876 and time explicitly in the constructor, or by using the static
1877 function currentDateTime(), which returns a QDateTime object set
1878 to the system clock's time. The date and time can be changed with
1879 setDate() and setTime(). A datetime can also be set using the
1880 setTime_t() function, which takes a POSIX-standard "number of
1881 seconds since 00:00:00 on January 1, 1970" value. The fromString()
1882 function returns a QDateTime given a string and a date format
1883 which is used to interpret the date within the string.
1884
1885 The date() and time() functions provide access to the date and
1886 time parts of the datetime. The same information is provided in
1887 textual format by the toString() function.
1888
1889 QDateTime provides a full set of operators to compare two
1890 QDateTime objects where smaller means earlier and larger means
1891 later.
1892
1893 You can increment (or decrement) a datetime by a given number of
1894 seconds using addSecs() or days using addDays(). Similarly you can
1895 use addMonths() and addYears(). The daysTo() function returns the
1896 number of days between two datetimes, and secsTo() returns the
1897 number of seconds between two datetimes.
1898
1899 The range of a datetime object is constrained to the ranges of the
1900 QDate and QTime objects which it embodies.
1901
1902 \sa QDate QTime QDateTimeEdit
1903*/
1904
1905
1906/*!
1907 \fn QDateTime::QDateTime()
1908
1909 Constructs a null datetime (i.e. null date and null time). A null
1910 datetime is invalid, since the date is invalid.
1911
1912 \sa isValid()
1913*/
1914
1915
1916/*!
1917 Constructs a datetime with date \a date and null (but valid) time
1918 (00:00:00.000).
1919*/
1920
1921QDateTime::QDateTime( const QDate &date )
1922 : d(date)
1923{
1924}
1925
1926/*!
1927 Constructs a datetime with date \a date and time \a time.
1928*/
1929
1930QDateTime::QDateTime( const QDate &date, const QTime &time )
1931 : d(date), t(time)
1932{
1933}
1934
1935
1936/*!
1937 \fn bool QDateTime::isNull() const
1938
1939 Returns TRUE if both the date and the time are null; otherwise
1940 returns FALSE. A null datetime is invalid.
1941
1942 \sa QDate::isNull(), QTime::isNull()
1943*/
1944
1945/*!
1946 \fn bool QDateTime::isValid() const
1947
1948 Returns TRUE if both the date and the time are valid; otherwise
1949 returns FALSE.
1950
1951 \sa QDate::isValid(), QTime::isValid()
1952*/
1953
1954/*!
1955 \fn QDate QDateTime::date() const
1956
1957 Returns the date part of the datetime.
1958
1959 \sa setDate(), time()
1960*/
1961
1962/*!
1963 \fn QTime QDateTime::time() const
1964
1965 Returns the time part of the datetime.
1966
1967 \sa setTime(), date()
1968*/
1969
1970/*!
1971 \fn void QDateTime::setDate( const QDate &date )
1972
1973 Sets the date part of this datetime to \a date.
1974
1975 \sa date(), setTime()
1976*/
1977
1978/*!
1979 \fn void QDateTime::setTime( const QTime &time )
1980
1981 Sets the time part of this datetime to \a time.
1982
1983 \sa time(), setDate()
1984*/
1985
1986
1987/*!
1988 Returns the datetime as the number of seconds that have passed
1989 since 1970-01-01T00:00:00, Coordinated Universal Time (UTC).
1990
1991 On systems that do not support timezones, this function will
1992 behave as if local time were UTC.
1993
1994 \sa setTime_t()
1995*/
1996
1997uint QDateTime::toTime_t() const
1998{
1999 tm brokenDown;
2000 brokenDown.tm_sec = t.second();
2001 brokenDown.tm_min = t.minute();
2002 brokenDown.tm_hour = t.hour();
2003 brokenDown.tm_mday = d.day();
2004 brokenDown.tm_mon = d.month() - 1;
2005 brokenDown.tm_year = d.year() - 1900;
2006 brokenDown.tm_isdst = -1;
2007 int secsSince1Jan1970UTC = (int) mktime( &brokenDown );
2008 if ( secsSince1Jan1970UTC < -1 )
2009 secsSince1Jan1970UTC = -1;
2010 return (uint) secsSince1Jan1970UTC;
2011}
2012
2013/*!
2014 \overload
2015
2016 Convenience function that sets the date and time to local time
2017 based on the given UTC time.
2018*/
2019
2020void QDateTime::setTime_t( uint secsSince1Jan1970UTC )
2021{
2022 setTime_t( secsSince1Jan1970UTC, Qt::LocalTime );
2023}
2024
2025/*!
2026 Sets the date and time to \a ts time (\c Qt::LocalTime or \c
2027 Qt::UTC) given the number of seconds that have passed since
2028 1970-01-01T00:00:00, Coordinated Universal Time (UTC). On systems
2029 that do not support timezones this function will behave as if
2030 local time were UTC.
2031
2032 On Windows, only a subset of \a secsSince1Jan1970UTC values are
2033 supported, as Windows starts counting from 1980.
2034
2035 \sa toTime_t()
2036*/
2037void QDateTime::setTime_t( uint secsSince1Jan1970UTC, Qt::TimeSpec ts )
2038{
2039 time_t tmp = (time_t) secsSince1Jan1970UTC;
2040 tm *brokenDown = 0;
2041
2042#if defined(Q_OS_UNIX) && defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
2043 // posix compliant system
2044 // use the reentrant versions of localtime() and gmtime() where available
2045 tm res;
2046 if ( ts == Qt::LocalTime )
2047 brokenDown = localtime_r( &tmp, &res );
2048 if ( !brokenDown ) {
2049 brokenDown = gmtime_r( &tmp, &res );
2050 if ( !brokenDown ) {
2051 d.jd = QDate::gregorianToJulian( 1970, 1, 1 );
2052 t.ds = 0;
2053 return;
2054 }
2055 }
2056#else
2057 if ( ts == Qt::LocalTime )
2058 brokenDown = localtime( &tmp );
2059 if ( !brokenDown ) {
2060 brokenDown = gmtime( &tmp );
2061 if ( !brokenDown ) {
2062 d.jd = QDate::gregorianToJulian( 1970, 1, 1 );
2063 t.ds = 0;
2064 return;
2065 }
2066 }
2067#endif
2068
2069 d.jd = QDate::gregorianToJulian( brokenDown->tm_year + 1900,
2070 brokenDown->tm_mon + 1,
2071 brokenDown->tm_mday );
2072 t.ds = MSECS_PER_HOUR * brokenDown->tm_hour +
2073 MSECS_PER_MIN * brokenDown->tm_min +
2074 1000 * brokenDown->tm_sec;
2075}
2076#ifndef QT_NO_DATESTRING
2077#ifndef QT_NO_SPRINTF
2078/*!
2079 \overload
2080
2081 Returns the datetime as a string. The \a f parameter determines
2082 the format of the string.
2083
2084 If \a f is \c Qt::TextDate, the string format is "Wed May 20
2085 03:40:13 1998" (using QDate::shortDayName(), QDate::shortMonthName(),
2086 and QTime::toString() to generate the string, so the day and month
2087 names will have localized names).
2088
2089 If \a f is \c Qt::ISODate, the string format corresponds to the
2090 ISO 8601 extended specification for representations of dates and
2091 times, which is YYYY-MM-DDTHH:MM:SS.
2092
2093 If \a f is \c Qt::LocalDate, the string format depends on the
2094 locale settings of the system.
2095
2096 If the format \a f is invalid or the datetime is invalid, toString()
2097 returns a null string.
2098
2099 \sa QDate::toString() QTime::toString()
2100*/
2101
2102QString QDateTime::toString( Qt::DateFormat f ) const
2103{
2104 if ( !isValid() )
2105 return QString::null;
2106
2107 if ( f == Qt::ISODate ) {
2108 return d.toString( Qt::ISODate ) + "T" + t.toString( Qt::ISODate );
2109 }
2110#ifndef QT_NO_TEXTDATE
2111 else if ( f == Qt::TextDate ) {
2112#ifndef Q_WS_WIN
2113 QString buf = d.shortDayName( d.dayOfWeek() );
2114 buf += ' ';
2115 buf += d.shortMonthName( d.month() );
2116 buf += ' ';
2117 buf += QString().setNum( d.day() );
2118 buf += ' ';
2119#else
2120 QString buf;
2121 QString winstr;
2122 QT_WA( {
2123 TCHAR out[255];
2124 GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_ILDATE, out, 255 );
2125 winstr = QString::fromUcs2( (ushort*)out );
2126 } , {
2127 char out[255];
2128 GetLocaleInfoA( LOCALE_USER_DEFAULT, LOCALE_ILDATE, (char*)&out, 255 );
2129 winstr = QString::fromLocal8Bit( out );
2130 } );
2131 switch ( winstr.toInt() ) {
2132 case 1:
2133 buf = d.shortDayName( d.dayOfWeek() ) + " " + QString().setNum( d.day() ) + ". " + d.shortMonthName( d.month() ) + " ";
2134 break;
2135 default:
2136 buf = d.shortDayName( d.dayOfWeek() ) + " " + d.shortMonthName( d.month() ) + " " + QString().setNum( d.day() ) + " ";
2137 break;
2138 }
2139#endif
2140 buf += t.toString();
2141 buf += ' ';
2142 buf += QString().setNum( d.year() );
2143 return buf;
2144 }
2145#endif
2146 else if ( f == Qt::LocalDate ) {
2147 return d.toString( Qt::LocalDate ) + " " + t.toString( Qt::LocalDate );
2148 }
2149 return QString::null;
2150}
2151#endif
2152
2153/*!
2154 Returns the datetime as a string. The \a format parameter
2155 determines the format of the result string.
2156
2157 These expressions may be used for the date:
2158
2159 \table
2160 \header \i Expression \i Output
2161 \row \i d \i the day as number without a leading zero (1-31)
2162 \row \i dd \i the day as number with a leading zero (01-31)
2163 \row \i ddd
2164 \i the abbreviated localized day name (e.g. 'Mon'..'Sun').
2165 Uses QDate::shortDayName().
2166 \row \i dddd
2167 \i the long localized day name (e.g. 'Monday'..'Sunday').
2168 Uses QDate::longDayName().
2169 \row \i M \i the month as number without a leading zero (1-12)
2170 \row \i MM \i the month as number with a leading zero (01-12)
2171 \row \i MMM
2172 \i the abbreviated localized month name (e.g. 'Jan'..'Dec').
2173 Uses QDate::shortMonthName().
2174 \row \i MMMM
2175 \i the long localized month name (e.g. 'January'..'December').
2176 Uses QDate::longMonthName().
2177 \row \i yy \i the year as two digit number (00-99)
2178 \row \i yyyy \i the year as four digit number (1752-8000)
2179 \endtable
2180
2181 These expressions may be used for the time:
2182
2183 \table
2184 \header \i Expression \i Output
2185 \row \i h
2186 \i the hour without a leading zero (0..23 or 1..12 if AM/PM display)
2187 \row \i hh
2188 \i the hour with a leading zero (00..23 or 01..12 if AM/PM display)
2189 \row \i m \i the minute without a leading zero (0..59)
2190 \row \i mm \i the minute with a leading zero (00..59)
2191 \row \i s \i the second whithout a leading zero (0..59)
2192 \row \i ss \i the second whith a leading zero (00..59)
2193 \row \i z \i the milliseconds without leading zeroes (0..999)
2194 \row \i zzz \i the milliseconds with leading zeroes (000..999)
2195 \row \i AP
2196 \i use AM/PM display. \e AP will be replaced by either "AM" or "PM".
2197 \row \i ap
2198 \i use am/pm display. \e ap will be replaced by either "am" or "pm".
2199 \endtable
2200
2201 All other input characters will be ignored.
2202
2203 Example format strings (assumed that the QDateTime is
2204 21<small><sup>st</sup></small> May 2001 14:13:09)
2205
2206 \table
2207 \header \i Format \i Result
2208 \row \i dd.MM.yyyy \i11 21.05.2001
2209 \row \i ddd MMMM d yy \i11 Tue May 21 01
2210 \row \i hh:mm:ss.zzz \i11 14:13:09.042
2211 \row \i h:m:s ap \i11 2:13:9 pm
2212 \endtable
2213
2214 If the datetime is an invalid datetime, then QString::null will be returned.
2215
2216 \sa QDate::toString() QTime::toString()
2217*/
2218QString QDateTime::toString( const QString& format ) const
2219{
2220 return fmtDateTime( format, &t, &d );
2221}
2222#endif //QT_NO_DATESTRING
2223
2224/*!
2225 Returns a QDateTime object containing a datetime \a ndays days
2226 later than the datetime of this object (or earlier if \a ndays is
2227 negative).
2228
2229 \sa daysTo(), addMonths(), addYears(), addSecs()
2230*/
2231
2232QDateTime QDateTime::addDays( int ndays ) const
2233{
2234 return QDateTime( d.addDays(ndays), t );
2235}
2236
2237/*!
2238 Returns a QDateTime object containing a datetime \a nmonths months
2239 later than the datetime of this object (or earlier if \a nmonths
2240 is negative).
2241
2242 \sa daysTo(), addDays(), addYears(), addSecs()
2243*/
2244
2245QDateTime QDateTime::addMonths( int nmonths ) const
2246{
2247 return QDateTime( d.addMonths(nmonths), t );
2248}
2249
2250/*!
2251 Returns a QDateTime object containing a datetime \a nyears years
2252 later than the datetime of this object (or earlier if \a nyears is
2253 negative).
2254
2255 \sa daysTo(), addDays(), addMonths(), addSecs()
2256*/
2257
2258QDateTime QDateTime::addYears( int nyears ) const
2259{
2260 return QDateTime( d.addYears(nyears), t );
2261}
2262
2263/*!
2264 Returns a QDateTime object containing a datetime \a nsecs seconds
2265 later than the datetime of this object (or earlier if \a nsecs is
2266 negative).
2267
2268 \sa secsTo(), addDays(), addMonths(), addYears()
2269*/
2270
2271QDateTime QDateTime::addSecs( int nsecs ) const
2272{
2273 uint dd = d.jd;
2274 int tt = t.ds;
2275 int sign = 1;
2276 if ( nsecs < 0 ) {
2277 nsecs = -nsecs;
2278 sign = -1;
2279 }
2280 if ( nsecs >= (int)SECS_PER_DAY ) {
2281 dd += sign*(nsecs/SECS_PER_DAY);
2282 nsecs %= SECS_PER_DAY;
2283 }
2284 tt += sign*nsecs*1000;
2285 if ( tt < 0 ) {
2286 tt = MSECS_PER_DAY - tt - 1;
2287 dd -= tt / MSECS_PER_DAY;
2288 tt = tt % MSECS_PER_DAY;
2289 tt = MSECS_PER_DAY - tt - 1;
2290 } else if ( tt >= (int)MSECS_PER_DAY ) {
2291 dd += ( tt / MSECS_PER_DAY );
2292 tt = tt % MSECS_PER_DAY;
2293 }
2294 QDateTime ret;
2295 ret.t.ds = tt;
2296 ret.d.jd = dd;
2297 return ret;
2298}
2299
2300/*!
2301 Returns the number of days from this datetime to \a dt (which is
2302 negative if \a dt is earlier than this datetime).
2303
2304 \sa addDays(), secsTo()
2305*/
2306
2307int QDateTime::daysTo( const QDateTime &dt ) const
2308{
2309 return d.daysTo( dt.d );
2310}
2311
2312/*!
2313 Returns the number of seconds from this datetime to \a dt (which
2314 is negative if \a dt is earlier than this datetime).
2315
2316 Example:
2317 \code
2318 QDateTime dt = QDateTime::currentDateTime();
2319 QDateTime xmas( QDate(dt.date().year(),12,24), QTime(17,00) );
2320 qDebug( "There are %d seconds to Christmas", dt.secsTo(xmas) );
2321 \endcode
2322
2323 \sa addSecs(), daysTo(), QTime::secsTo()
2324*/
2325
2326int QDateTime::secsTo( const QDateTime &dt ) const
2327{
2328 return t.secsTo(dt.t) + d.daysTo(dt.d)*SECS_PER_DAY;
2329}
2330
2331
2332/*!
2333 Returns TRUE if this datetime is equal to \a dt; otherwise returns FALSE.
2334
2335 \sa operator!=()
2336*/
2337
2338bool QDateTime::operator==( const QDateTime &dt ) const
2339{
2340 return t == dt.t && d == dt.d;
2341}
2342
2343/*!
2344 Returns TRUE if this datetime is different from \a dt; otherwise
2345 returns FALSE.
2346
2347 \sa operator==()
2348*/
2349
2350bool QDateTime::operator!=( const QDateTime &dt ) const
2351{
2352 return t != dt.t || d != dt.d;
2353}
2354
2355/*!
2356 Returns TRUE if this datetime is earlier than \a dt; otherwise
2357 returns FALSE.
2358*/
2359
2360bool QDateTime::operator<( const QDateTime &dt ) const
2361{
2362 if ( d < dt.d )
2363 return TRUE;
2364 return d == dt.d ? t < dt.t : FALSE;
2365}
2366
2367/*!
2368 Returns TRUE if this datetime is earlier than or equal to \a dt;
2369 otherwise returns FALSE.
2370*/
2371
2372bool QDateTime::operator<=( const QDateTime &dt ) const
2373{
2374 if ( d < dt.d )
2375 return TRUE;
2376 return d == dt.d ? t <= dt.t : FALSE;
2377}
2378
2379/*!
2380 Returns TRUE if this datetime is later than \a dt; otherwise
2381 returns FALSE.
2382*/
2383
2384bool QDateTime::operator>( const QDateTime &dt ) const
2385{
2386 if ( d > dt.d )
2387 return TRUE;
2388 return d == dt.d ? t > dt.t : FALSE;
2389}
2390
2391/*!
2392 Returns TRUE if this datetime is later than or equal to \a dt;
2393 otherwise returns FALSE.
2394*/
2395
2396bool QDateTime::operator>=( const QDateTime &dt ) const
2397{
2398 if ( d > dt.d )
2399 return TRUE;
2400 return d == dt.d ? t >= dt.t : FALSE;
2401}
2402
2403/*!
2404 \overload
2405
2406 Returns the current datetime, as reported by the system clock.
2407
2408 \sa QDate::currentDate(), QTime::currentTime()
2409*/
2410
2411QDateTime QDateTime::currentDateTime()
2412{
2413 return currentDateTime( Qt::LocalTime );
2414}
2415
2416/*!
2417 Returns the current datetime, as reported by the system clock, for the
2418 TimeSpec \a ts. The default TimeSpec is LocalTime.
2419
2420 \sa QDate::currentDate(), QTime::currentTime(), Qt::TimeSpec
2421*/
2422
2423QDateTime QDateTime::currentDateTime( Qt::TimeSpec ts )
2424{
2425 QDateTime dt;
2426 QTime t;
2427 dt.setDate( QDate::currentDate(ts) );
2428 if ( QTime::currentTime(&t, ts) ) // midnight or right after?
2429 dt.setDate( QDate::currentDate(ts) ); // fetch date again
2430 dt.setTime( t );
2431 return dt;
2432}
2433
2434#ifndef QT_NO_DATESTRING
2435/*!
2436 Returns the QDateTime represented by the string \a s, using the
2437 format \a f, or an invalid datetime if this is not possible.
2438
2439 Note for \c Qt::TextDate: It is recommended that you use the
2440 English short month names (e.g. "Jan"). Although localized month
2441 names can also be used, they depend on the user's locale settings.
2442
2443 \warning Note that \c Qt::LocalDate cannot be used here.
2444*/
2445QDateTime QDateTime::fromString( const QString& s, Qt::DateFormat f )
2446{
2447 if ( ( s.isEmpty() ) || ( f == Qt::LocalDate ) ) {
2448#if defined(QT_CHECK_RANGE)
2449 qWarning( "QDateTime::fromString: Parameter out of range" );
2450#endif
2451 QDateTime dt;
2452 dt.d.jd = 0;
2453 return dt;
2454 }
2455 if ( f == Qt::ISODate ) {
2456 return QDateTime( QDate::fromString( s.mid(0,10), Qt::ISODate ),
2457 QTime::fromString( s.mid(11), Qt::ISODate ) );
2458 }
2459#if !defined(QT_NO_REGEXP) && !defined(QT_NO_TEXTDATE)
2460 else if ( f == Qt::TextDate ) {
2461 QString monthName( s.mid( 4, 3 ) );
2462 int month = -1;
2463 // Assume that English monthnames are the default
2464 for ( int i = 0; i < 12; ++i ) {
2465 if ( monthName == qt_shortMonthNames[i] ) {
2466 month = i + 1;
2467 break;
2468 }
2469 }
2470 // If English names can't be found, search the localized ones
2471 if ( month == -1 ) {
2472 for ( int i = 1; i <= 12; ++i ) {
2473 if ( monthName == QDate::shortMonthName( i ) ) {
2474 month = i;
2475 break;
2476 }
2477 }
2478 }
2479#if defined(QT_CHECK_RANGE)
2480 if ( month < 1 || month > 12 ) {
2481 qWarning( "QDateTime::fromString: Parameter out of range" );
2482 QDateTime dt;
2483 dt.d.jd = 0;
2484 return dt;
2485 }
2486#endif
2487 int day = s.mid( 8, 2 ).simplifyWhiteSpace().toInt();
2488 int year = s.right( 4 ).toInt();
2489 QDate date( year, month, day );
2490 QTime time;
2491 int hour, minute, second;
2492 int pivot = s.find( QRegExp(QString::fromLatin1("[0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) );
2493 if ( pivot != -1 ) {
2494 hour = s.mid( pivot, 2 ).toInt();
2495 minute = s.mid( pivot+3, 2 ).toInt();
2496 second = s.mid( pivot+6, 2 ).toInt();
2497 time.setHMS( hour, minute, second );
2498 }
2499 return QDateTime( date, time );
2500 }
2501#endif //QT_NO_REGEXP
2502 return QDateTime();
2503}
2504#endif //QT_NO_DATESTRING
2505
2506
2507/*****************************************************************************
2508 Date/time stream functions
2509 *****************************************************************************/
2510
2511#ifndef QT_NO_DATASTREAM
2512/*!
2513 \relates QDate
2514
2515 Writes the date, \a d, to the data stream, \a s.
2516
2517 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2518*/
2519
2520QDataStream &operator<<( QDataStream &s, const QDate &d )
2521{
2522 return s << (Q_UINT32)(d.jd);
2523}
2524
2525/*!
2526 \relates QDate
2527
2528 Reads a date from the stream \a s into \a d.
2529
2530 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2531*/
2532
2533QDataStream &operator>>( QDataStream &s, QDate &d )
2534{
2535 Q_UINT32 jd;
2536 s >> jd;
2537 d.jd = jd;
2538 return s;
2539}
2540
2541/*!
2542 \relates QTime
2543
2544 Writes time \a t to the stream \a s.
2545
2546 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2547*/
2548
2549QDataStream &operator<<( QDataStream &s, const QTime &t )
2550{
2551 return s << (Q_UINT32)(t.ds);
2552}
2553
2554/*!
2555 \relates QTime
2556
2557 Reads a time from the stream \a s into \a t.
2558
2559 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2560*/
2561
2562QDataStream &operator>>( QDataStream &s, QTime &t )
2563{
2564 Q_UINT32 ds;
2565 s >> ds;
2566 t.ds = ds;
2567 return s;
2568}
2569
2570/*!
2571 \relates QDateTime
2572
2573 Writes the datetime \a dt to the stream \a s.
2574
2575 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2576*/
2577
2578QDataStream &operator<<( QDataStream &s, const QDateTime &dt )
2579{
2580 return s << dt.d << dt.t;
2581}
2582
2583/*!
2584 \relates QDateTime
2585
2586 Reads a datetime from the stream \a s into \a dt.
2587
2588 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
2589*/
2590
2591QDataStream &operator>>( QDataStream &s, QDateTime &dt )
2592{
2593 s >> dt.d >> dt.t;
2594 return s;
2595}
2596#endif //QT_NO_DATASTREAM
Note: See TracBrowser for help on using the repository browser.