]> git.saurik.com Git - wxWidgets.git/blob - src/common/datetime.cpp
DJGPP compilation fixes
[wxWidgets.git] / src / common / datetime.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: wx/datetime.h
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 11.05.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
10 //
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
15 //
16 // Licence: wxWindows license
17 ///////////////////////////////////////////////////////////////////////////////
18
19 /*
20 * Implementation notes:
21 *
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
24 * expressed in GMT.
25 *
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
28 *
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
31 *
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
35 * or less)
36 *
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
40 * ToTimezone()
41 *
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
44 * wxDateTime::Tm.
45 */
46
47 // ============================================================================
48 // declarations
49 // ============================================================================
50
51 // ----------------------------------------------------------------------------
52 // headers
53 // ----------------------------------------------------------------------------
54
55 #ifdef __GNUG__
56 #pragma implementation "datetime.h"
57 #endif
58
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
61
62 #ifdef __BORLANDC__
63 #pragma hdrstop
64 #endif
65
66 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
67
68 #ifndef WX_PRECOMP
69 #include "wx/string.h"
70 #include "wx/log.h"
71 #endif // WX_PRECOMP
72
73 #include "wx/intl.h"
74 #include "wx/thread.h"
75 #include "wx/tokenzr.h"
76 #include "wx/module.h"
77
78 #define wxDEFINE_TIME_CONSTANTS // before including datetime.h
79
80 #include <ctype.h>
81
82 #include "wx/datetime.h"
83 #include "wx/timer.h" // for wxGetLocalTimeMillis()
84
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
88
89 #if defined(HAVE_STRPTIME) && defined(__LINUX__)
90 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
91 // crash (instead of just failing):
92 //
93 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
94 // strptime(buf, "%x", &tm);
95 //
96 // so don't use it
97 #undef HAVE_STRPTIME
98 #endif // broken strptime()
99
100 #ifndef WX_TIMEZONE
101 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
102 #define WX_TIMEZONE _timezone
103 #elif defined(__MWERKS__)
104 long wxmw_timezone = 28800;
105 #define WX_TIMEZONE wxmw_timezone;
106 #elif defined(__DJGPP__)
107 #include <sys/timeb.h>
108 static long wxGetTimeZone()
109 {
110 struct timeb tb;
111 ftime(&tb);
112 return tb.timezone;
113 }
114 #define WX_TIMEZONE wxGetTimeZone()
115 #else // unknown platform - try timezone
116 #define WX_TIMEZONE timezone
117 #endif
118 #endif // !WX_TIMEZONE
119
120 // ----------------------------------------------------------------------------
121 // macros
122 // ----------------------------------------------------------------------------
123
124 // debugging helper: just a convenient replacement of wxCHECK()
125 #define wxDATETIME_CHECK(expr, msg) \
126 if ( !(expr) ) \
127 { \
128 wxFAIL_MSG(msg); \
129 *this = wxInvalidDateTime; \
130 return *this; \
131 }
132
133 // ----------------------------------------------------------------------------
134 // private classes
135 // ----------------------------------------------------------------------------
136
137 class wxDateTimeHolidaysModule : public wxModule
138 {
139 public:
140 virtual bool OnInit()
141 {
142 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays);
143
144 return TRUE;
145 }
146
147 virtual void OnExit()
148 {
149 wxDateTimeHolidayAuthority::ClearAllAuthorities();
150 wxDateTimeHolidayAuthority::ms_authorities.Clear();
151 }
152
153 private:
154 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule)
155 };
156
157 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule, wxModule)
158
159 // ----------------------------------------------------------------------------
160 // constants
161 // ----------------------------------------------------------------------------
162
163 // some trivial ones
164 static const int MONTHS_IN_YEAR = 12;
165
166 static const int SEC_PER_MIN = 60;
167
168 static const int MIN_PER_HOUR = 60;
169
170 static const int HOURS_PER_DAY = 24;
171
172 static const long SECONDS_PER_DAY = 86400l;
173
174 static const int DAYS_PER_WEEK = 7;
175
176 static const long MILLISECONDS_PER_DAY = 86400000l;
177
178 // this is the integral part of JDN of the midnight of Jan 1, 1970
179 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
180 static const long EPOCH_JDN = 2440587l;
181
182 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
183 // reference date for us) is Nov 24, 4714BC
184 static const int JDN_0_YEAR = -4713;
185 static const int JDN_0_MONTH = wxDateTime::Nov;
186 static const int JDN_0_DAY = 24;
187
188 // the constants used for JDN calculations
189 static const long JDN_OFFSET = 32046l;
190 static const long DAYS_PER_5_MONTHS = 153l;
191 static const long DAYS_PER_4_YEARS = 1461l;
192 static const long DAYS_PER_400_YEARS = 146097l;
193
194 // this array contains the cumulated number of days in all previous months for
195 // normal and leap years
196 static const wxDateTime::wxDateTime_t gs_cumulatedDays[2][MONTHS_IN_YEAR] =
197 {
198 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
199 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
200 };
201
202 // ----------------------------------------------------------------------------
203 // global data
204 // ----------------------------------------------------------------------------
205
206 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
207 // indicate an invalid wxDateTime object
208
209 static const wxDateTime gs_dtDefault;
210
211 const wxDateTime& wxDefaultDateTime = gs_dtDefault;
212
213 wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
214
215 // ----------------------------------------------------------------------------
216 // private globals
217 // ----------------------------------------------------------------------------
218
219 // a critical section is needed to protect GetTimeZone() static
220 // variable in MT case
221 #if wxUSE_THREADS
222 static wxCriticalSection gs_critsectTimezone;
223 #endif // wxUSE_THREADS
224
225 // ----------------------------------------------------------------------------
226 // private functions
227 // ----------------------------------------------------------------------------
228
229 // debugger helper: shows what the date really is
230 #ifdef __WXDEBUG__
231 extern const wxChar *wxDumpDate(const wxDateTime* dt)
232 {
233 static wxChar buf[128];
234
235 wxStrcpy(buf, dt->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
236
237 return buf;
238 }
239 #endif // Debug
240
241 // get the number of days in the given month of the given year
242 static inline
243 wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
244 {
245 // the number of days in month in Julian/Gregorian calendar: the first line
246 // is for normal years, the second one is for the leap ones
247 static wxDateTime::wxDateTime_t daysInMonth[2][MONTHS_IN_YEAR] =
248 {
249 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
250 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
251 };
252
253 return daysInMonth[wxDateTime::IsLeapYear(year)][month];
254 }
255
256 // ensure that the timezone variable is set by calling localtime
257 static int GetTimeZone()
258 {
259 // set to TRUE when the timezone is set
260 static bool s_timezoneSet = FALSE;
261
262 wxCRIT_SECT_LOCKER(lock, gs_critsectTimezone);
263
264 if ( !s_timezoneSet )
265 {
266 // just call localtime() instead of figuring out whether this system
267 // supports tzset(), _tzset() or something else
268 time_t t = 0;
269
270 (void)localtime(&t);
271 s_timezoneSet = TRUE;
272 }
273
274 return (int)WX_TIMEZONE;
275 }
276
277 // return the integral part of the JDN for the midnight of the given date (to
278 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
279 // noon of the previous day)
280 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day,
281 wxDateTime::Month mon,
282 int year)
283 {
284 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
285
286 // check the date validity
287 wxASSERT_MSG(
288 (year > JDN_0_YEAR) ||
289 ((year == JDN_0_YEAR) && (mon > JDN_0_MONTH)) ||
290 ((year == JDN_0_YEAR) && (mon == JDN_0_MONTH) && (day >= JDN_0_DAY)),
291 _T("date out of range - can't convert to JDN")
292 );
293
294 // make the year positive to avoid problems with negative numbers division
295 year += 4800;
296
297 // months are counted from March here
298 int month;
299 if ( mon >= wxDateTime::Mar )
300 {
301 month = mon - 2;
302 }
303 else
304 {
305 month = mon + 10;
306 year--;
307 }
308
309 // now we can simply add all the contributions together
310 return ((year / 100) * DAYS_PER_400_YEARS) / 4
311 + ((year % 100) * DAYS_PER_4_YEARS) / 4
312 + (month * DAYS_PER_5_MONTHS + 2) / 5
313 + day
314 - JDN_OFFSET;
315 }
316
317 // this function is a wrapper around strftime(3)
318 static wxString CallStrftime(const wxChar *format, const tm* tm)
319 {
320 wxChar buf[4096];
321 if ( !wxStrftime(buf, WXSIZEOF(buf), format, tm) )
322 {
323 // buffer is too small?
324 wxFAIL_MSG(_T("strftime() failed"));
325 }
326
327 return wxString(buf);
328 }
329
330 // if year and/or month have invalid values, replace them with the current ones
331 static void ReplaceDefaultYearMonthWithCurrent(int *year,
332 wxDateTime::Month *month)
333 {
334 struct tm *tmNow = NULL;
335
336 if ( *year == wxDateTime::Inv_Year )
337 {
338 tmNow = wxDateTime::GetTmNow();
339
340 *year = 1900 + tmNow->tm_year;
341 }
342
343 if ( *month == wxDateTime::Inv_Month )
344 {
345 if ( !tmNow )
346 tmNow = wxDateTime::GetTmNow();
347
348 *month = (wxDateTime::Month)tmNow->tm_mon;
349 }
350 }
351
352 // fll the struct tm with default values
353 static void InitTm(struct tm& tm)
354 {
355 // struct tm may have etxra fields (undocumented and with unportable
356 // names) which, nevertheless, must be set to 0
357 memset(&tm, 0, sizeof(struct tm));
358
359 tm.tm_mday = 1; // mday 0 is invalid
360 tm.tm_year = 76; // any valid year
361 tm.tm_isdst = -1; // auto determine
362 }
363
364 // parsing helpers
365 // ---------------
366
367 // return the month if the string is a month name or Inv_Month otherwise
368 static wxDateTime::Month GetMonthFromName(const wxString& name, int flags)
369 {
370 wxDateTime::Month mon;
371 for ( mon = wxDateTime::Jan; mon < wxDateTime::Inv_Month; wxNextMonth(mon) )
372 {
373 // case-insensitive comparison either one of or with both abbreviated
374 // and not versions
375 if ( flags & wxDateTime::Name_Full )
376 {
377 if ( name.CmpNoCase(wxDateTime::
378 GetMonthName(mon, wxDateTime::Name_Full)) == 0 )
379 {
380 break;
381 }
382 }
383
384 if ( flags & wxDateTime::Name_Abbr )
385 {
386 if ( name.CmpNoCase(wxDateTime::
387 GetMonthName(mon, wxDateTime::Name_Abbr)) == 0 )
388 {
389 break;
390 }
391 }
392 }
393
394 return mon;
395 }
396
397 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
398 static wxDateTime::WeekDay GetWeekDayFromName(const wxString& name, int flags)
399 {
400 wxDateTime::WeekDay wd;
401 for ( wd = wxDateTime::Sun; wd < wxDateTime::Inv_WeekDay; wxNextWDay(wd) )
402 {
403 // case-insensitive comparison either one of or with both abbreviated
404 // and not versions
405 if ( flags & wxDateTime::Name_Full )
406 {
407 if ( name.CmpNoCase(wxDateTime::
408 GetWeekDayName(wd, wxDateTime::Name_Full)) == 0 )
409 {
410 break;
411 }
412 }
413
414 if ( flags & wxDateTime::Name_Abbr )
415 {
416 if ( name.CmpNoCase(wxDateTime::
417 GetWeekDayName(wd, wxDateTime::Name_Abbr)) == 0 )
418 {
419 break;
420 }
421 }
422 }
423
424 return wd;
425 }
426
427 // scans all digits (but no more than len) and returns the resulting number
428 static bool GetNumericToken(size_t len, const wxChar*& p, unsigned long *number)
429 {
430 size_t n = 1;
431 wxString s;
432 while ( wxIsdigit(*p) )
433 {
434 s += *p++;
435
436 if ( len && ++n > len )
437 break;
438 }
439
440 return !!s && s.ToULong(number);
441 }
442
443 // scans all alphabetic characters and returns the resulting string
444 static wxString GetAlphaToken(const wxChar*& p)
445 {
446 wxString s;
447 while ( wxIsalpha(*p) )
448 {
449 s += *p++;
450 }
451
452 return s;
453 }
454
455 // ============================================================================
456 // implementation of wxDateTime
457 // ============================================================================
458
459 // ----------------------------------------------------------------------------
460 // struct Tm
461 // ----------------------------------------------------------------------------
462
463 wxDateTime::Tm::Tm()
464 {
465 year = (wxDateTime_t)wxDateTime::Inv_Year;
466 mon = wxDateTime::Inv_Month;
467 mday = 0;
468 hour = min = sec = msec = 0;
469 wday = wxDateTime::Inv_WeekDay;
470 }
471
472 wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
473 : m_tz(tz)
474 {
475 msec = 0;
476 sec = tm.tm_sec;
477 min = tm.tm_min;
478 hour = tm.tm_hour;
479 mday = tm.tm_mday;
480 mon = (wxDateTime::Month)tm.tm_mon;
481 year = 1900 + tm.tm_year;
482 wday = tm.tm_wday;
483 yday = tm.tm_yday;
484 }
485
486 bool wxDateTime::Tm::IsValid() const
487 {
488 // we allow for the leap seconds, although we don't use them (yet)
489 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
490 (mday <= GetNumOfDaysInMonth(year, mon)) &&
491 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
492 }
493
494 void wxDateTime::Tm::ComputeWeekDay()
495 {
496 // compute the week day from day/month/year: we use the dumbest algorithm
497 // possible: just compute our JDN and then use the (simple to derive)
498 // formula: weekday = (JDN + 1.5) % 7
499 wday = (wxDateTime::WeekDay)(GetTruncatedJDN(mday, mon, year) + 2) % 7;
500 }
501
502 void wxDateTime::Tm::AddMonths(int monDiff)
503 {
504 // normalize the months field
505 while ( monDiff < -mon )
506 {
507 year--;
508
509 monDiff += MONTHS_IN_YEAR;
510 }
511
512 while ( monDiff + mon >= MONTHS_IN_YEAR )
513 {
514 year++;
515
516 monDiff -= MONTHS_IN_YEAR;
517 }
518
519 mon = (wxDateTime::Month)(mon + monDiff);
520
521 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
522
523 // NB: we don't check here that the resulting date is valid, this function
524 // is private and the caller must check it if needed
525 }
526
527 void wxDateTime::Tm::AddDays(int dayDiff)
528 {
529 // normalize the days field
530 while ( dayDiff + mday < 1 )
531 {
532 AddMonths(-1);
533
534 dayDiff += GetNumOfDaysInMonth(year, mon);
535 }
536
537 mday += dayDiff;
538 while ( mday > GetNumOfDaysInMonth(year, mon) )
539 {
540 mday -= GetNumOfDaysInMonth(year, mon);
541
542 AddMonths(1);
543 }
544
545 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
546 _T("logic error") );
547 }
548
549 // ----------------------------------------------------------------------------
550 // class TimeZone
551 // ----------------------------------------------------------------------------
552
553 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
554 {
555 switch ( tz )
556 {
557 case wxDateTime::Local:
558 // get the offset from C RTL: it returns the difference GMT-local
559 // while we want to have the offset _from_ GMT, hence the '-'
560 m_offset = -GetTimeZone();
561 break;
562
563 case wxDateTime::GMT_12:
564 case wxDateTime::GMT_11:
565 case wxDateTime::GMT_10:
566 case wxDateTime::GMT_9:
567 case wxDateTime::GMT_8:
568 case wxDateTime::GMT_7:
569 case wxDateTime::GMT_6:
570 case wxDateTime::GMT_5:
571 case wxDateTime::GMT_4:
572 case wxDateTime::GMT_3:
573 case wxDateTime::GMT_2:
574 case wxDateTime::GMT_1:
575 m_offset = -3600*(wxDateTime::GMT0 - tz);
576 break;
577
578 case wxDateTime::GMT0:
579 case wxDateTime::GMT1:
580 case wxDateTime::GMT2:
581 case wxDateTime::GMT3:
582 case wxDateTime::GMT4:
583 case wxDateTime::GMT5:
584 case wxDateTime::GMT6:
585 case wxDateTime::GMT7:
586 case wxDateTime::GMT8:
587 case wxDateTime::GMT9:
588 case wxDateTime::GMT10:
589 case wxDateTime::GMT11:
590 case wxDateTime::GMT12:
591 m_offset = 3600*(tz - wxDateTime::GMT0);
592 break;
593
594 case wxDateTime::A_CST:
595 // Central Standard Time in use in Australia = UTC + 9.5
596 m_offset = 60l*(9*60 + 30);
597 break;
598
599 default:
600 wxFAIL_MSG( _T("unknown time zone") );
601 }
602 }
603
604 // ----------------------------------------------------------------------------
605 // static functions
606 // ----------------------------------------------------------------------------
607
608 /* static */
609 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
610 {
611 if ( year == Inv_Year )
612 year = GetCurrentYear();
613
614 if ( cal == Gregorian )
615 {
616 // in Gregorian calendar leap years are those divisible by 4 except
617 // those divisible by 100 unless they're also divisible by 400
618 // (in some countries, like Russia and Greece, additional corrections
619 // exist, but they won't manifest themselves until 2700)
620 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
621 }
622 else if ( cal == Julian )
623 {
624 // in Julian calendar the rule is simpler
625 return year % 4 == 0;
626 }
627 else
628 {
629 wxFAIL_MSG(_T("unknown calendar"));
630
631 return FALSE;
632 }
633 }
634
635 /* static */
636 int wxDateTime::GetCentury(int year)
637 {
638 return year > 0 ? year / 100 : year / 100 - 1;
639 }
640
641 /* static */
642 int wxDateTime::ConvertYearToBC(int year)
643 {
644 // year 0 is BC 1
645 return year > 0 ? year : year - 1;
646 }
647
648 /* static */
649 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
650 {
651 switch ( cal )
652 {
653 case Gregorian:
654 return Now().GetYear();
655
656 case Julian:
657 wxFAIL_MSG(_T("TODO"));
658 break;
659
660 default:
661 wxFAIL_MSG(_T("unsupported calendar"));
662 break;
663 }
664
665 return Inv_Year;
666 }
667
668 /* static */
669 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
670 {
671 switch ( cal )
672 {
673 case Gregorian:
674 return Now().GetMonth();
675
676 case Julian:
677 wxFAIL_MSG(_T("TODO"));
678 break;
679
680 default:
681 wxFAIL_MSG(_T("unsupported calendar"));
682 break;
683 }
684
685 return Inv_Month;
686 }
687
688 /* static */
689 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
690 {
691 if ( year == Inv_Year )
692 {
693 // take the current year if none given
694 year = GetCurrentYear();
695 }
696
697 switch ( cal )
698 {
699 case Gregorian:
700 case Julian:
701 return IsLeapYear(year) ? 366 : 365;
702
703 default:
704 wxFAIL_MSG(_T("unsupported calendar"));
705 break;
706 }
707
708 return 0;
709 }
710
711 /* static */
712 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
713 int year,
714 wxDateTime::Calendar cal)
715 {
716 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
717
718 if ( cal == Gregorian || cal == Julian )
719 {
720 if ( year == Inv_Year )
721 {
722 // take the current year if none given
723 year = GetCurrentYear();
724 }
725
726 return GetNumOfDaysInMonth(year, month);
727 }
728 else
729 {
730 wxFAIL_MSG(_T("unsupported calendar"));
731
732 return 0;
733 }
734 }
735
736 /* static */
737 wxString wxDateTime::GetMonthName(wxDateTime::Month month,
738 wxDateTime::NameFlags flags)
739 {
740 wxCHECK_MSG( month != Inv_Month, _T(""), _T("invalid month") );
741
742 // notice that we must set all the fields to avoid confusing libc (GNU one
743 // gets confused to a crash if we don't do this)
744 tm tm;
745 InitTm(tm);
746 tm.tm_mon = month;
747
748 return CallStrftime(flags == Name_Abbr ? _T("%b") : _T("%B"), &tm);
749 }
750
751 /* static */
752 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday,
753 wxDateTime::NameFlags flags)
754 {
755 wxCHECK_MSG( wday != Inv_WeekDay, _T(""), _T("invalid weekday") );
756
757 // take some arbitrary Sunday
758 tm tm;
759 InitTm(tm);
760 tm.tm_mday = 28;
761 tm.tm_mon = Nov;
762 tm.tm_year = 99;
763
764 // and offset it by the number of days needed to get the correct wday
765 tm.tm_mday += wday;
766
767 // call mktime() to normalize it...
768 (void)mktime(&tm);
769
770 // ... and call strftime()
771 return CallStrftime(flags == Name_Abbr ? _T("%a") : _T("%A"), &tm);
772 }
773
774 /* static */
775 void wxDateTime::GetAmPmStrings(wxString *am, wxString *pm)
776 {
777 tm tm;
778 InitTm(tm);
779 if ( am )
780 {
781 *am = CallStrftime(_T("%p"), &tm);
782 }
783 if ( pm )
784 {
785 tm.tm_hour = 13;
786 *pm = CallStrftime(_T("%p"), &tm);
787 }
788 }
789
790 // ----------------------------------------------------------------------------
791 // Country stuff: date calculations depend on the country (DST, work days,
792 // ...), so we need to know which rules to follow.
793 // ----------------------------------------------------------------------------
794
795 /* static */
796 wxDateTime::Country wxDateTime::GetCountry()
797 {
798 // TODO use LOCALE_ICOUNTRY setting under Win32
799
800 if ( ms_country == Country_Unknown )
801 {
802 // try to guess from the time zone name
803 time_t t = time(NULL);
804 struct tm *tm = localtime(&t);
805
806 wxString tz = CallStrftime(_T("%Z"), tm);
807 if ( tz == _T("WET") || tz == _T("WEST") )
808 {
809 ms_country = UK;
810 }
811 else if ( tz == _T("CET") || tz == _T("CEST") )
812 {
813 ms_country = Country_EEC;
814 }
815 else if ( tz == _T("MSK") || tz == _T("MSD") )
816 {
817 ms_country = Russia;
818 }
819 else if ( tz == _T("AST") || tz == _T("ADT") ||
820 tz == _T("EST") || tz == _T("EDT") ||
821 tz == _T("CST") || tz == _T("CDT") ||
822 tz == _T("MST") || tz == _T("MDT") ||
823 tz == _T("PST") || tz == _T("PDT") )
824 {
825 ms_country = USA;
826 }
827 else
828 {
829 // well, choose a default one
830 ms_country = USA;
831 }
832 }
833
834 return ms_country;
835 }
836
837 /* static */
838 void wxDateTime::SetCountry(wxDateTime::Country country)
839 {
840 ms_country = country;
841 }
842
843 /* static */
844 bool wxDateTime::IsWestEuropeanCountry(Country country)
845 {
846 if ( country == Country_Default )
847 {
848 country = GetCountry();
849 }
850
851 return (Country_WesternEurope_Start <= country) &&
852 (country <= Country_WesternEurope_End);
853 }
854
855 // ----------------------------------------------------------------------------
856 // DST calculations: we use 3 different rules for the West European countries,
857 // USA and for the rest of the world. This is undoubtedly false for many
858 // countries, but I lack the necessary info (and the time to gather it),
859 // please add the other rules here!
860 // ----------------------------------------------------------------------------
861
862 /* static */
863 bool wxDateTime::IsDSTApplicable(int year, Country country)
864 {
865 if ( year == Inv_Year )
866 {
867 // take the current year if none given
868 year = GetCurrentYear();
869 }
870
871 if ( country == Country_Default )
872 {
873 country = GetCountry();
874 }
875
876 switch ( country )
877 {
878 case USA:
879 case UK:
880 // DST was first observed in the US and UK during WWI, reused
881 // during WWII and used again since 1966
882 return year >= 1966 ||
883 (year >= 1942 && year <= 1945) ||
884 (year == 1918 || year == 1919);
885
886 default:
887 // assume that it started after WWII
888 return year > 1950;
889 }
890 }
891
892 /* static */
893 wxDateTime wxDateTime::GetBeginDST(int year, Country country)
894 {
895 if ( year == Inv_Year )
896 {
897 // take the current year if none given
898 year = GetCurrentYear();
899 }
900
901 if ( country == Country_Default )
902 {
903 country = GetCountry();
904 }
905
906 if ( !IsDSTApplicable(year, country) )
907 {
908 return wxInvalidDateTime;
909 }
910
911 wxDateTime dt;
912
913 if ( IsWestEuropeanCountry(country) || (country == Russia) )
914 {
915 // DST begins at 1 a.m. GMT on the last Sunday of March
916 if ( !dt.SetToLastWeekDay(Sun, Mar, year) )
917 {
918 // weird...
919 wxFAIL_MSG( _T("no last Sunday in March?") );
920 }
921
922 dt += wxTimeSpan::Hours(1);
923
924 // disable DST tests because it could result in an infinite recursion!
925 dt.MakeGMT(TRUE);
926 }
927 else switch ( country )
928 {
929 case USA:
930 switch ( year )
931 {
932 case 1918:
933 case 1919:
934 // don't know for sure - assume it was in effect all year
935
936 case 1943:
937 case 1944:
938 case 1945:
939 dt.Set(1, Jan, year);
940 break;
941
942 case 1942:
943 // DST was installed Feb 2, 1942 by the Congress
944 dt.Set(2, Feb, year);
945 break;
946
947 // Oil embargo changed the DST period in the US
948 case 1974:
949 dt.Set(6, Jan, 1974);
950 break;
951
952 case 1975:
953 dt.Set(23, Feb, 1975);
954 break;
955
956 default:
957 // before 1986, DST begun on the last Sunday of April, but
958 // in 1986 Reagan changed it to begin at 2 a.m. of the
959 // first Sunday in April
960 if ( year < 1986 )
961 {
962 if ( !dt.SetToLastWeekDay(Sun, Apr, year) )
963 {
964 // weird...
965 wxFAIL_MSG( _T("no first Sunday in April?") );
966 }
967 }
968 else
969 {
970 if ( !dt.SetToWeekDay(Sun, 1, Apr, year) )
971 {
972 // weird...
973 wxFAIL_MSG( _T("no first Sunday in April?") );
974 }
975 }
976
977 dt += wxTimeSpan::Hours(2);
978
979 // TODO what about timezone??
980 }
981
982 break;
983
984 default:
985 // assume Mar 30 as the start of the DST for the rest of the world
986 // - totally bogus, of course
987 dt.Set(30, Mar, year);
988 }
989
990 return dt;
991 }
992
993 /* static */
994 wxDateTime wxDateTime::GetEndDST(int year, Country country)
995 {
996 if ( year == Inv_Year )
997 {
998 // take the current year if none given
999 year = GetCurrentYear();
1000 }
1001
1002 if ( country == Country_Default )
1003 {
1004 country = GetCountry();
1005 }
1006
1007 if ( !IsDSTApplicable(year, country) )
1008 {
1009 return wxInvalidDateTime;
1010 }
1011
1012 wxDateTime dt;
1013
1014 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1015 {
1016 // DST ends at 1 a.m. GMT on the last Sunday of October
1017 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1018 {
1019 // weirder and weirder...
1020 wxFAIL_MSG( _T("no last Sunday in October?") );
1021 }
1022
1023 dt += wxTimeSpan::Hours(1);
1024
1025 // disable DST tests because it could result in an infinite recursion!
1026 dt.MakeGMT(TRUE);
1027 }
1028 else switch ( country )
1029 {
1030 case USA:
1031 switch ( year )
1032 {
1033 case 1918:
1034 case 1919:
1035 // don't know for sure - assume it was in effect all year
1036
1037 case 1943:
1038 case 1944:
1039 dt.Set(31, Dec, year);
1040 break;
1041
1042 case 1945:
1043 // the time was reset after the end of the WWII
1044 dt.Set(30, Sep, year);
1045 break;
1046
1047 default:
1048 // DST ends at 2 a.m. on the last Sunday of October
1049 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1050 {
1051 // weirder and weirder...
1052 wxFAIL_MSG( _T("no last Sunday in October?") );
1053 }
1054
1055 dt += wxTimeSpan::Hours(2);
1056
1057 // TODO what about timezone??
1058 }
1059 break;
1060
1061 default:
1062 // assume October 26th as the end of the DST - totally bogus too
1063 dt.Set(26, Oct, year);
1064 }
1065
1066 return dt;
1067 }
1068
1069 // ----------------------------------------------------------------------------
1070 // constructors and assignment operators
1071 // ----------------------------------------------------------------------------
1072
1073 // return the current time with ms precision
1074 /* static */ wxDateTime wxDateTime::UNow()
1075 {
1076 return wxDateTime(wxGetLocalTimeMillis());
1077 }
1078
1079 // the values in the tm structure contain the local time
1080 wxDateTime& wxDateTime::Set(const struct tm& tm)
1081 {
1082 struct tm tm2(tm);
1083 time_t timet = mktime(&tm2);
1084
1085 if ( timet == (time_t)-1 )
1086 {
1087 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1088 // less than timezone - try to make it work for this case
1089 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
1090 {
1091 // add timezone to make sure that date is in range
1092 tm2.tm_sec -= GetTimeZone();
1093
1094 timet = mktime(&tm2);
1095 if ( timet != (time_t)-1 )
1096 {
1097 timet += GetTimeZone();
1098
1099 return Set(timet);
1100 }
1101 }
1102
1103 wxFAIL_MSG( _T("mktime() failed") );
1104
1105 *this = wxInvalidDateTime;
1106
1107 return *this;
1108 }
1109 else
1110 {
1111 return Set(timet);
1112 }
1113 }
1114
1115 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
1116 wxDateTime_t minute,
1117 wxDateTime_t second,
1118 wxDateTime_t millisec)
1119 {
1120 // we allow seconds to be 61 to account for the leap seconds, even if we
1121 // don't use them really
1122 wxDATETIME_CHECK( hour < 24 &&
1123 second < 62 &&
1124 minute < 60 &&
1125 millisec < 1000,
1126 _T("Invalid time in wxDateTime::Set()") );
1127
1128 // get the current date from system
1129 struct tm *tm = GetTmNow();
1130
1131 wxDATETIME_CHECK( tm, _T("localtime() failed") );
1132
1133 // adjust the time
1134 tm->tm_hour = hour;
1135 tm->tm_min = minute;
1136 tm->tm_sec = second;
1137
1138 (void)Set(*tm);
1139
1140 // and finally adjust milliseconds
1141 return SetMillisecond(millisec);
1142 }
1143
1144 wxDateTime& wxDateTime::Set(wxDateTime_t day,
1145 Month month,
1146 int year,
1147 wxDateTime_t hour,
1148 wxDateTime_t minute,
1149 wxDateTime_t second,
1150 wxDateTime_t millisec)
1151 {
1152 wxDATETIME_CHECK( hour < 24 &&
1153 second < 62 &&
1154 minute < 60 &&
1155 millisec < 1000,
1156 _T("Invalid time in wxDateTime::Set()") );
1157
1158 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1159
1160 wxDATETIME_CHECK( (0 < day) && (day <= GetNumberOfDays(month, year)),
1161 _T("Invalid date in wxDateTime::Set()") );
1162
1163 // the range of time_t type (inclusive)
1164 static const int yearMinInRange = 1970;
1165 static const int yearMaxInRange = 2037;
1166
1167 // test only the year instead of testing for the exact end of the Unix
1168 // time_t range - it doesn't bring anything to do more precise checks
1169 if ( year >= yearMinInRange && year <= yearMaxInRange )
1170 {
1171 // use the standard library version if the date is in range - this is
1172 // probably more efficient than our code
1173 struct tm tm;
1174 tm.tm_year = year - 1900;
1175 tm.tm_mon = month;
1176 tm.tm_mday = day;
1177 tm.tm_hour = hour;
1178 tm.tm_min = minute;
1179 tm.tm_sec = second;
1180 tm.tm_isdst = -1; // mktime() will guess it
1181
1182 (void)Set(tm);
1183
1184 // and finally adjust milliseconds
1185 return SetMillisecond(millisec);
1186 }
1187 else
1188 {
1189 // do time calculations ourselves: we want to calculate the number of
1190 // milliseconds between the given date and the epoch
1191
1192 // get the JDN for the midnight of this day
1193 m_time = GetTruncatedJDN(day, month, year);
1194 m_time -= EPOCH_JDN;
1195 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
1196
1197 // JDN corresponds to GMT, we take localtime
1198 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
1199 }
1200
1201 return *this;
1202 }
1203
1204 wxDateTime& wxDateTime::Set(double jdn)
1205 {
1206 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1207 // EPOCH_JDN + 0.5
1208 jdn -= EPOCH_JDN + 0.5;
1209
1210 jdn *= MILLISECONDS_PER_DAY;
1211
1212 m_time.Assign(jdn);
1213
1214 return *this;
1215 }
1216
1217 wxDateTime& wxDateTime::ResetTime()
1218 {
1219 Tm tm = GetTm();
1220
1221 if ( tm.hour || tm.min || tm.sec || tm.msec )
1222 {
1223 tm.msec =
1224 tm.sec =
1225 tm.min =
1226 tm.hour = 0;
1227
1228 Set(tm);
1229 }
1230
1231 return *this;
1232 }
1233
1234 // ----------------------------------------------------------------------------
1235 // time_t <-> broken down time conversions
1236 // ----------------------------------------------------------------------------
1237
1238 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
1239 {
1240 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1241
1242 time_t time = GetTicks();
1243 if ( time != (time_t)-1 )
1244 {
1245 // use C RTL functions
1246 tm *tm;
1247 if ( tz.GetOffset() == -GetTimeZone() )
1248 {
1249 // we are working with local time
1250 tm = localtime(&time);
1251
1252 // should never happen
1253 wxCHECK_MSG( tm, Tm(), _T("localtime() failed") );
1254 }
1255 else
1256 {
1257 time += (time_t)tz.GetOffset();
1258 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1259 int time2 = (int) time;
1260 if ( time2 >= 0 )
1261 #else
1262 if ( time >= 0 )
1263 #endif
1264 {
1265 tm = gmtime(&time);
1266
1267 // should never happen
1268 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
1269 }
1270 else
1271 {
1272 tm = (struct tm *)NULL;
1273 }
1274 }
1275
1276 if ( tm )
1277 {
1278 // adjust the milliseconds
1279 Tm tm2(*tm, tz);
1280 long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong();
1281 tm2.msec = (wxDateTime_t)(timeOnly % 1000);
1282 return tm2;
1283 }
1284 //else: use generic code below
1285 }
1286
1287 // remember the time and do the calculations with the date only - this
1288 // eliminates rounding errors of the floating point arithmetics
1289
1290 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
1291
1292 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1293
1294 // we want to always have positive time and timeMidnight to be really
1295 // the midnight before it
1296 if ( timeOnly < 0 )
1297 {
1298 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1299 }
1300
1301 timeMidnight -= timeOnly;
1302
1303 // calculate the Gregorian date from JDN for the midnight of our date:
1304 // this will yield day, month (in 1..12 range) and year
1305
1306 // actually, this is the JDN for the noon of the previous day
1307 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
1308
1309 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1310
1311 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
1312
1313 // calculate the century
1314 long temp = (jdn + JDN_OFFSET) * 4 - 1;
1315 long century = temp / DAYS_PER_400_YEARS;
1316
1317 // then the year and day of year (1 <= dayOfYear <= 366)
1318 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
1319 long year = (century * 100) + (temp / DAYS_PER_4_YEARS);
1320 long dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
1321
1322 // and finally the month and day of the month
1323 temp = dayOfYear * 5 - 3;
1324 long month = temp / DAYS_PER_5_MONTHS;
1325 long day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
1326
1327 // month is counted from March - convert to normal
1328 if ( month < 10 )
1329 {
1330 month += 3;
1331 }
1332 else
1333 {
1334 year += 1;
1335 month -= 9;
1336 }
1337
1338 // year is offset by 4800
1339 year -= 4800;
1340
1341 // check that the algorithm gave us something reasonable
1342 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
1343 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
1344
1345 // construct Tm from these values
1346 Tm tm;
1347 tm.year = (int)year;
1348 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1349 tm.mday = (wxDateTime_t)day;
1350 tm.msec = (wxDateTime_t)(timeOnly % 1000);
1351 timeOnly -= tm.msec;
1352 timeOnly /= 1000; // now we have time in seconds
1353
1354 tm.sec = (wxDateTime_t)(timeOnly % 60);
1355 timeOnly -= tm.sec;
1356 timeOnly /= 60; // now we have time in minutes
1357
1358 tm.min = (wxDateTime_t)(timeOnly % 60);
1359 timeOnly -= tm.min;
1360
1361 tm.hour = (wxDateTime_t)(timeOnly / 60);
1362
1363 return tm;
1364 }
1365
1366 wxDateTime& wxDateTime::SetYear(int year)
1367 {
1368 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1369
1370 Tm tm(GetTm());
1371 tm.year = year;
1372 Set(tm);
1373
1374 return *this;
1375 }
1376
1377 wxDateTime& wxDateTime::SetMonth(Month month)
1378 {
1379 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1380
1381 Tm tm(GetTm());
1382 tm.mon = month;
1383 Set(tm);
1384
1385 return *this;
1386 }
1387
1388 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
1389 {
1390 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1391
1392 Tm tm(GetTm());
1393 tm.mday = mday;
1394 Set(tm);
1395
1396 return *this;
1397 }
1398
1399 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
1400 {
1401 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1402
1403 Tm tm(GetTm());
1404 tm.hour = hour;
1405 Set(tm);
1406
1407 return *this;
1408 }
1409
1410 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
1411 {
1412 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1413
1414 Tm tm(GetTm());
1415 tm.min = min;
1416 Set(tm);
1417
1418 return *this;
1419 }
1420
1421 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
1422 {
1423 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1424
1425 Tm tm(GetTm());
1426 tm.sec = sec;
1427 Set(tm);
1428
1429 return *this;
1430 }
1431
1432 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
1433 {
1434 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1435
1436 // we don't need to use GetTm() for this one
1437 m_time -= m_time % 1000l;
1438 m_time += millisecond;
1439
1440 return *this;
1441 }
1442
1443 // ----------------------------------------------------------------------------
1444 // wxDateTime arithmetics
1445 // ----------------------------------------------------------------------------
1446
1447 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
1448 {
1449 Tm tm(GetTm());
1450
1451 tm.year += diff.GetYears();
1452 tm.AddMonths(diff.GetMonths());
1453
1454 // check that the resulting date is valid
1455 if ( tm.mday > GetNumOfDaysInMonth(tm.year, tm.mon) )
1456 {
1457 // We suppose that when adding one month to Jan 31 we want to get Feb
1458 // 28 (or 29), i.e. adding a month to the last day of the month should
1459 // give the last day of the next month which is quite logical.
1460 //
1461 // Unfortunately, there is no logic way to understand what should
1462 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1463 // We make it Feb 28 (last day too), but it is highly questionable.
1464 tm.mday = GetNumOfDaysInMonth(tm.year, tm.mon);
1465 }
1466
1467 tm.AddDays(diff.GetTotalDays());
1468
1469 Set(tm);
1470
1471 wxASSERT_MSG( IsSameTime(tm),
1472 _T("Add(wxDateSpan) shouldn't modify time") );
1473
1474 return *this;
1475 }
1476
1477 // ----------------------------------------------------------------------------
1478 // Weekday and monthday stuff
1479 // ----------------------------------------------------------------------------
1480
1481 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek, WeekDay weekday)
1482 {
1483 int year = GetYear();
1484
1485 // Jan 4 always lies in the 1st week of the year
1486 Set(4, Jan, year);
1487 SetToWeekDayInSameWeek(weekday) += wxDateSpan::Weeks(numWeek);
1488
1489 if ( GetYear() != year )
1490 {
1491 // oops... numWeek was too big
1492 return FALSE;
1493 }
1494
1495 return TRUE;
1496 }
1497
1498 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
1499 int year)
1500 {
1501 // take the current month/year if none specified
1502 if ( year == Inv_Year )
1503 year = GetYear();
1504 if ( month == Inv_Month )
1505 month = GetMonth();
1506
1507 return Set(GetNumOfDaysInMonth(year, month), month, year);
1508 }
1509
1510 wxDateTime& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday)
1511 {
1512 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1513
1514 WeekDay wdayThis = GetWeekDay();
1515 if ( weekday == wdayThis )
1516 {
1517 // nothing to do
1518 return *this;
1519 }
1520 else if ( weekday < wdayThis )
1521 {
1522 return Subtract(wxDateSpan::Days(wdayThis - weekday));
1523 }
1524 else // weekday > wdayThis
1525 {
1526 return Add(wxDateSpan::Days(weekday - wdayThis));
1527 }
1528 }
1529
1530 wxDateTime& wxDateTime::SetToNextWeekDay(WeekDay weekday)
1531 {
1532 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1533
1534 int diff;
1535 WeekDay wdayThis = GetWeekDay();
1536 if ( weekday == wdayThis )
1537 {
1538 // nothing to do
1539 return *this;
1540 }
1541 else if ( weekday < wdayThis )
1542 {
1543 // need to advance a week
1544 diff = 7 - (wdayThis - weekday);
1545 }
1546 else // weekday > wdayThis
1547 {
1548 diff = weekday - wdayThis;
1549 }
1550
1551 return Add(wxDateSpan::Days(diff));
1552 }
1553
1554 wxDateTime& wxDateTime::SetToPrevWeekDay(WeekDay weekday)
1555 {
1556 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1557
1558 int diff;
1559 WeekDay wdayThis = GetWeekDay();
1560 if ( weekday == wdayThis )
1561 {
1562 // nothing to do
1563 return *this;
1564 }
1565 else if ( weekday > wdayThis )
1566 {
1567 // need to go to previous week
1568 diff = 7 - (weekday - wdayThis);
1569 }
1570 else // weekday < wdayThis
1571 {
1572 diff = wdayThis - weekday;
1573 }
1574
1575 return Subtract(wxDateSpan::Days(diff));
1576 }
1577
1578 bool wxDateTime::SetToWeekDay(WeekDay weekday,
1579 int n,
1580 Month month,
1581 int year)
1582 {
1583 wxCHECK_MSG( weekday != Inv_WeekDay, FALSE, _T("invalid weekday") );
1584
1585 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1586 // anyhow in such case - but may be should still give an assert for it?
1587
1588 // take the current month/year if none specified
1589 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1590
1591 wxDateTime dt;
1592
1593 // TODO this probably could be optimised somehow...
1594
1595 if ( n > 0 )
1596 {
1597 // get the first day of the month
1598 dt.Set(1, month, year);
1599
1600 // get its wday
1601 WeekDay wdayFirst = dt.GetWeekDay();
1602
1603 // go to the first weekday of the month
1604 int diff = weekday - wdayFirst;
1605 if ( diff < 0 )
1606 diff += 7;
1607
1608 // add advance n-1 weeks more
1609 diff += 7*(n - 1);
1610
1611 dt += wxDateSpan::Days(diff);
1612 }
1613 else // count from the end of the month
1614 {
1615 // get the last day of the month
1616 dt.SetToLastMonthDay(month, year);
1617
1618 // get its wday
1619 WeekDay wdayLast = dt.GetWeekDay();
1620
1621 // go to the last weekday of the month
1622 int diff = wdayLast - weekday;
1623 if ( diff < 0 )
1624 diff += 7;
1625
1626 // and rewind n-1 weeks from there
1627 diff += 7*(-n - 1);
1628
1629 dt -= wxDateSpan::Days(diff);
1630 }
1631
1632 // check that it is still in the same month
1633 if ( dt.GetMonth() == month )
1634 {
1635 *this = dt;
1636
1637 return TRUE;
1638 }
1639 else
1640 {
1641 // no such day in this month
1642 return FALSE;
1643 }
1644 }
1645
1646 wxDateTime::wxDateTime_t wxDateTime::GetDayOfYear(const TimeZone& tz) const
1647 {
1648 Tm tm(GetTm(tz));
1649
1650 return gs_cumulatedDays[IsLeapYear(tm.year)][tm.mon] + tm.mday;
1651 }
1652
1653 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags,
1654 const TimeZone& tz) const
1655 {
1656 if ( flags == Default_First )
1657 {
1658 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1659 }
1660
1661 wxDateTime_t nDayInYear = GetDayOfYear(tz);
1662 wxDateTime_t week;
1663
1664 WeekDay wd = GetWeekDay(tz);
1665 if ( flags == Sunday_First )
1666 {
1667 week = (nDayInYear - wd + 7) / 7;
1668 }
1669 else
1670 {
1671 // have to shift the week days values
1672 week = (nDayInYear - (wd - 1 + 7) % 7 + 7) / 7;
1673 }
1674
1675 // FIXME some more elegant way??
1676 WeekDay wdYearStart = wxDateTime(1, Jan, GetYear()).GetWeekDay();
1677 if ( wdYearStart == Wed || wdYearStart == Thu )
1678 {
1679 week++;
1680 }
1681
1682 return week;
1683 }
1684
1685 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags,
1686 const TimeZone& tz) const
1687 {
1688 Tm tm = GetTm(tz);
1689 wxDateTime dtMonthStart = wxDateTime(1, tm.mon, tm.year);
1690 int nWeek = GetWeekOfYear(flags) - dtMonthStart.GetWeekOfYear(flags) + 1;
1691 if ( nWeek < 0 )
1692 {
1693 // this may happen for January when Jan, 1 is the last week of the
1694 // previous year
1695 nWeek += IsLeapYear(tm.year - 1) ? 53 : 52;
1696 }
1697
1698 return (wxDateTime::wxDateTime_t)nWeek;
1699 }
1700
1701 wxDateTime& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday)
1702 {
1703 int year = GetYear();
1704 wxDATETIME_CHECK( (0 < yday) && (yday <= GetNumberOfDays(year)),
1705 _T("invalid year day") );
1706
1707 bool isLeap = IsLeapYear(year);
1708 for ( Month mon = Jan; mon < Inv_Month; wxNextMonth(mon) )
1709 {
1710 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1711 // don't need it neither - because of the CHECK above we know that
1712 // yday lies in December then
1713 if ( (mon == Dec) || (yday < gs_cumulatedDays[isLeap][mon + 1]) )
1714 {
1715 Set(yday - gs_cumulatedDays[isLeap][mon], mon, year);
1716
1717 break;
1718 }
1719 }
1720
1721 return *this;
1722 }
1723
1724 // ----------------------------------------------------------------------------
1725 // Julian day number conversion and related stuff
1726 // ----------------------------------------------------------------------------
1727
1728 double wxDateTime::GetJulianDayNumber() const
1729 {
1730 // JDN are always expressed for the GMT dates
1731 Tm tm(ToTimezone(GMT0).GetTm(GMT0));
1732
1733 double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
1734
1735 // add the part GetTruncatedJDN() neglected
1736 result += 0.5;
1737
1738 // and now add the time: 86400 sec = 1 JDN
1739 return result + ((double)(60*(60*tm.hour + tm.min) + tm.sec)) / 86400;
1740 }
1741
1742 double wxDateTime::GetRataDie() const
1743 {
1744 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1745 return GetJulianDayNumber() - 1721119.5 - 306;
1746 }
1747
1748 // ----------------------------------------------------------------------------
1749 // timezone and DST stuff
1750 // ----------------------------------------------------------------------------
1751
1752 int wxDateTime::IsDST(wxDateTime::Country country) const
1753 {
1754 wxCHECK_MSG( country == Country_Default, -1,
1755 _T("country support not implemented") );
1756
1757 // use the C RTL for the dates in the standard range
1758 time_t timet = GetTicks();
1759 if ( timet != (time_t)-1 )
1760 {
1761 tm *tm = localtime(&timet);
1762
1763 wxCHECK_MSG( tm, -1, _T("localtime() failed") );
1764
1765 return tm->tm_isdst;
1766 }
1767 else
1768 {
1769 int year = GetYear();
1770
1771 if ( !IsDSTApplicable(year, country) )
1772 {
1773 // no DST time in this year in this country
1774 return -1;
1775 }
1776
1777 return IsBetween(GetBeginDST(year, country), GetEndDST(year, country));
1778 }
1779 }
1780
1781 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz, bool noDST)
1782 {
1783 long secDiff = GetTimeZone() + tz.GetOffset();
1784
1785 // we need to know whether DST is or not in effect for this date unless
1786 // the test disabled by the caller
1787 if ( !noDST && (IsDST() == 1) )
1788 {
1789 // FIXME we assume that the DST is always shifted by 1 hour
1790 secDiff -= 3600;
1791 }
1792
1793 return Subtract(wxTimeSpan::Seconds(secDiff));
1794 }
1795
1796 // ----------------------------------------------------------------------------
1797 // wxDateTime to/from text representations
1798 // ----------------------------------------------------------------------------
1799
1800 wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
1801 {
1802 wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
1803
1804 // we have to use our own implementation if the date is out of range of
1805 // strftime() or if we use non standard specificators
1806 time_t time = GetTicks();
1807 if ( (time != (time_t)-1) && !wxStrstr(format, _T("%l")) )
1808 {
1809 // use strftime()
1810 tm *tm;
1811 if ( tz.GetOffset() == -GetTimeZone() )
1812 {
1813 // we are working with local time
1814 tm = localtime(&time);
1815
1816 // should never happen
1817 wxCHECK_MSG( tm, wxEmptyString, _T("localtime() failed") );
1818 }
1819 else
1820 {
1821 time += (int)tz.GetOffset();
1822
1823 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1824 int time2 = (int) time;
1825 if ( time2 >= 0 )
1826 #else
1827 if ( time >= 0 )
1828 #endif
1829 {
1830 tm = gmtime(&time);
1831
1832 // should never happen
1833 wxCHECK_MSG( tm, wxEmptyString, _T("gmtime() failed") );
1834 }
1835 else
1836 {
1837 tm = (struct tm *)NULL;
1838 }
1839 }
1840
1841 if ( tm )
1842 {
1843 return CallStrftime(format, tm);
1844 }
1845 //else: use generic code below
1846 }
1847
1848 // we only parse ANSI C format specifications here, no POSIX 2
1849 // complications, no GNU extensions but we do add support for a "%l" format
1850 // specifier allowing to get the number of milliseconds
1851 Tm tm = GetTm(tz);
1852
1853 // used for calls to strftime() when we only deal with time
1854 struct tm tmTimeOnly;
1855 tmTimeOnly.tm_hour = tm.hour;
1856 tmTimeOnly.tm_min = tm.min;
1857 tmTimeOnly.tm_sec = tm.sec;
1858 tmTimeOnly.tm_wday = 0;
1859 tmTimeOnly.tm_yday = 0;
1860 tmTimeOnly.tm_mday = 1; // any date will do
1861 tmTimeOnly.tm_mon = 0;
1862 tmTimeOnly.tm_year = 76;
1863 tmTimeOnly.tm_isdst = 0; // no DST, we adjust for tz ourselves
1864
1865 wxString tmp, res, fmt;
1866 for ( const wxChar *p = format; *p; p++ )
1867 {
1868 if ( *p != _T('%') )
1869 {
1870 // copy as is
1871 res += *p;
1872
1873 continue;
1874 }
1875
1876 // set the default format
1877 switch ( *++p )
1878 {
1879 case _T('Y'): // year has 4 digits
1880 fmt = _T("%04d");
1881 break;
1882
1883 case _T('j'): // day of year has 3 digits
1884 case _T('l'): // milliseconds have 3 digits
1885 fmt = _T("%03d");
1886 break;
1887
1888 default:
1889 // it's either another valid format specifier in which case
1890 // the format is "%02d" (for all the rest) or we have the
1891 // field width preceding the format in which case it will
1892 // override the default format anyhow
1893 fmt = _T("%02d");
1894 }
1895
1896 bool restart = TRUE;
1897 while ( restart )
1898 {
1899 restart = FALSE;
1900
1901 // start of the format specification
1902 switch ( *p )
1903 {
1904 case _T('a'): // a weekday name
1905 case _T('A'):
1906 // second parameter should be TRUE for abbreviated names
1907 res += GetWeekDayName(tm.GetWeekDay(),
1908 *p == _T('a') ? Name_Abbr : Name_Full);
1909 break;
1910
1911 case _T('b'): // a month name
1912 case _T('B'):
1913 res += GetMonthName(tm.mon,
1914 *p == _T('b') ? Name_Abbr : Name_Full);
1915 break;
1916
1917 case _T('c'): // locale default date and time representation
1918 case _T('x'): // locale default date representation
1919 //
1920 // the problem: there is no way to know what do these format
1921 // specifications correspond to for the current locale.
1922 //
1923 // the solution: use a hack and still use strftime(): first
1924 // find the YEAR which is a year in the strftime() range (1970
1925 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
1926 // of the real year. Then make a copy of the format and
1927 // replace all occurences of YEAR in it with some unique
1928 // string not appearing anywhere else in it, then use
1929 // strftime() to format the date in year YEAR and then replace
1930 // YEAR back by the real year and the unique replacement
1931 // string back with YEAR. Notice that "all occurences of YEAR"
1932 // means all occurences of 4 digit as well as 2 digit form!
1933 //
1934 // the bugs: we assume that neither of %c nor %x contains any
1935 // fields which may change between the YEAR and real year. For
1936 // example, the week number (%U, %W) and the day number (%j)
1937 // will change if one of these years is leap and the other one
1938 // is not!
1939 {
1940 // find the YEAR: normally, for any year X, Jan 1 or the
1941 // year X + 28 is the same weekday as Jan 1 of X (because
1942 // the weekday advances by 1 for each normal X and by 2
1943 // for each leap X, hence by 5 every 4 years or by 35
1944 // which is 0 mod 7 every 28 years) but this rule breaks
1945 // down if there are years between X and Y which are
1946 // divisible by 4 but not leap (i.e. divisible by 100 but
1947 // not 400), hence the correction.
1948
1949 int yearReal = GetYear(tz);
1950 int mod28 = yearReal % 28;
1951
1952 // be careful to not go too far - we risk to leave the
1953 // supported range
1954 int year;
1955 if ( mod28 < 10 )
1956 {
1957 year = 1988 + mod28; // 1988 == 0 (mod 28)
1958 }
1959 else
1960 {
1961 year = 1970 + mod28 - 10; // 1970 == 10 (mod 28)
1962 }
1963
1964 int nCentury = year / 100,
1965 nCenturyReal = yearReal / 100;
1966
1967 // need to adjust for the years divisble by 400 which are
1968 // not leap but are counted like leap ones if we just take
1969 // the number of centuries in between for nLostWeekDays
1970 int nLostWeekDays = (nCentury - nCenturyReal) -
1971 (nCentury / 4 - nCenturyReal / 4);
1972
1973 // we have to gain back the "lost" weekdays: note that the
1974 // effect of this loop is to not do anything to
1975 // nLostWeekDays (which we won't use any more), but to
1976 // (indirectly) set the year correctly
1977 while ( (nLostWeekDays % 7) != 0 )
1978 {
1979 nLostWeekDays += year++ % 4 ? 1 : 2;
1980 }
1981
1982 // at any rate, we couldn't go further than 1988 + 9 + 28!
1983 wxASSERT_MSG( year < 2030,
1984 _T("logic error in wxDateTime::Format") );
1985
1986 wxString strYear, strYear2;
1987 strYear.Printf(_T("%d"), year);
1988 strYear2.Printf(_T("%d"), year % 100);
1989
1990 // find two strings not occuring in format (this is surely
1991 // not optimal way of doing it... improvements welcome!)
1992 wxString fmt = format;
1993 wxString replacement = (wxChar)-1;
1994 while ( fmt.Find(replacement) != wxNOT_FOUND )
1995 {
1996 replacement << (wxChar)-1;
1997 }
1998
1999 wxString replacement2 = (wxChar)-2;
2000 while ( fmt.Find(replacement) != wxNOT_FOUND )
2001 {
2002 replacement << (wxChar)-2;
2003 }
2004
2005 // replace all occurences of year with it
2006 bool wasReplaced = fmt.Replace(strYear, replacement) > 0;
2007 if ( !wasReplaced )
2008 wasReplaced = fmt.Replace(strYear2, replacement2) > 0;
2009
2010 // use strftime() to format the same date but in supported
2011 // year
2012 //
2013 // NB: we assume that strftime() doesn't check for the
2014 // date validity and will happily format the date
2015 // corresponding to Feb 29 of a non leap year (which
2016 // may happen if yearReal was leap and year is not)
2017 struct tm tmAdjusted;
2018 InitTm(tmAdjusted);
2019 tmAdjusted.tm_hour = tm.hour;
2020 tmAdjusted.tm_min = tm.min;
2021 tmAdjusted.tm_sec = tm.sec;
2022 tmAdjusted.tm_wday = tm.GetWeekDay();
2023 tmAdjusted.tm_yday = GetDayOfYear();
2024 tmAdjusted.tm_mday = tm.mday;
2025 tmAdjusted.tm_mon = tm.mon;
2026 tmAdjusted.tm_year = year - 1900;
2027 tmAdjusted.tm_isdst = 0; // no DST, already adjusted
2028 wxString str = CallStrftime(*p == _T('c') ? _T("%c")
2029 : _T("%x"),
2030 &tmAdjusted);
2031
2032 // now replace the occurence of 1999 with the real year
2033 wxString strYearReal, strYearReal2;
2034 strYearReal.Printf(_T("%04d"), yearReal);
2035 strYearReal2.Printf(_T("%02d"), yearReal % 100);
2036 str.Replace(strYear, strYearReal);
2037 str.Replace(strYear2, strYearReal2);
2038
2039 // and replace back all occurences of replacement string
2040 if ( wasReplaced )
2041 {
2042 str.Replace(replacement2, strYear2);
2043 str.Replace(replacement, strYear);
2044 }
2045
2046 res += str;
2047 }
2048 break;
2049
2050 case _T('d'): // day of a month (01-31)
2051 res += wxString::Format(fmt, tm.mday);
2052 break;
2053
2054 case _T('H'): // hour in 24h format (00-23)
2055 res += wxString::Format(fmt, tm.hour);
2056 break;
2057
2058 case _T('I'): // hour in 12h format (01-12)
2059 {
2060 // 24h -> 12h, 0h -> 12h too
2061 int hour12 = tm.hour > 12 ? tm.hour - 12
2062 : tm.hour ? tm.hour : 12;
2063 res += wxString::Format(fmt, hour12);
2064 }
2065 break;
2066
2067 case _T('j'): // day of the year
2068 res += wxString::Format(fmt, GetDayOfYear(tz));
2069 break;
2070
2071 case _T('l'): // milliseconds (NOT STANDARD)
2072 res += wxString::Format(fmt, GetMillisecond(tz));
2073 break;
2074
2075 case _T('m'): // month as a number (01-12)
2076 res += wxString::Format(fmt, tm.mon + 1);
2077 break;
2078
2079 case _T('M'): // minute as a decimal number (00-59)
2080 res += wxString::Format(fmt, tm.min);
2081 break;
2082
2083 case _T('p'): // AM or PM string
2084 res += CallStrftime(_T("%p"), &tmTimeOnly);
2085 break;
2086
2087 case _T('S'): // second as a decimal number (00-61)
2088 res += wxString::Format(fmt, tm.sec);
2089 break;
2090
2091 case _T('U'): // week number in the year (Sunday 1st week day)
2092 res += wxString::Format(fmt, GetWeekOfYear(Sunday_First, tz));
2093 break;
2094
2095 case _T('W'): // week number in the year (Monday 1st week day)
2096 res += wxString::Format(fmt, GetWeekOfYear(Monday_First, tz));
2097 break;
2098
2099 case _T('w'): // weekday as a number (0-6), Sunday = 0
2100 res += wxString::Format(fmt, tm.GetWeekDay());
2101 break;
2102
2103 // case _T('x'): -- handled with "%c"
2104
2105 case _T('X'): // locale default time representation
2106 // just use strftime() to format the time for us
2107 res += CallStrftime(_T("%X"), &tmTimeOnly);
2108 break;
2109
2110 case _T('y'): // year without century (00-99)
2111 res += wxString::Format(fmt, tm.year % 100);
2112 break;
2113
2114 case _T('Y'): // year with century
2115 res += wxString::Format(fmt, tm.year);
2116 break;
2117
2118 case _T('Z'): // timezone name
2119 res += CallStrftime(_T("%Z"), &tmTimeOnly);
2120 break;
2121
2122 default:
2123 // is it the format width?
2124 fmt.Empty();
2125 while ( *p == _T('-') || *p == _T('+') ||
2126 *p == _T(' ') || wxIsdigit(*p) )
2127 {
2128 fmt += *p;
2129 }
2130
2131 if ( !fmt.IsEmpty() )
2132 {
2133 // we've only got the flags and width so far in fmt
2134 fmt.Prepend(_T('%'));
2135 fmt.Append(_T('d'));
2136
2137 restart = TRUE;
2138
2139 break;
2140 }
2141
2142 // no, it wasn't the width
2143 wxFAIL_MSG(_T("unknown format specificator"));
2144
2145 // fall through and just copy it nevertheless
2146
2147 case _T('%'): // a percent sign
2148 res += *p;
2149 break;
2150
2151 case 0: // the end of string
2152 wxFAIL_MSG(_T("missing format at the end of string"));
2153
2154 // just put the '%' which was the last char in format
2155 res += _T('%');
2156 break;
2157 }
2158 }
2159 }
2160
2161 return res;
2162 }
2163
2164 // this function parses a string in (strict) RFC 822 format: see the section 5
2165 // of the RFC for the detailed description, but briefly it's something of the
2166 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2167 //
2168 // this function is "strict" by design - it must reject anything except true
2169 // RFC822 time specs.
2170 //
2171 // TODO a great candidate for using reg exps
2172 const wxChar *wxDateTime::ParseRfc822Date(const wxChar* date)
2173 {
2174 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
2175
2176 const wxChar *p = date;
2177 const wxChar *comma = wxStrchr(p, _T(','));
2178 if ( comma )
2179 {
2180 // the part before comma is the weekday
2181
2182 // skip it for now - we don't use but might check that it really
2183 // corresponds to the specfied date
2184 p = comma + 1;
2185
2186 if ( *p != _T(' ') )
2187 {
2188 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2189
2190 return (wxChar *)NULL;
2191 }
2192
2193 p++; // skip space
2194 }
2195
2196 // the following 1 or 2 digits are the day number
2197 if ( !wxIsdigit(*p) )
2198 {
2199 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2200
2201 return (wxChar *)NULL;
2202 }
2203
2204 wxDateTime_t day = *p++ - _T('0');
2205 if ( wxIsdigit(*p) )
2206 {
2207 day *= 10;
2208 day += *p++ - _T('0');
2209 }
2210
2211 if ( *p++ != _T(' ') )
2212 {
2213 return (wxChar *)NULL;
2214 }
2215
2216 // the following 3 letters specify the month
2217 wxString monName(p, 3);
2218 Month mon;
2219 if ( monName == _T("Jan") )
2220 mon = Jan;
2221 else if ( monName == _T("Feb") )
2222 mon = Feb;
2223 else if ( monName == _T("Mar") )
2224 mon = Mar;
2225 else if ( monName == _T("Apr") )
2226 mon = Apr;
2227 else if ( monName == _T("May") )
2228 mon = May;
2229 else if ( monName == _T("Jun") )
2230 mon = Jun;
2231 else if ( monName == _T("Jul") )
2232 mon = Jul;
2233 else if ( monName == _T("Aug") )
2234 mon = Aug;
2235 else if ( monName == _T("Sep") )
2236 mon = Sep;
2237 else if ( monName == _T("Oct") )
2238 mon = Oct;
2239 else if ( monName == _T("Nov") )
2240 mon = Nov;
2241 else if ( monName == _T("Dec") )
2242 mon = Dec;
2243 else
2244 {
2245 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName.c_str());
2246
2247 return (wxChar *)NULL;
2248 }
2249
2250 p += 3;
2251
2252 if ( *p++ != _T(' ') )
2253 {
2254 return (wxChar *)NULL;
2255 }
2256
2257 // next is the year
2258 if ( !wxIsdigit(*p) )
2259 {
2260 // no year?
2261 return (wxChar *)NULL;
2262 }
2263
2264 int year = *p++ - _T('0');
2265
2266 if ( !wxIsdigit(*p) )
2267 {
2268 // should have at least 2 digits in the year
2269 return (wxChar *)NULL;
2270 }
2271
2272 year *= 10;
2273 year += *p++ - _T('0');
2274
2275 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2276 if ( wxIsdigit(*p) )
2277 {
2278 year *= 10;
2279 year += *p++ - _T('0');
2280
2281 if ( !wxIsdigit(*p) )
2282 {
2283 // no 3 digit years please
2284 return (wxChar *)NULL;
2285 }
2286
2287 year *= 10;
2288 year += *p++ - _T('0');
2289 }
2290
2291 if ( *p++ != _T(' ') )
2292 {
2293 return (wxChar *)NULL;
2294 }
2295
2296 // time is in the format hh:mm:ss and seconds are optional
2297 if ( !wxIsdigit(*p) )
2298 {
2299 return (wxChar *)NULL;
2300 }
2301
2302 wxDateTime_t hour = *p++ - _T('0');
2303
2304 if ( !wxIsdigit(*p) )
2305 {
2306 return (wxChar *)NULL;
2307 }
2308
2309 hour *= 10;
2310 hour += *p++ - _T('0');
2311
2312 if ( *p++ != _T(':') )
2313 {
2314 return (wxChar *)NULL;
2315 }
2316
2317 if ( !wxIsdigit(*p) )
2318 {
2319 return (wxChar *)NULL;
2320 }
2321
2322 wxDateTime_t min = *p++ - _T('0');
2323
2324 if ( !wxIsdigit(*p) )
2325 {
2326 return (wxChar *)NULL;
2327 }
2328
2329 min *= 10;
2330 min += *p++ - _T('0');
2331
2332 wxDateTime_t sec = 0;
2333 if ( *p++ == _T(':') )
2334 {
2335 if ( !wxIsdigit(*p) )
2336 {
2337 return (wxChar *)NULL;
2338 }
2339
2340 sec = *p++ - _T('0');
2341
2342 if ( !wxIsdigit(*p) )
2343 {
2344 return (wxChar *)NULL;
2345 }
2346
2347 sec *= 10;
2348 sec += *p++ - _T('0');
2349 }
2350
2351 if ( *p++ != _T(' ') )
2352 {
2353 return (wxChar *)NULL;
2354 }
2355
2356 // and now the interesting part: the timezone
2357 int offset;
2358 if ( *p == _T('-') || *p == _T('+') )
2359 {
2360 // the explicit offset given: it has the form of hhmm
2361 bool plus = *p++ == _T('+');
2362
2363 if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
2364 {
2365 return (wxChar *)NULL;
2366 }
2367
2368 // hours
2369 offset = 60*(10*(*p - _T('0')) + (*(p + 1) - _T('0')));
2370
2371 p += 2;
2372
2373 if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
2374 {
2375 return (wxChar *)NULL;
2376 }
2377
2378 // minutes
2379 offset += 10*(*p - _T('0')) + (*(p + 1) - _T('0'));
2380
2381 if ( !plus )
2382 {
2383 offset = -offset;
2384 }
2385
2386 p += 2;
2387 }
2388 else
2389 {
2390 // the symbolic timezone given: may be either military timezone or one
2391 // of standard abbreviations
2392 if ( !*(p + 1) )
2393 {
2394 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2395 static const int offsets[26] =
2396 {
2397 //A B C D E F G H I J K L M
2398 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2399 //N O P R Q S T U V W Z Y Z
2400 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2401 };
2402
2403 if ( *p < _T('A') || *p > _T('Z') || *p == _T('J') )
2404 {
2405 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p);
2406
2407 return (wxChar *)NULL;
2408 }
2409
2410 offset = offsets[*p++ - _T('A')];
2411 }
2412 else
2413 {
2414 // abbreviation
2415 wxString tz = p;
2416 if ( tz == _T("UT") || tz == _T("UTC") || tz == _T("GMT") )
2417 offset = 0;
2418 else if ( tz == _T("AST") )
2419 offset = AST - GMT0;
2420 else if ( tz == _T("ADT") )
2421 offset = ADT - GMT0;
2422 else if ( tz == _T("EST") )
2423 offset = EST - GMT0;
2424 else if ( tz == _T("EDT") )
2425 offset = EDT - GMT0;
2426 else if ( tz == _T("CST") )
2427 offset = CST - GMT0;
2428 else if ( tz == _T("CDT") )
2429 offset = CDT - GMT0;
2430 else if ( tz == _T("MST") )
2431 offset = MST - GMT0;
2432 else if ( tz == _T("MDT") )
2433 offset = MDT - GMT0;
2434 else if ( tz == _T("PST") )
2435 offset = PST - GMT0;
2436 else if ( tz == _T("PDT") )
2437 offset = PDT - GMT0;
2438 else
2439 {
2440 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p);
2441
2442 return (wxChar *)NULL;
2443 }
2444
2445 p += tz.length();
2446 }
2447
2448 // make it minutes
2449 offset *= 60;
2450 }
2451
2452 // the spec was correct
2453 Set(day, mon, year, hour, min, sec);
2454 MakeTimezone((wxDateTime_t)(60*offset));
2455
2456 return p;
2457 }
2458
2459 const wxChar *wxDateTime::ParseFormat(const wxChar *date,
2460 const wxChar *format,
2461 const wxDateTime& dateDef)
2462 {
2463 wxCHECK_MSG( date && format, (wxChar *)NULL,
2464 _T("NULL pointer in wxDateTime::ParseFormat()") );
2465
2466 wxString str;
2467 unsigned long num;
2468
2469 // what fields have we found?
2470 bool haveWDay = FALSE,
2471 haveYDay = FALSE,
2472 haveDay = FALSE,
2473 haveMon = FALSE,
2474 haveYear = FALSE,
2475 haveHour = FALSE,
2476 haveMin = FALSE,
2477 haveSec = FALSE;
2478
2479 bool hourIsIn12hFormat = FALSE, // or in 24h one?
2480 isPM = FALSE; // AM by default
2481
2482 // and the value of the items we have (init them to get rid of warnings)
2483 wxDateTime_t sec = 0,
2484 min = 0,
2485 hour = 0;
2486 WeekDay wday = Inv_WeekDay;
2487 wxDateTime_t yday = 0,
2488 mday = 0;
2489 wxDateTime::Month mon = Inv_Month;
2490 int year = 0;
2491
2492 const wxChar *input = date;
2493 for ( const wxChar *fmt = format; *fmt; fmt++ )
2494 {
2495 if ( *fmt != _T('%') )
2496 {
2497 if ( wxIsspace(*fmt) )
2498 {
2499 // a white space in the format string matches 0 or more white
2500 // spaces in the input
2501 while ( wxIsspace(*input) )
2502 {
2503 input++;
2504 }
2505 }
2506 else // !space
2507 {
2508 // any other character (not whitespace, not '%') must be
2509 // matched by itself in the input
2510 if ( *input++ != *fmt )
2511 {
2512 // no match
2513 return (wxChar *)NULL;
2514 }
2515 }
2516
2517 // done with this format char
2518 continue;
2519 }
2520
2521 // start of a format specification
2522
2523 // parse the optional width
2524 size_t width = 0;
2525 while ( isdigit(*++fmt) )
2526 {
2527 width *= 10;
2528 width += *fmt - _T('0');
2529 }
2530
2531 // then the format itself
2532 switch ( *fmt )
2533 {
2534 case _T('a'): // a weekday name
2535 case _T('A'):
2536 {
2537 int flag = *fmt == _T('a') ? Name_Abbr : Name_Full;
2538 wday = GetWeekDayFromName(GetAlphaToken(input), flag);
2539 if ( wday == Inv_WeekDay )
2540 {
2541 // no match
2542 return (wxChar *)NULL;
2543 }
2544 }
2545 haveWDay = TRUE;
2546 break;
2547
2548 case _T('b'): // a month name
2549 case _T('B'):
2550 {
2551 int flag = *fmt == _T('b') ? Name_Abbr : Name_Full;
2552 mon = GetMonthFromName(GetAlphaToken(input), flag);
2553 if ( mon == Inv_Month )
2554 {
2555 // no match
2556 return (wxChar *)NULL;
2557 }
2558 }
2559 haveMon = TRUE;
2560 break;
2561
2562 case _T('c'): // locale default date and time representation
2563 {
2564 wxDateTime dt;
2565
2566 // this is the format which corresponds to ctime() output
2567 // and strptime("%c") should parse it, so try it first
2568 static const wxChar *fmtCtime = _T("%a %b %d %H:%M:%S %Y");
2569
2570 const wxChar *result = dt.ParseFormat(input, fmtCtime);
2571 if ( !result )
2572 {
2573 result = dt.ParseFormat(input, _T("%x %X"));
2574 }
2575
2576 if ( !result )
2577 {
2578 result = dt.ParseFormat(input, _T("%X %x"));
2579 }
2580
2581 if ( !result )
2582 {
2583 // we've tried everything and still no match
2584 return (wxChar *)NULL;
2585 }
2586
2587 Tm tm = dt.GetTm();
2588
2589 haveDay = haveMon = haveYear =
2590 haveHour = haveMin = haveSec = TRUE;
2591
2592 hour = tm.hour;
2593 min = tm.min;
2594 sec = tm.sec;
2595
2596 year = tm.year;
2597 mon = tm.mon;
2598 mday = tm.mday;
2599
2600 input = result;
2601 }
2602 break;
2603
2604 case _T('d'): // day of a month (01-31)
2605 if ( !GetNumericToken(width, input, &num) ||
2606 (num > 31) || (num < 1) )
2607 {
2608 // no match
2609 return (wxChar *)NULL;
2610 }
2611
2612 // we can't check whether the day range is correct yet, will
2613 // do it later - assume ok for now
2614 haveDay = TRUE;
2615 mday = (wxDateTime_t)num;
2616 break;
2617
2618 case _T('H'): // hour in 24h format (00-23)
2619 if ( !GetNumericToken(width, input, &num) || (num > 23) )
2620 {
2621 // no match
2622 return (wxChar *)NULL;
2623 }
2624
2625 haveHour = TRUE;
2626 hour = (wxDateTime_t)num;
2627 break;
2628
2629 case _T('I'): // hour in 12h format (01-12)
2630 if ( !GetNumericToken(width, input, &num) || !num || (num > 12) )
2631 {
2632 // no match
2633 return (wxChar *)NULL;
2634 }
2635
2636 haveHour = TRUE;
2637 hourIsIn12hFormat = TRUE;
2638 hour = (wxDateTime_t)(num % 12); // 12 should be 0
2639 break;
2640
2641 case _T('j'): // day of the year
2642 if ( !GetNumericToken(width, input, &num) || !num || (num > 366) )
2643 {
2644 // no match
2645 return (wxChar *)NULL;
2646 }
2647
2648 haveYDay = TRUE;
2649 yday = (wxDateTime_t)num;
2650 break;
2651
2652 case _T('m'): // month as a number (01-12)
2653 if ( !GetNumericToken(width, input, &num) || !num || (num > 12) )
2654 {
2655 // no match
2656 return (wxChar *)NULL;
2657 }
2658
2659 haveMon = TRUE;
2660 mon = (Month)(num - 1);
2661 break;
2662
2663 case _T('M'): // minute as a decimal number (00-59)
2664 if ( !GetNumericToken(width, input, &num) || (num > 59) )
2665 {
2666 // no match
2667 return (wxChar *)NULL;
2668 }
2669
2670 haveMin = TRUE;
2671 min = (wxDateTime_t)num;
2672 break;
2673
2674 case _T('p'): // AM or PM string
2675 {
2676 wxString am, pm, token = GetAlphaToken(input);
2677
2678 GetAmPmStrings(&am, &pm);
2679 if ( token.CmpNoCase(pm) == 0 )
2680 {
2681 isPM = TRUE;
2682 }
2683 else if ( token.CmpNoCase(am) != 0 )
2684 {
2685 // no match
2686 return (wxChar *)NULL;
2687 }
2688 }
2689 break;
2690
2691 case _T('r'): // time as %I:%M:%S %p
2692 {
2693 wxDateTime dt;
2694 input = dt.ParseFormat(input, _T("%I:%M:%S %p"));
2695 if ( !input )
2696 {
2697 // no match
2698 return (wxChar *)NULL;
2699 }
2700
2701 haveHour = haveMin = haveSec = TRUE;
2702
2703 Tm tm = dt.GetTm();
2704 hour = tm.hour;
2705 min = tm.min;
2706 sec = tm.sec;
2707 }
2708 break;
2709
2710 case _T('R'): // time as %H:%M
2711 {
2712 wxDateTime dt;
2713 input = dt.ParseFormat(input, _T("%H:%M"));
2714 if ( !input )
2715 {
2716 // no match
2717 return (wxChar *)NULL;
2718 }
2719
2720 haveHour = haveMin = TRUE;
2721
2722 Tm tm = dt.GetTm();
2723 hour = tm.hour;
2724 min = tm.min;
2725 }
2726
2727 case _T('S'): // second as a decimal number (00-61)
2728 if ( !GetNumericToken(width, input, &num) || (num > 61) )
2729 {
2730 // no match
2731 return (wxChar *)NULL;
2732 }
2733
2734 haveSec = TRUE;
2735 sec = (wxDateTime_t)num;
2736 break;
2737
2738 case _T('T'): // time as %H:%M:%S
2739 {
2740 wxDateTime dt;
2741 input = dt.ParseFormat(input, _T("%H:%M:%S"));
2742 if ( !input )
2743 {
2744 // no match
2745 return (wxChar *)NULL;
2746 }
2747
2748 haveHour = haveMin = haveSec = TRUE;
2749
2750 Tm tm = dt.GetTm();
2751 hour = tm.hour;
2752 min = tm.min;
2753 sec = tm.sec;
2754 }
2755 break;
2756
2757 case _T('w'): // weekday as a number (0-6), Sunday = 0
2758 if ( !GetNumericToken(width, input, &num) || (wday > 6) )
2759 {
2760 // no match
2761 return (wxChar *)NULL;
2762 }
2763
2764 haveWDay = TRUE;
2765 wday = (WeekDay)num;
2766 break;
2767
2768 case _T('x'): // locale default date representation
2769 #ifdef HAVE_STRPTIME
2770 // try using strptime() - it may fail even if the input is
2771 // correct but the date is out of range, so we will fall back
2772 // to our generic code anyhow (FIXME !Unicode friendly)
2773 {
2774 struct tm tm;
2775 const wxChar *result = strptime(input, "%x", &tm);
2776 if ( result )
2777 {
2778 input = result;
2779
2780 haveDay = haveMon = haveYear = TRUE;
2781
2782 year = 1900 + tm.tm_year;
2783 mon = (Month)tm.tm_mon;
2784 mday = tm.tm_mday;
2785
2786 break;
2787 }
2788 }
2789 #endif // HAVE_STRPTIME
2790
2791 // TODO query the LOCALE_IDATE setting under Win32
2792 {
2793 wxDateTime dt;
2794
2795 wxString fmtDate, fmtDateAlt;
2796 if ( IsWestEuropeanCountry(GetCountry()) ||
2797 GetCountry() == Russia )
2798 {
2799 fmtDate = _T("%d/%m/%y");
2800 fmtDateAlt = _T("%m/%d/%y");
2801 }
2802 else // assume USA
2803 {
2804 fmtDate = _T("%m/%d/%y");
2805 fmtDateAlt = _T("%d/%m/%y");
2806 }
2807
2808 const wxChar *result = dt.ParseFormat(input, fmtDate);
2809
2810 if ( !result )
2811 {
2812 // ok, be nice and try another one
2813 result = dt.ParseFormat(input, fmtDateAlt);
2814 }
2815
2816 if ( !result )
2817 {
2818 // bad luck
2819 return (wxChar *)NULL;
2820 }
2821
2822 Tm tm = dt.GetTm();
2823
2824 haveDay = haveMon = haveYear = TRUE;
2825
2826 year = tm.year;
2827 mon = tm.mon;
2828 mday = tm.mday;
2829
2830 input = result;
2831 }
2832
2833 break;
2834
2835 case _T('X'): // locale default time representation
2836 #ifdef HAVE_STRPTIME
2837 {
2838 // use strptime() to do it for us (FIXME !Unicode friendly)
2839 struct tm tm;
2840 input = strptime(input, "%X", &tm);
2841 if ( !input )
2842 {
2843 return (wxChar *)NULL;
2844 }
2845
2846 haveHour = haveMin = haveSec = TRUE;
2847
2848 hour = tm.tm_hour;
2849 min = tm.tm_min;
2850 sec = tm.tm_sec;
2851 }
2852 #else // !HAVE_STRPTIME
2853 // TODO under Win32 we can query the LOCALE_ITIME system
2854 // setting which says whether the default time format is
2855 // 24 or 12 hour
2856 {
2857 // try to parse what follows as "%H:%M:%S" and, if this
2858 // fails, as "%I:%M:%S %p" - this should catch the most
2859 // common cases
2860 wxDateTime dt;
2861
2862 const wxChar *result = dt.ParseFormat(input, _T("%T"));
2863 if ( !result )
2864 {
2865 result = dt.ParseFormat(input, _T("%r"));
2866 }
2867
2868 if ( !result )
2869 {
2870 // no match
2871 return (wxChar *)NULL;
2872 }
2873
2874 haveHour = haveMin = haveSec = TRUE;
2875
2876 Tm tm = dt.GetTm();
2877 hour = tm.hour;
2878 min = tm.min;
2879 sec = tm.sec;
2880
2881 input = result;
2882 }
2883 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
2884 break;
2885
2886 case _T('y'): // year without century (00-99)
2887 if ( !GetNumericToken(width, input, &num) || (num > 99) )
2888 {
2889 // no match
2890 return (wxChar *)NULL;
2891 }
2892
2893 haveYear = TRUE;
2894
2895 // TODO should have an option for roll over date instead of
2896 // hard coding it here
2897 year = (num > 30 ? 1900 : 2000) + (wxDateTime_t)num;
2898 break;
2899
2900 case _T('Y'): // year with century
2901 if ( !GetNumericToken(width, input, &num) )
2902 {
2903 // no match
2904 return (wxChar *)NULL;
2905 }
2906
2907 haveYear = TRUE;
2908 year = (wxDateTime_t)num;
2909 break;
2910
2911 case _T('Z'): // timezone name
2912 wxFAIL_MSG(_T("TODO"));
2913 break;
2914
2915 case _T('%'): // a percent sign
2916 if ( *input++ != _T('%') )
2917 {
2918 // no match
2919 return (wxChar *)NULL;
2920 }
2921 break;
2922
2923 case 0: // the end of string
2924 wxFAIL_MSG(_T("unexpected format end"));
2925
2926 // fall through
2927
2928 default: // not a known format spec
2929 return (wxChar *)NULL;
2930 }
2931 }
2932
2933 // format matched, try to construct a date from what we have now
2934 Tm tmDef;
2935 if ( dateDef.IsValid() )
2936 {
2937 // take this date as default
2938 tmDef = dateDef.GetTm();
2939 }
2940 else if ( IsValid() )
2941 {
2942 // if this date is valid, don't change it
2943 tmDef = GetTm();
2944 }
2945 else
2946 {
2947 // no default and this date is invalid - fall back to Today()
2948 tmDef = Today().GetTm();
2949 }
2950
2951 Tm tm = tmDef;
2952
2953 // set the date
2954 if ( haveYear )
2955 {
2956 tm.year = year;
2957 }
2958
2959 // TODO we don't check here that the values are consistent, if both year
2960 // day and month/day were found, we just ignore the year day and we
2961 // also always ignore the week day
2962 if ( haveMon && haveDay )
2963 {
2964 if ( mday > GetNumOfDaysInMonth(tm.year, mon) )
2965 {
2966 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
2967
2968 return (wxChar *)NULL;
2969 }
2970
2971 tm.mon = mon;
2972 tm.mday = mday;
2973 }
2974 else if ( haveYDay )
2975 {
2976 if ( yday > GetNumberOfDays(tm.year) )
2977 {
2978 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
2979
2980 return (wxChar *)NULL;
2981 }
2982
2983 Tm tm2 = wxDateTime(1, Jan, tm.year).SetToYearDay(yday).GetTm();
2984
2985 tm.mon = tm2.mon;
2986 tm.mday = tm2.mday;
2987 }
2988
2989 // deal with AM/PM
2990 if ( haveHour && hourIsIn12hFormat && isPM )
2991 {
2992 // translate to 24hour format
2993 hour += 12;
2994 }
2995 //else: either already in 24h format or no translation needed
2996
2997 // set the time
2998 if ( haveHour )
2999 {
3000 tm.hour = hour;
3001 }
3002
3003 if ( haveMin )
3004 {
3005 tm.min = min;
3006 }
3007
3008 if ( haveSec )
3009 {
3010 tm.sec = sec;
3011 }
3012
3013 Set(tm);
3014
3015 return input;
3016 }
3017
3018 const wxChar *wxDateTime::ParseDateTime(const wxChar *date)
3019 {
3020 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3021
3022 // there is a public domain version of getdate.y, but it only works for
3023 // English...
3024 wxFAIL_MSG(_T("TODO"));
3025
3026 return (wxChar *)NULL;
3027 }
3028
3029 const wxChar *wxDateTime::ParseDate(const wxChar *date)
3030 {
3031 // this is a simplified version of ParseDateTime() which understands only
3032 // "today" (for wxDate compatibility) and digits only otherwise (and not
3033 // all esoteric constructions ParseDateTime() knows about)
3034
3035 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3036
3037 const wxChar *p = date;
3038 while ( wxIsspace(*p) )
3039 p++;
3040
3041 // some special cases
3042 static struct
3043 {
3044 const wxChar *str;
3045 int dayDiffFromToday;
3046 } literalDates[] =
3047 {
3048 { wxTRANSLATE("today"), 0 },
3049 { wxTRANSLATE("yesterday"), -1 },
3050 { wxTRANSLATE("tomorrow"), 1 },
3051 };
3052
3053 for ( size_t n = 0; n < WXSIZEOF(literalDates); n++ )
3054 {
3055 wxString date = wxGetTranslation(literalDates[n].str);
3056 size_t len = date.length();
3057 if ( wxStrlen(p) >= len && (wxString(p, len).CmpNoCase(date) == 0) )
3058 {
3059 // nothing can follow this, so stop here
3060 p += len;
3061
3062 int dayDiffFromToday = literalDates[n].dayDiffFromToday;
3063 *this = Today();
3064 if ( dayDiffFromToday )
3065 {
3066 *this += wxDateSpan::Days(dayDiffFromToday);
3067 }
3068
3069 return p;
3070 }
3071 }
3072
3073 // We try to guess what we have here: for each new (numeric) token, we
3074 // determine if it can be a month, day or a year. Of course, there is an
3075 // ambiguity as some numbers may be days as well as months, so we also
3076 // have the ability to back track.
3077
3078 // what do we have?
3079 bool haveDay = FALSE, // the months day?
3080 haveWDay = FALSE, // the day of week?
3081 haveMon = FALSE, // the month?
3082 haveYear = FALSE; // the year?
3083
3084 // and the value of the items we have (init them to get rid of warnings)
3085 WeekDay wday = Inv_WeekDay;
3086 wxDateTime_t day = 0;
3087 wxDateTime::Month mon = Inv_Month;
3088 int year = 0;
3089
3090 // tokenize the string
3091 size_t nPosCur = 0;
3092 static const wxChar *dateDelimiters = _T(".,/-\t\n ");
3093 wxStringTokenizer tok(p, dateDelimiters);
3094 while ( tok.HasMoreTokens() )
3095 {
3096 wxString token = tok.GetNextToken();
3097 if ( !token )
3098 continue;
3099
3100 // is it a number?
3101 unsigned long val;
3102 if ( token.ToULong(&val) )
3103 {
3104 // guess what this number is
3105
3106 bool isDay = FALSE,
3107 isMonth = FALSE,
3108 isYear = FALSE;
3109
3110 if ( !haveMon && val > 0 && val <= 12 )
3111 {
3112 // assume it is month
3113 isMonth = TRUE;
3114 }
3115 else // not the month
3116 {
3117 wxDateTime_t maxDays = haveMon
3118 ? GetNumOfDaysInMonth(haveYear ? year : Inv_Year, mon)
3119 : 31;
3120
3121 // can it be day?
3122 if ( (val == 0) || (val > (unsigned long)maxDays) ) // cast to shut up compiler warning in BCC
3123 {
3124 isYear = TRUE;
3125 }
3126 else
3127 {
3128 isDay = TRUE;
3129 }
3130 }
3131
3132 if ( isYear )
3133 {
3134 if ( haveYear )
3135 break;
3136
3137 haveYear = TRUE;
3138
3139 year = (wxDateTime_t)val;
3140 }
3141 else if ( isDay )
3142 {
3143 if ( haveDay )
3144 break;
3145
3146 haveDay = TRUE;
3147
3148 day = (wxDateTime_t)val;
3149 }
3150 else if ( isMonth )
3151 {
3152 haveMon = TRUE;
3153
3154 mon = (Month)(val - 1);
3155 }
3156 }
3157 else // not a number
3158 {
3159 // be careful not to overwrite the current mon value
3160 Month mon2 = GetMonthFromName(token, Name_Full | Name_Abbr);
3161 if ( mon2 != Inv_Month )
3162 {
3163 // it's a month
3164 if ( haveMon )
3165 {
3166 // but we already have a month - maybe we guessed wrong?
3167 if ( !haveDay )
3168 {
3169 // no need to check in month range as always < 12, but
3170 // the days are counted from 1 unlike the months
3171 day = (wxDateTime_t)mon + 1;
3172 haveDay = TRUE;
3173 }
3174 else
3175 {
3176 // could possible be the year (doesn't the year come
3177 // before the month in the japanese format?) (FIXME)
3178 break;
3179 }
3180 }
3181
3182 mon = mon2;
3183
3184 haveMon = TRUE;
3185 }
3186 else // not a valid month name
3187 {
3188 wday = GetWeekDayFromName(token, Name_Full | Name_Abbr);
3189 if ( wday != Inv_WeekDay )
3190 {
3191 // a week day
3192 if ( haveWDay )
3193 {
3194 break;
3195 }
3196
3197 haveWDay = TRUE;
3198 }
3199 else // not a valid weekday name
3200 {
3201 // try the ordinals
3202 static const wxChar *ordinals[] =
3203 {
3204 wxTRANSLATE("first"),
3205 wxTRANSLATE("second"),
3206 wxTRANSLATE("third"),
3207 wxTRANSLATE("fourth"),
3208 wxTRANSLATE("fifth"),
3209 wxTRANSLATE("sixth"),
3210 wxTRANSLATE("seventh"),
3211 wxTRANSLATE("eighth"),
3212 wxTRANSLATE("ninth"),
3213 wxTRANSLATE("tenth"),
3214 wxTRANSLATE("eleventh"),
3215 wxTRANSLATE("twelfth"),
3216 wxTRANSLATE("thirteenth"),
3217 wxTRANSLATE("fourteenth"),
3218 wxTRANSLATE("fifteenth"),
3219 wxTRANSLATE("sixteenth"),
3220 wxTRANSLATE("seventeenth"),
3221 wxTRANSLATE("eighteenth"),
3222 wxTRANSLATE("nineteenth"),
3223 wxTRANSLATE("twentieth"),
3224 // that's enough - otherwise we'd have problems with
3225 // composite (or not) ordinals
3226 };
3227
3228 size_t n;
3229 for ( n = 0; n < WXSIZEOF(ordinals); n++ )
3230 {
3231 if ( token.CmpNoCase(ordinals[n]) == 0 )
3232 {
3233 break;
3234 }
3235 }
3236
3237 if ( n == WXSIZEOF(ordinals) )
3238 {
3239 // stop here - something unknown
3240 break;
3241 }
3242
3243 // it's a day
3244 if ( haveDay )
3245 {
3246 // don't try anything here (as in case of numeric day
3247 // above) - the symbolic day spec should always
3248 // precede the month/year
3249 break;
3250 }
3251
3252 haveDay = TRUE;
3253
3254 day = (wxDateTime_t)(n + 1);
3255 }
3256 }
3257 }
3258
3259 nPosCur = tok.GetPosition();
3260 }
3261
3262 // either no more tokens or the scan was stopped by something we couldn't
3263 // parse - in any case, see if we can construct a date from what we have
3264 if ( !haveDay && !haveWDay )
3265 {
3266 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3267
3268 return (wxChar *)NULL;
3269 }
3270
3271 if ( haveWDay && (haveMon || haveYear || haveDay) &&
3272 !(haveDay && haveMon && haveYear) )
3273 {
3274 // without adjectives (which we don't support here) the week day only
3275 // makes sense completely separately or with the full date
3276 // specification (what would "Wed 1999" mean?)
3277 return (wxChar *)NULL;
3278 }
3279
3280 if ( !haveWDay && haveYear && !(haveDay && haveMon) )
3281 {
3282 // may be we have month and day instead of day and year?
3283 if ( haveDay && !haveMon )
3284 {
3285 if ( day <= 12 )
3286 {
3287 // exchange day and month
3288 mon = (wxDateTime::Month)(day - 1);
3289
3290 // we're in the current year then
3291 if ( (year > 0) &&
3292 (unsigned)year <= GetNumOfDaysInMonth(Inv_Year, mon) )
3293 {
3294 day = year;
3295
3296 haveMon = TRUE;
3297 haveYear = FALSE;
3298 }
3299 //else: no, can't exchange, leave haveMon == FALSE
3300 }
3301 }
3302
3303 if ( !haveMon )
3304 {
3305 // if we give the year, month and day must be given too
3306 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3307
3308 return (wxChar *)NULL;
3309 }
3310 }
3311
3312 if ( !haveMon )
3313 {
3314 mon = GetCurrentMonth();
3315 }
3316
3317 if ( !haveYear )
3318 {
3319 year = GetCurrentYear();
3320 }
3321
3322 if ( haveDay )
3323 {
3324 Set(day, mon, year);
3325
3326 if ( haveWDay )
3327 {
3328 // check that it is really the same
3329 if ( GetWeekDay() != wday )
3330 {
3331 // inconsistency detected
3332 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3333
3334 return (wxChar *)NULL;
3335 }
3336 }
3337 }
3338 else // haveWDay
3339 {
3340 *this = Today();
3341
3342 SetToWeekDayInSameWeek(wday);
3343 }
3344
3345 // return the pointer to the first unparsed char
3346 p += nPosCur;
3347 if ( nPosCur && wxStrchr(dateDelimiters, *(p - 1)) )
3348 {
3349 // if we couldn't parse the token after the delimiter, put back the
3350 // delimiter as well
3351 p--;
3352 }
3353
3354 return p;
3355 }
3356
3357 const wxChar *wxDateTime::ParseTime(const wxChar *time)
3358 {
3359 wxCHECK_MSG( time, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3360
3361 // first try some extra things
3362 static const struct
3363 {
3364 const wxChar *name;
3365 wxDateTime_t hour;
3366 } stdTimes[] =
3367 {
3368 { wxTRANSLATE("noon"), 12 },
3369 { wxTRANSLATE("midnight"), 00 },
3370 // anything else?
3371 };
3372
3373 for ( size_t n = 0; n < WXSIZEOF(stdTimes); n++ )
3374 {
3375 wxString timeString = wxGetTranslation(stdTimes[n].name);
3376 size_t len = timeString.length();
3377 if ( timeString.CmpNoCase(wxString(time, len)) == 0 )
3378 {
3379 Set(stdTimes[n].hour, 0, 0);
3380
3381 return time + len;
3382 }
3383 }
3384
3385 // try all time formats we may think about in the order from longest to
3386 // shortest
3387
3388 // 12hour with AM/PM?
3389 const wxChar *result = ParseFormat(time, _T("%I:%M:%S %p"));
3390
3391 if ( !result )
3392 {
3393 // normally, it's the same, but why not try it?
3394 result = ParseFormat(time, _T("%H:%M:%S"));
3395 }
3396
3397 if ( !result )
3398 {
3399 // 12hour with AM/PM but without seconds?
3400 result = ParseFormat(time, _T("%I:%M %p"));
3401 }
3402
3403 if ( !result )
3404 {
3405 // without seconds?
3406 result = ParseFormat(time, _T("%H:%M"));
3407 }
3408
3409 if ( !result )
3410 {
3411 // just the hour and AM/PM?
3412 result = ParseFormat(time, _T("%I %p"));
3413 }
3414
3415 if ( !result )
3416 {
3417 // just the hour?
3418 result = ParseFormat(time, _T("%H"));
3419 }
3420
3421 if ( !result )
3422 {
3423 // parse the standard format: normally it is one of the formats above
3424 // but it may be set to something completely different by the user
3425 result = ParseFormat(time, _T("%X"));
3426 }
3427
3428 // TODO: parse timezones
3429
3430 return result;
3431 }
3432
3433 // ----------------------------------------------------------------------------
3434 // Workdays and holidays support
3435 // ----------------------------------------------------------------------------
3436
3437 bool wxDateTime::IsWorkDay(Country WXUNUSED(country)) const
3438 {
3439 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3440 }
3441
3442 // ============================================================================
3443 // wxTimeSpan
3444 // ============================================================================
3445
3446 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3447 // it locally to the method as it provokes an internal compiler error in egcs
3448 // 2.91.60 when building with -O2
3449 enum TimeSpanPart
3450 {
3451 Part_Week,
3452 Part_Day,
3453 Part_Hour,
3454 Part_Min,
3455 Part_Sec,
3456 Part_MSec
3457 };
3458
3459 // not all strftime(3) format specifiers make sense here because, for example,
3460 // a time span doesn't have a year nor a timezone
3461 //
3462 // Here are the ones which are supported (all of them are supported by strftime
3463 // as well):
3464 // %H hour in 24 hour format
3465 // %M minute (00 - 59)
3466 // %S second (00 - 59)
3467 // %% percent sign
3468 //
3469 // Also, for MFC CTimeSpan compatibility, we support
3470 // %D number of days
3471 //
3472 // And, to be better than MFC :-), we also have
3473 // %E number of wEeks
3474 // %l milliseconds (000 - 999)
3475 wxString wxTimeSpan::Format(const wxChar *format) const
3476 {
3477 wxCHECK_MSG( format, _T(""), _T("NULL format in wxTimeSpan::Format") );
3478
3479 wxString str;
3480 str.Alloc(wxStrlen(format));
3481
3482 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3483 //
3484 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3485 // question is what should ts.Format("%S") do? The code here returns "3273"
3486 // in this case (i.e. the total number of seconds, not just seconds % 60)
3487 // because, for me, this call means "give me entire time interval in
3488 // seconds" and not "give me the seconds part of the time interval"
3489 //
3490 // If we agree that it should behave like this, it is clear that the
3491 // interpretation of each format specifier depends on the presence of the
3492 // other format specs in the string: if there was "%H" before "%M", we
3493 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3494
3495 // we remember the most important unit found so far
3496 TimeSpanPart partBiggest = Part_MSec;
3497
3498 for ( const wxChar *pch = format; *pch; pch++ )
3499 {
3500 wxChar ch = *pch;
3501
3502 if ( ch == _T('%') )
3503 {
3504 // the start of the format specification of the printf() below
3505 wxString fmtPrefix = _T('%');
3506
3507 // the number
3508 long n;
3509
3510 ch = *++pch; // get the format spec char
3511 switch ( ch )
3512 {
3513 default:
3514 wxFAIL_MSG( _T("invalid format character") );
3515 // fall through
3516
3517 case _T('%'):
3518 str += ch;
3519
3520 // skip the part below switch
3521 continue;
3522
3523 case _T('D'):
3524 n = GetDays();
3525 if ( partBiggest < Part_Day )
3526 {
3527 n %= DAYS_PER_WEEK;
3528 }
3529 else
3530 {
3531 partBiggest = Part_Day;
3532 }
3533 break;
3534
3535 case _T('E'):
3536 partBiggest = Part_Week;
3537 n = GetWeeks();
3538 break;
3539
3540 case _T('H'):
3541 n = GetHours();
3542 if ( partBiggest < Part_Hour )
3543 {
3544 n %= HOURS_PER_DAY;
3545 }
3546 else
3547 {
3548 partBiggest = Part_Hour;
3549 }
3550
3551 fmtPrefix += _T("02");
3552 break;
3553
3554 case _T('l'):
3555 n = GetMilliseconds().ToLong();
3556 if ( partBiggest < Part_MSec )
3557 {
3558 n %= 1000;
3559 }
3560 //else: no need to reset partBiggest to Part_MSec, it is
3561 // the least significant one anyhow
3562
3563 fmtPrefix += _T("03");
3564 break;
3565
3566 case _T('M'):
3567 n = GetMinutes();
3568 if ( partBiggest < Part_Min )
3569 {
3570 n %= MIN_PER_HOUR;
3571 }
3572 else
3573 {
3574 partBiggest = Part_Min;
3575 }
3576
3577 fmtPrefix += _T("02");
3578 break;
3579
3580 case _T('S'):
3581 n = GetSeconds().ToLong();
3582 if ( partBiggest < Part_Sec )
3583 {
3584 n %= SEC_PER_MIN;
3585 }
3586 else
3587 {
3588 partBiggest = Part_Sec;
3589 }
3590
3591 fmtPrefix += _T("02");
3592 break;
3593 }
3594
3595 str += wxString::Format(fmtPrefix + _T("ld"), n);
3596 }
3597 else
3598 {
3599 // normal character, just copy
3600 str += ch;
3601 }
3602 }
3603
3604 return str;
3605 }
3606
3607 // ============================================================================
3608 // wxDateTimeHolidayAuthority and related classes
3609 // ============================================================================
3610
3611 #include "wx/arrimpl.cpp"
3612
3613 WX_DEFINE_OBJARRAY(wxDateTimeArray);
3614
3615 static int wxCMPFUNC_CONV
3616 wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
3617 {
3618 wxDateTime dt1 = **first,
3619 dt2 = **second;
3620
3621 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
3622 }
3623
3624 // ----------------------------------------------------------------------------
3625 // wxDateTimeHolidayAuthority
3626 // ----------------------------------------------------------------------------
3627
3628 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
3629
3630 /* static */
3631 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
3632 {
3633 size_t count = ms_authorities.GetCount();
3634 for ( size_t n = 0; n < count; n++ )
3635 {
3636 if ( ms_authorities[n]->DoIsHoliday(dt) )
3637 {
3638 return TRUE;
3639 }
3640 }
3641
3642 return FALSE;
3643 }
3644
3645 /* static */
3646 size_t
3647 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
3648 const wxDateTime& dtEnd,
3649 wxDateTimeArray& holidays)
3650 {
3651 wxDateTimeArray hol;
3652
3653 holidays.Empty();
3654
3655 size_t count = ms_authorities.GetCount();
3656 for ( size_t nAuth = 0; nAuth < count; nAuth++ )
3657 {
3658 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
3659
3660 WX_APPEND_ARRAY(holidays, hol);
3661 }
3662
3663 holidays.Sort(wxDateTimeCompareFunc);
3664
3665 return holidays.GetCount();
3666 }
3667
3668 /* static */
3669 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3670 {
3671 WX_CLEAR_ARRAY(ms_authorities);
3672 }
3673
3674 /* static */
3675 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
3676 {
3677 ms_authorities.Add(auth);
3678 }
3679
3680 // ----------------------------------------------------------------------------
3681 // wxDateTimeWorkDays
3682 // ----------------------------------------------------------------------------
3683
3684 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
3685 {
3686 wxDateTime::WeekDay wd = dt.GetWeekDay();
3687
3688 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
3689 }
3690
3691 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
3692 const wxDateTime& dtEnd,
3693 wxDateTimeArray& holidays) const
3694 {
3695 if ( dtStart > dtEnd )
3696 {
3697 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3698
3699 return 0u;
3700 }
3701
3702 holidays.Empty();
3703
3704 // instead of checking all days, start with the first Sat after dtStart and
3705 // end with the last Sun before dtEnd
3706 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
3707 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
3708 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
3709 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
3710 dt;
3711
3712 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
3713 {
3714 holidays.Add(dt);
3715 }
3716
3717 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
3718 {
3719 holidays.Add(dt);
3720 }
3721
3722 return holidays.GetCount();
3723 }
3724
3725 #endif // wxUSE_DATETIME