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