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