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