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