source: trunk/src/tools/qdatetime.cpp

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

Transferred Qt for OS/2 version 3.3.1-rc5 sources from the CVS

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