build fix (part of r59673, r59656)
[wxWidgets.git] / src / common / datetime.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/datetime.cpp
3 // Purpose: implementation of time/date related classes
4 // (for formatting&parsing see datetimefmt.cpp)
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 11.05.99
8 // RCS-ID: $Id$
9 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // parts of code taken from sndcal library by Scott E. Lee:
11 //
12 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
13 // Permission granted to use, copy, modify, distribute and sell
14 // so long as the above copyright and this permission statement
15 // are retained in all copies.
16 //
17 // Licence: wxWindows licence
18 ///////////////////////////////////////////////////////////////////////////////
19
20 /*
21 * Implementation notes:
22 *
23 * 1. the time is stored as a 64bit integer containing the signed number of
24 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
25 * expressed in GMT.
26 *
27 * 2. the range is thus something about 580 million years, but due to current
28 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 *
30 * 3. standard ANSI C functions are used to do time calculations whenever
31 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 *
33 * 4. otherwise, the calculations are done by converting the date to/from JDN
34 * first (the range limitation mentioned above comes from here: the
35 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
36 * or less)
37 *
38 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
39 * this moment in local time and may be converted to the object
40 * corresponding to the same date/time in another time zone by using
41 * ToTimezone()
42 *
43 * 6. the conversions to the current (or any other) timezone are done when the
44 * internal time representation is converted to the broken-down one in
45 * wxDateTime::Tm.
46 */
47
48 // ============================================================================
49 // declarations
50 // ============================================================================
51
52 // ----------------------------------------------------------------------------
53 // headers
54 // ----------------------------------------------------------------------------
55
56 // For compilers that support precompilation, includes "wx.h".
57 #include "wx/wxprec.h"
58
59 #ifdef __BORLANDC__
60 #pragma hdrstop
61 #endif
62
63 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
64
65 #ifndef WX_PRECOMP
66 #ifdef __WXMSW__
67 #include "wx/msw/wrapwin.h"
68 #endif
69 #include "wx/string.h"
70 #include "wx/log.h"
71 #include "wx/intl.h"
72 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
73 #include "wx/module.h"
74 #include "wx/crt.h"
75 #endif // WX_PRECOMP
76
77 #include "wx/thread.h"
78 #include "wx/tokenzr.h"
79
80 #include <ctype.h>
81
82 #ifdef __WINDOWS__
83 #include <winnls.h>
84 #ifndef __WXWINCE__
85 #include <locale.h>
86 #endif
87 #endif
88
89 #include "wx/datetime.h"
90
91 // ----------------------------------------------------------------------------
92 // wxXTI
93 // ----------------------------------------------------------------------------
94
95 #if wxUSE_EXTENDED_RTTI
96
97 template<> void wxStringReadValue(const wxString &s , wxDateTime &data )
98 {
99 data.ParseFormat(s,"%Y-%m-%d %H:%M:%S", NULL);
100 }
101
102 template<> void wxStringWriteValue(wxString &s , const wxDateTime &data )
103 {
104 s = data.Format("%Y-%m-%d %H:%M:%S");
105 }
106
107 wxCUSTOM_TYPE_INFO(wxDateTime, wxToStringConverter<wxDateTime> , wxFromStringConverter<wxDateTime>)
108
109 #endif // wxUSE_EXTENDED_RTTI
110
111
112 // ----------------------------------------------------------------------------
113 // conditional compilation
114 // ----------------------------------------------------------------------------
115
116 #if defined(__MWERKS__) && wxUSE_UNICODE
117 #include <wtime.h>
118 #endif
119
120 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
121 #if defined(__WXPALMOS__)
122 #define WX_GMTOFF_IN_TM
123 #elif defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
124 #define WX_TIMEZONE _timezone
125 #elif defined(__MWERKS__)
126 long wxmw_timezone = 28800;
127 #define WX_TIMEZONE wxmw_timezone
128 #elif defined(__DJGPP__) || defined(__WINE__)
129 #include <sys/timeb.h>
130 #include <values.h>
131 static long wxGetTimeZone()
132 {
133 static long timezone = MAXLONG; // invalid timezone
134 if (timezone == MAXLONG)
135 {
136 struct timeb tb;
137 ftime(&tb);
138 timezone = tb.timezone;
139 }
140 return timezone;
141 }
142 #define WX_TIMEZONE wxGetTimeZone()
143 #elif defined(__DARWIN__)
144 #define WX_GMTOFF_IN_TM
145 #elif defined(__WXWINCE__) && defined(__VISUALC8__)
146 // _timezone is not present in dynamic run-time library
147 #if 0
148 // Solution (1): use the function equivalent of _timezone
149 static long wxGetTimeZone()
150 {
151 static long s_Timezone = MAXLONG; // invalid timezone
152 if (s_Timezone == MAXLONG)
153 {
154 int t;
155 _get_timezone(& t);
156 s_Timezone = (long) t;
157 }
158 return s_Timezone;
159 }
160 #define WX_TIMEZONE wxGetTimeZone()
161 #elif 1
162 // Solution (2): using GetTimeZoneInformation
163 static long wxGetTimeZone()
164 {
165 static long timezone = MAXLONG; // invalid timezone
166 if (timezone == MAXLONG)
167 {
168 TIME_ZONE_INFORMATION tzi;
169 ::GetTimeZoneInformation(&tzi);
170 timezone = tzi.Bias;
171 }
172 return timezone;
173 }
174 #define WX_TIMEZONE wxGetTimeZone()
175 #else
176 // Old method using _timezone: this symbol doesn't exist in the dynamic run-time library (i.e. using /MD)
177 #define WX_TIMEZONE _timezone
178 #endif
179 #else // unknown platform - try timezone
180 #define WX_TIMEZONE timezone
181 #endif
182 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
183
184 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
185 #if defined(__WXWINCE__) && defined(__VISUALC8__)
186
187 struct tm *wxLocaltime_r(const time_t *t, struct tm* tm)
188 {
189 __time64_t t64 = *t;
190 return _localtime64_s(tm, &t64) == 0 ? tm : NULL;
191 }
192
193 struct tm *wxGmtime_r(const time_t* t, struct tm* tm)
194 {
195 __time64_t t64 = *t;
196 return _gmtime64_s(tm, &t64) == 0 ? tm : NULL;
197 }
198
199 #else // !wxWinCE with VC8
200
201 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
202 static wxMutex timeLock;
203 #endif
204
205 #ifndef HAVE_LOCALTIME_R
206 struct tm *wxLocaltime_r(const time_t* ticks, struct tm* temp)
207 {
208 #if wxUSE_THREADS && !defined(__WINDOWS__)
209 // No need to waste time with a mutex on windows since it's using
210 // thread local storage for localtime anyway.
211 wxMutexLocker locker(timeLock);
212 #endif
213
214 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
215 #ifdef __BORLANDC__
216 if ( !*ticks )
217 return NULL;
218 #endif
219
220 const tm * const t = localtime(ticks);
221 if ( !t )
222 return NULL;
223
224 memcpy(temp, t, sizeof(struct tm));
225 return temp;
226 }
227 #endif // !HAVE_LOCALTIME_R
228
229 #ifndef HAVE_GMTIME_R
230 struct tm *wxGmtime_r(const time_t* ticks, struct tm* temp)
231 {
232 #if wxUSE_THREADS && !defined(__WINDOWS__)
233 // No need to waste time with a mutex on windows since it's
234 // using thread local storage for gmtime anyway.
235 wxMutexLocker locker(timeLock);
236 #endif
237
238 #ifdef __BORLANDC__
239 if ( !*ticks )
240 return NULL;
241 #endif
242
243 const tm * const t = gmtime(ticks);
244 if ( !t )
245 return NULL;
246
247 memcpy(temp, gmtime(ticks), sizeof(struct tm));
248 return temp;
249 }
250 #endif // !HAVE_GMTIME_R
251
252 #endif // wxWinCE with VC8/other platforms
253
254 // ----------------------------------------------------------------------------
255 // macros
256 // ----------------------------------------------------------------------------
257
258 // debugging helper: just a convenient replacement of wxCHECK()
259 #define wxDATETIME_CHECK(expr, msg) \
260 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
261
262 // ----------------------------------------------------------------------------
263 // private classes
264 // ----------------------------------------------------------------------------
265
266 class wxDateTimeHolidaysModule : public wxModule
267 {
268 public:
269 virtual bool OnInit()
270 {
271 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays);
272
273 return true;
274 }
275
276 virtual void OnExit()
277 {
278 wxDateTimeHolidayAuthority::ClearAllAuthorities();
279 wxDateTimeHolidayAuthority::ms_authorities.clear();
280 }
281
282 private:
283 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule)
284 };
285
286 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule, wxModule)
287
288 // ----------------------------------------------------------------------------
289 // constants
290 // ----------------------------------------------------------------------------
291
292 // some trivial ones
293 static const int MONTHS_IN_YEAR = 12;
294
295 static const int SEC_PER_MIN = 60;
296
297 static const int MIN_PER_HOUR = 60;
298
299 static const int HOURS_PER_DAY = 24;
300
301 static const long SECONDS_PER_DAY = 86400l;
302
303 static const int DAYS_PER_WEEK = 7;
304
305 static const long MILLISECONDS_PER_DAY = 86400000l;
306
307 // this is the integral part of JDN of the midnight of Jan 1, 1970
308 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
309 static const long EPOCH_JDN = 2440587l;
310
311 // used only in asserts
312 #ifdef __WXDEBUG__
313 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
314 // reference date for us) is Nov 24, 4714BC
315 static const int JDN_0_YEAR = -4713;
316 static const int JDN_0_MONTH = wxDateTime::Nov;
317 static const int JDN_0_DAY = 24;
318 #endif // __WXDEBUG__
319
320 // the constants used for JDN calculations
321 static const long JDN_OFFSET = 32046l;
322 static const long DAYS_PER_5_MONTHS = 153l;
323 static const long DAYS_PER_4_YEARS = 1461l;
324 static const long DAYS_PER_400_YEARS = 146097l;
325
326 // this array contains the cumulated number of days in all previous months for
327 // normal and leap years
328 static const wxDateTime::wxDateTime_t gs_cumulatedDays[2][MONTHS_IN_YEAR] =
329 {
330 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
331 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
332 };
333
334 const long wxDateTime::TIME_T_FACTOR = 1000l;
335
336 // ----------------------------------------------------------------------------
337 // global data
338 // ----------------------------------------------------------------------------
339
340 const char *wxDefaultDateTimeFormat = "%c";
341 const char *wxDefaultTimeSpanFormat = "%H:%M:%S";
342
343 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
344 // indicate an invalid wxDateTime object
345 const wxDateTime wxDefaultDateTime;
346
347 wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
348
349 // ----------------------------------------------------------------------------
350 // private functions
351 // ----------------------------------------------------------------------------
352
353 // debugger helper: shows what the date really is
354 #ifdef __WXDEBUG__
355 extern const char *wxDumpDate(const wxDateTime* dt)
356 {
357 static char buf[128];
358
359 wxString fmt(dt->Format("%Y-%m-%d (%a) %H:%M:%S"));
360 wxStrlcpy(buf,
361 (fmt + " (" + dt->GetValue().ToString() + " ticks)").ToAscii(),
362 WXSIZEOF(buf));
363
364 return buf;
365 }
366 #endif // Debug
367
368 // get the number of days in the given month of the given year
369 static inline
370 wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
371 {
372 // the number of days in month in Julian/Gregorian calendar: the first line
373 // is for normal years, the second one is for the leap ones
374 static wxDateTime::wxDateTime_t daysInMonth[2][MONTHS_IN_YEAR] =
375 {
376 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
377 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
378 };
379
380 return daysInMonth[wxDateTime::IsLeapYear(year)][month];
381 }
382
383 // returns the time zone in the C sense, i.e. the difference UTC - local
384 // (in seconds)
385 static int GetTimeZone()
386 {
387 // set to true when the timezone is set
388 static bool s_timezoneSet = false;
389 static long gmtoffset = LONG_MAX; // invalid timezone
390
391 // ensure that the timezone variable is set by calling wxLocaltime_r
392 if ( !s_timezoneSet )
393 {
394 // just call wxLocaltime_r() instead of figuring out whether this
395 // system supports tzset(), _tzset() or something else
396 time_t t = 0;
397 struct tm tm;
398
399 wxLocaltime_r(&t, &tm);
400 s_timezoneSet = true;
401
402 #ifdef WX_GMTOFF_IN_TM
403 // note that GMT offset is the opposite of time zone and so to return
404 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
405 // cases we have to negate it
406 gmtoffset = -tm.tm_gmtoff;
407 #else // !WX_GMTOFF_IN_TM
408 gmtoffset = WX_TIMEZONE;
409 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
410 }
411
412 return (int)gmtoffset;
413 }
414
415 // return the integral part of the JDN for the midnight of the given date (to
416 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
417 // noon of the previous day)
418 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day,
419 wxDateTime::Month mon,
420 int year)
421 {
422 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
423
424 // check the date validity
425 wxASSERT_MSG(
426 (year > JDN_0_YEAR) ||
427 ((year == JDN_0_YEAR) && (mon > JDN_0_MONTH)) ||
428 ((year == JDN_0_YEAR) && (mon == JDN_0_MONTH) && (day >= JDN_0_DAY)),
429 _T("date out of range - can't convert to JDN")
430 );
431
432 // make the year positive to avoid problems with negative numbers division
433 year += 4800;
434
435 // months are counted from March here
436 int month;
437 if ( mon >= wxDateTime::Mar )
438 {
439 month = mon - 2;
440 }
441 else
442 {
443 month = mon + 10;
444 year--;
445 }
446
447 // now we can simply add all the contributions together
448 return ((year / 100) * DAYS_PER_400_YEARS) / 4
449 + ((year % 100) * DAYS_PER_4_YEARS) / 4
450 + (month * DAYS_PER_5_MONTHS + 2) / 5
451 + day
452 - JDN_OFFSET;
453 }
454
455 #ifdef HAVE_STRFTIME
456
457 // this function is a wrapper around strftime(3) adding error checking
458 static wxString CallStrftime(const wxString& format, const tm* tm)
459 {
460 wxChar buf[4096];
461 // Create temp wxString here to work around mingw/cygwin bug 1046059
462 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
463 wxString s;
464
465 if ( !wxStrftime(buf, WXSIZEOF(buf), format, tm) )
466 {
467 // if the format is valid, buffer must be too small?
468 wxFAIL_MSG(_T("strftime() failed"));
469
470 buf[0] = '\0';
471 }
472
473 s = buf;
474 return s;
475 }
476
477 #endif // HAVE_STRFTIME
478
479 // if year and/or month have invalid values, replace them with the current ones
480 static void ReplaceDefaultYearMonthWithCurrent(int *year,
481 wxDateTime::Month *month)
482 {
483 struct tm *tmNow = NULL;
484 struct tm tmstruct;
485
486 if ( *year == wxDateTime::Inv_Year )
487 {
488 tmNow = wxDateTime::GetTmNow(&tmstruct);
489
490 *year = 1900 + tmNow->tm_year;
491 }
492
493 if ( *month == wxDateTime::Inv_Month )
494 {
495 if ( !tmNow )
496 tmNow = wxDateTime::GetTmNow(&tmstruct);
497
498 *month = (wxDateTime::Month)tmNow->tm_mon;
499 }
500 }
501
502 // fll the struct tm with default values
503 static void InitTm(struct tm& tm)
504 {
505 // struct tm may have etxra fields (undocumented and with unportable
506 // names) which, nevertheless, must be set to 0
507 memset(&tm, 0, sizeof(struct tm));
508
509 tm.tm_mday = 1; // mday 0 is invalid
510 tm.tm_year = 76; // any valid year
511 tm.tm_isdst = -1; // auto determine
512 }
513
514 // ============================================================================
515 // implementation of wxDateTime
516 // ============================================================================
517
518 // ----------------------------------------------------------------------------
519 // struct Tm
520 // ----------------------------------------------------------------------------
521
522 wxDateTime::Tm::Tm()
523 {
524 year = (wxDateTime_t)wxDateTime::Inv_Year;
525 mon = wxDateTime::Inv_Month;
526 mday = 0;
527 hour = min = sec = msec = 0;
528 wday = wxDateTime::Inv_WeekDay;
529 }
530
531 wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
532 : m_tz(tz)
533 {
534 msec = 0;
535 sec = (wxDateTime::wxDateTime_t)tm.tm_sec;
536 min = (wxDateTime::wxDateTime_t)tm.tm_min;
537 hour = (wxDateTime::wxDateTime_t)tm.tm_hour;
538 mday = (wxDateTime::wxDateTime_t)tm.tm_mday;
539 mon = (wxDateTime::Month)tm.tm_mon;
540 year = 1900 + tm.tm_year;
541 wday = (wxDateTime::wxDateTime_t)tm.tm_wday;
542 yday = (wxDateTime::wxDateTime_t)tm.tm_yday;
543 }
544
545 bool wxDateTime::Tm::IsValid() const
546 {
547 // we allow for the leap seconds, although we don't use them (yet)
548 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
549 (mday <= GetNumOfDaysInMonth(year, mon)) &&
550 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
551 }
552
553 void wxDateTime::Tm::ComputeWeekDay()
554 {
555 // compute the week day from day/month/year: we use the dumbest algorithm
556 // possible: just compute our JDN and then use the (simple to derive)
557 // formula: weekday = (JDN + 1.5) % 7
558 wday = (wxDateTime::wxDateTime_t)((GetTruncatedJDN(mday, mon, year) + 2) % 7);
559 }
560
561 void wxDateTime::Tm::AddMonths(int monDiff)
562 {
563 // normalize the months field
564 while ( monDiff < -mon )
565 {
566 year--;
567
568 monDiff += MONTHS_IN_YEAR;
569 }
570
571 while ( monDiff + mon >= MONTHS_IN_YEAR )
572 {
573 year++;
574
575 monDiff -= MONTHS_IN_YEAR;
576 }
577
578 mon = (wxDateTime::Month)(mon + monDiff);
579
580 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
581
582 // NB: we don't check here that the resulting date is valid, this function
583 // is private and the caller must check it if needed
584 }
585
586 void wxDateTime::Tm::AddDays(int dayDiff)
587 {
588 // normalize the days field
589 while ( dayDiff + mday < 1 )
590 {
591 AddMonths(-1);
592
593 dayDiff += GetNumOfDaysInMonth(year, mon);
594 }
595
596 mday = (wxDateTime::wxDateTime_t)( mday + dayDiff );
597 while ( mday > GetNumOfDaysInMonth(year, mon) )
598 {
599 mday -= GetNumOfDaysInMonth(year, mon);
600
601 AddMonths(1);
602 }
603
604 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
605 _T("logic error") );
606 }
607
608 // ----------------------------------------------------------------------------
609 // class TimeZone
610 // ----------------------------------------------------------------------------
611
612 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
613 {
614 switch ( tz )
615 {
616 case wxDateTime::Local:
617 // get the offset from C RTL: it returns the difference GMT-local
618 // while we want to have the offset _from_ GMT, hence the '-'
619 m_offset = -GetTimeZone();
620 break;
621
622 case wxDateTime::GMT_12:
623 case wxDateTime::GMT_11:
624 case wxDateTime::GMT_10:
625 case wxDateTime::GMT_9:
626 case wxDateTime::GMT_8:
627 case wxDateTime::GMT_7:
628 case wxDateTime::GMT_6:
629 case wxDateTime::GMT_5:
630 case wxDateTime::GMT_4:
631 case wxDateTime::GMT_3:
632 case wxDateTime::GMT_2:
633 case wxDateTime::GMT_1:
634 m_offset = -3600*(wxDateTime::GMT0 - tz);
635 break;
636
637 case wxDateTime::GMT0:
638 case wxDateTime::GMT1:
639 case wxDateTime::GMT2:
640 case wxDateTime::GMT3:
641 case wxDateTime::GMT4:
642 case wxDateTime::GMT5:
643 case wxDateTime::GMT6:
644 case wxDateTime::GMT7:
645 case wxDateTime::GMT8:
646 case wxDateTime::GMT9:
647 case wxDateTime::GMT10:
648 case wxDateTime::GMT11:
649 case wxDateTime::GMT12:
650 case wxDateTime::GMT13:
651 m_offset = 3600*(tz - wxDateTime::GMT0);
652 break;
653
654 case wxDateTime::A_CST:
655 // Central Standard Time in use in Australia = UTC + 9.5
656 m_offset = 60l*(9*MIN_PER_HOUR + MIN_PER_HOUR/2);
657 break;
658
659 default:
660 wxFAIL_MSG( _T("unknown time zone") );
661 }
662 }
663
664 // ----------------------------------------------------------------------------
665 // static functions
666 // ----------------------------------------------------------------------------
667
668 /* static */
669 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
670 {
671 if ( year == Inv_Year )
672 year = GetCurrentYear();
673
674 if ( cal == Gregorian )
675 {
676 // in Gregorian calendar leap years are those divisible by 4 except
677 // those divisible by 100 unless they're also divisible by 400
678 // (in some countries, like Russia and Greece, additional corrections
679 // exist, but they won't manifest themselves until 2700)
680 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
681 }
682 else if ( cal == Julian )
683 {
684 // in Julian calendar the rule is simpler
685 return year % 4 == 0;
686 }
687 else
688 {
689 wxFAIL_MSG(_T("unknown calendar"));
690
691 return false;
692 }
693 }
694
695 /* static */
696 int wxDateTime::GetCentury(int year)
697 {
698 return year > 0 ? year / 100 : year / 100 - 1;
699 }
700
701 /* static */
702 int wxDateTime::ConvertYearToBC(int year)
703 {
704 // year 0 is BC 1
705 return year > 0 ? year : year - 1;
706 }
707
708 /* static */
709 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
710 {
711 switch ( cal )
712 {
713 case Gregorian:
714 return Now().GetYear();
715
716 case Julian:
717 wxFAIL_MSG(_T("TODO"));
718 break;
719
720 default:
721 wxFAIL_MSG(_T("unsupported calendar"));
722 break;
723 }
724
725 return Inv_Year;
726 }
727
728 /* static */
729 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
730 {
731 switch ( cal )
732 {
733 case Gregorian:
734 return Now().GetMonth();
735
736 case Julian:
737 wxFAIL_MSG(_T("TODO"));
738 break;
739
740 default:
741 wxFAIL_MSG(_T("unsupported calendar"));
742 break;
743 }
744
745 return Inv_Month;
746 }
747
748 /* static */
749 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
750 {
751 if ( year == Inv_Year )
752 {
753 // take the current year if none given
754 year = GetCurrentYear();
755 }
756
757 switch ( cal )
758 {
759 case Gregorian:
760 case Julian:
761 return IsLeapYear(year) ? 366 : 365;
762
763 default:
764 wxFAIL_MSG(_T("unsupported calendar"));
765 break;
766 }
767
768 return 0;
769 }
770
771 /* static */
772 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
773 int year,
774 wxDateTime::Calendar cal)
775 {
776 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
777
778 if ( cal == Gregorian || cal == Julian )
779 {
780 if ( year == Inv_Year )
781 {
782 // take the current year if none given
783 year = GetCurrentYear();
784 }
785
786 return GetNumOfDaysInMonth(year, month);
787 }
788 else
789 {
790 wxFAIL_MSG(_T("unsupported calendar"));
791
792 return 0;
793 }
794 }
795
796 /* static */
797 wxString wxDateTime::GetMonthName(wxDateTime::Month month,
798 wxDateTime::NameFlags flags)
799 {
800 wxCHECK_MSG( month != Inv_Month, wxEmptyString, _T("invalid month") );
801 #ifdef HAVE_STRFTIME
802 // notice that we must set all the fields to avoid confusing libc (GNU one
803 // gets confused to a crash if we don't do this)
804 tm tm;
805 InitTm(tm);
806 tm.tm_mon = month;
807
808 return CallStrftime(flags == Name_Abbr ? _T("%b") : _T("%B"), &tm);
809 #else // !HAVE_STRFTIME
810 wxString ret;
811 switch(month)
812 {
813 case Jan:
814 ret = (flags == Name_Abbr ? wxT("Jan"): wxT("January"));
815 break;
816 case Feb:
817 ret = (flags == Name_Abbr ? wxT("Feb"): wxT("Febuary"));
818 break;
819 case Mar:
820 ret = (flags == Name_Abbr ? wxT("Mar"): wxT("March"));
821 break;
822 case Apr:
823 ret = (flags == Name_Abbr ? wxT("Apr"): wxT("April"));
824 break;
825 case May:
826 ret = (flags == Name_Abbr ? wxT("May"): wxT("May"));
827 break;
828 case Jun:
829 ret = (flags == Name_Abbr ? wxT("Jun"): wxT("June"));
830 break;
831 case Jul:
832 ret = (flags == Name_Abbr ? wxT("Jul"): wxT("July"));
833 break;
834 case Aug:
835 ret = (flags == Name_Abbr ? wxT("Aug"): wxT("August"));
836 break;
837 case Sep:
838 ret = (flags == Name_Abbr ? wxT("Sep"): wxT("September"));
839 break;
840 case Oct:
841 ret = (flags == Name_Abbr ? wxT("Oct"): wxT("October"));
842 break;
843 case Nov:
844 ret = (flags == Name_Abbr ? wxT("Nov"): wxT("November"));
845 break;
846 case Dec:
847 ret = (flags == Name_Abbr ? wxT("Dec"): wxT("December"));
848 break;
849 }
850 return ret;
851 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
852 }
853
854 /* static */
855 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday,
856 wxDateTime::NameFlags flags)
857 {
858 wxCHECK_MSG( wday != Inv_WeekDay, wxEmptyString, _T("invalid weekday") );
859 #ifdef HAVE_STRFTIME
860 // take some arbitrary Sunday (but notice that the day should be such that
861 // after adding wday to it below we still have a valid date, e.g. don't
862 // take 28 here!)
863 tm tm;
864 InitTm(tm);
865 tm.tm_mday = 21;
866 tm.tm_mon = Nov;
867 tm.tm_year = 99;
868
869 // and offset it by the number of days needed to get the correct wday
870 tm.tm_mday += wday;
871
872 // call mktime() to normalize it...
873 (void)mktime(&tm);
874
875 // ... and call strftime()
876 return CallStrftime(flags == Name_Abbr ? _T("%a") : _T("%A"), &tm);
877 #else // !HAVE_STRFTIME
878 wxString ret;
879 switch(wday)
880 {
881 case Sun:
882 ret = (flags == Name_Abbr ? wxT("Sun") : wxT("Sunday"));
883 break;
884 case Mon:
885 ret = (flags == Name_Abbr ? wxT("Mon") : wxT("Monday"));
886 break;
887 case Tue:
888 ret = (flags == Name_Abbr ? wxT("Tue") : wxT("Tuesday"));
889 break;
890 case Wed:
891 ret = (flags == Name_Abbr ? wxT("Wed") : wxT("Wednesday"));
892 break;
893 case Thu:
894 ret = (flags == Name_Abbr ? wxT("Thu") : wxT("Thursday"));
895 break;
896 case Fri:
897 ret = (flags == Name_Abbr ? wxT("Fri") : wxT("Friday"));
898 break;
899 case Sat:
900 ret = (flags == Name_Abbr ? wxT("Sat") : wxT("Saturday"));
901 break;
902 }
903 return ret;
904 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
905 }
906
907 /* static */
908 void wxDateTime::GetAmPmStrings(wxString *am, wxString *pm)
909 {
910 tm tm;
911 InitTm(tm);
912 wxChar buffer[64];
913 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
914 // and causes an assertion failed if the buffer is to small (which is good) - OR -
915 // if strftime does not return anything because the format string is invalid - OR -
916 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
917 // wxDateTime::ParseTime will try several different formats to parse the time.
918 // As a result, GetAmPmStrings might get called, even if the current locale
919 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
920 // assert, even though it is a perfectly legal use.
921 if ( am )
922 {
923 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
924 *am = wxString(buffer);
925 else
926 *am = wxString();
927 }
928 if ( pm )
929 {
930 tm.tm_hour = 13;
931 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
932 *pm = wxString(buffer);
933 else
934 *pm = wxString();
935 }
936 }
937
938
939 // ----------------------------------------------------------------------------
940 // Country stuff: date calculations depend on the country (DST, work days,
941 // ...), so we need to know which rules to follow.
942 // ----------------------------------------------------------------------------
943
944 /* static */
945 wxDateTime::Country wxDateTime::GetCountry()
946 {
947 // TODO use LOCALE_ICOUNTRY setting under Win32
948 #ifndef __WXWINCE__
949 if ( ms_country == Country_Unknown )
950 {
951 // try to guess from the time zone name
952 time_t t = time(NULL);
953 struct tm tmstruct;
954 struct tm *tm = wxLocaltime_r(&t, &tmstruct);
955
956 wxString tz = CallStrftime(_T("%Z"), tm);
957 if ( tz == _T("WET") || tz == _T("WEST") )
958 {
959 ms_country = UK;
960 }
961 else if ( tz == _T("CET") || tz == _T("CEST") )
962 {
963 ms_country = Country_EEC;
964 }
965 else if ( tz == _T("MSK") || tz == _T("MSD") )
966 {
967 ms_country = Russia;
968 }
969 else if ( tz == _T("AST") || tz == _T("ADT") ||
970 tz == _T("EST") || tz == _T("EDT") ||
971 tz == _T("CST") || tz == _T("CDT") ||
972 tz == _T("MST") || tz == _T("MDT") ||
973 tz == _T("PST") || tz == _T("PDT") )
974 {
975 ms_country = USA;
976 }
977 else
978 {
979 // well, choose a default one
980 ms_country = USA;
981 }
982 }
983 #else // __WXWINCE__
984 ms_country = USA;
985 #endif // !__WXWINCE__/__WXWINCE__
986
987 return ms_country;
988 }
989
990 /* static */
991 void wxDateTime::SetCountry(wxDateTime::Country country)
992 {
993 ms_country = country;
994 }
995
996 /* static */
997 bool wxDateTime::IsWestEuropeanCountry(Country country)
998 {
999 if ( country == Country_Default )
1000 {
1001 country = GetCountry();
1002 }
1003
1004 return (Country_WesternEurope_Start <= country) &&
1005 (country <= Country_WesternEurope_End);
1006 }
1007
1008 // ----------------------------------------------------------------------------
1009 // DST calculations: we use 3 different rules for the West European countries,
1010 // USA and for the rest of the world. This is undoubtedly false for many
1011 // countries, but I lack the necessary info (and the time to gather it),
1012 // please add the other rules here!
1013 // ----------------------------------------------------------------------------
1014
1015 /* static */
1016 bool wxDateTime::IsDSTApplicable(int year, Country country)
1017 {
1018 if ( year == Inv_Year )
1019 {
1020 // take the current year if none given
1021 year = GetCurrentYear();
1022 }
1023
1024 if ( country == Country_Default )
1025 {
1026 country = GetCountry();
1027 }
1028
1029 switch ( country )
1030 {
1031 case USA:
1032 case UK:
1033 // DST was first observed in the US and UK during WWI, reused
1034 // during WWII and used again since 1966
1035 return year >= 1966 ||
1036 (year >= 1942 && year <= 1945) ||
1037 (year == 1918 || year == 1919);
1038
1039 default:
1040 // assume that it started after WWII
1041 return year > 1950;
1042 }
1043 }
1044
1045 /* static */
1046 wxDateTime wxDateTime::GetBeginDST(int year, Country country)
1047 {
1048 if ( year == Inv_Year )
1049 {
1050 // take the current year if none given
1051 year = GetCurrentYear();
1052 }
1053
1054 if ( country == Country_Default )
1055 {
1056 country = GetCountry();
1057 }
1058
1059 if ( !IsDSTApplicable(year, country) )
1060 {
1061 return wxInvalidDateTime;
1062 }
1063
1064 wxDateTime dt;
1065
1066 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1067 {
1068 // DST begins at 1 a.m. GMT on the last Sunday of March
1069 if ( !dt.SetToLastWeekDay(Sun, Mar, year) )
1070 {
1071 // weird...
1072 wxFAIL_MSG( _T("no last Sunday in March?") );
1073 }
1074
1075 dt += wxTimeSpan::Hours(1);
1076 }
1077 else switch ( country )
1078 {
1079 case USA:
1080 switch ( year )
1081 {
1082 case 1918:
1083 case 1919:
1084 // don't know for sure - assume it was in effect all year
1085
1086 case 1943:
1087 case 1944:
1088 case 1945:
1089 dt.Set(1, Jan, year);
1090 break;
1091
1092 case 1942:
1093 // DST was installed Feb 2, 1942 by the Congress
1094 dt.Set(2, Feb, year);
1095 break;
1096
1097 // Oil embargo changed the DST period in the US
1098 case 1974:
1099 dt.Set(6, Jan, 1974);
1100 break;
1101
1102 case 1975:
1103 dt.Set(23, Feb, 1975);
1104 break;
1105
1106 default:
1107 // before 1986, DST begun on the last Sunday of April, but
1108 // in 1986 Reagan changed it to begin at 2 a.m. of the
1109 // first Sunday in April
1110 if ( year < 1986 )
1111 {
1112 if ( !dt.SetToLastWeekDay(Sun, Apr, year) )
1113 {
1114 // weird...
1115 wxFAIL_MSG( _T("no first Sunday in April?") );
1116 }
1117 }
1118 else if ( year > 2006 )
1119 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1120 // Starting in 2007, daylight time begins in the United States on the
1121 // second Sunday in March and ends on the first Sunday in November
1122 {
1123 if ( !dt.SetToWeekDay(Sun, 2, Mar, year) )
1124 {
1125 // weird...
1126 wxFAIL_MSG( _T("no second Sunday in March?") );
1127 }
1128 }
1129 else
1130 {
1131 if ( !dt.SetToWeekDay(Sun, 1, Apr, year) )
1132 {
1133 // weird...
1134 wxFAIL_MSG( _T("no first Sunday in April?") );
1135 }
1136 }
1137
1138 dt += wxTimeSpan::Hours(2);
1139
1140 // TODO what about timezone??
1141 }
1142
1143 break;
1144
1145 default:
1146 // assume Mar 30 as the start of the DST for the rest of the world
1147 // - totally bogus, of course
1148 dt.Set(30, Mar, year);
1149 }
1150
1151 return dt;
1152 }
1153
1154 /* static */
1155 wxDateTime wxDateTime::GetEndDST(int year, Country country)
1156 {
1157 if ( year == Inv_Year )
1158 {
1159 // take the current year if none given
1160 year = GetCurrentYear();
1161 }
1162
1163 if ( country == Country_Default )
1164 {
1165 country = GetCountry();
1166 }
1167
1168 if ( !IsDSTApplicable(year, country) )
1169 {
1170 return wxInvalidDateTime;
1171 }
1172
1173 wxDateTime dt;
1174
1175 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1176 {
1177 // DST ends at 1 a.m. GMT on the last Sunday of October
1178 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1179 {
1180 // weirder and weirder...
1181 wxFAIL_MSG( _T("no last Sunday in October?") );
1182 }
1183
1184 dt += wxTimeSpan::Hours(1);
1185 }
1186 else switch ( country )
1187 {
1188 case USA:
1189 switch ( year )
1190 {
1191 case 1918:
1192 case 1919:
1193 // don't know for sure - assume it was in effect all year
1194
1195 case 1943:
1196 case 1944:
1197 dt.Set(31, Dec, year);
1198 break;
1199
1200 case 1945:
1201 // the time was reset after the end of the WWII
1202 dt.Set(30, Sep, year);
1203 break;
1204
1205 default: // default for switch (year)
1206 if ( year > 2006 )
1207 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1208 // Starting in 2007, daylight time begins in the United States on the
1209 // second Sunday in March and ends on the first Sunday in November
1210 {
1211 if ( !dt.SetToWeekDay(Sun, 1, Nov, year) )
1212 {
1213 // weird...
1214 wxFAIL_MSG( _T("no first Sunday in November?") );
1215 }
1216 }
1217 else
1218 // pre-2007
1219 // DST ends at 2 a.m. on the last Sunday of October
1220 {
1221 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1222 {
1223 // weirder and weirder...
1224 wxFAIL_MSG( _T("no last Sunday in October?") );
1225 }
1226 }
1227
1228 dt += wxTimeSpan::Hours(2);
1229
1230 // TODO: what about timezone??
1231 }
1232 break;
1233
1234 default: // default for switch (country)
1235 // assume October 26th as the end of the DST - totally bogus too
1236 dt.Set(26, Oct, year);
1237 }
1238
1239 return dt;
1240 }
1241
1242 // ----------------------------------------------------------------------------
1243 // constructors and assignment operators
1244 // ----------------------------------------------------------------------------
1245
1246 // return the current time with ms precision
1247 /* static */ wxDateTime wxDateTime::UNow()
1248 {
1249 return wxDateTime(wxGetLocalTimeMillis());
1250 }
1251
1252 // the values in the tm structure contain the local time
1253 wxDateTime& wxDateTime::Set(const struct tm& tm)
1254 {
1255 struct tm tm2(tm);
1256 time_t timet = mktime(&tm2);
1257
1258 if ( timet == (time_t)-1 )
1259 {
1260 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1261 // less than timezone - try to make it work for this case
1262 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
1263 {
1264 return Set((time_t)(
1265 GetTimeZone() +
1266 tm2.tm_hour * MIN_PER_HOUR * SEC_PER_MIN +
1267 tm2.tm_min * SEC_PER_MIN +
1268 tm2.tm_sec));
1269 }
1270
1271 wxFAIL_MSG( _T("mktime() failed") );
1272
1273 *this = wxInvalidDateTime;
1274
1275 return *this;
1276 }
1277 else
1278 {
1279 return Set(timet);
1280 }
1281 }
1282
1283 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
1284 wxDateTime_t minute,
1285 wxDateTime_t second,
1286 wxDateTime_t millisec)
1287 {
1288 // we allow seconds to be 61 to account for the leap seconds, even if we
1289 // don't use them really
1290 wxDATETIME_CHECK( hour < 24 &&
1291 second < 62 &&
1292 minute < 60 &&
1293 millisec < 1000,
1294 _T("Invalid time in wxDateTime::Set()") );
1295
1296 // get the current date from system
1297 struct tm tmstruct;
1298 struct tm *tm = GetTmNow(&tmstruct);
1299
1300 wxDATETIME_CHECK( tm, _T("wxLocaltime_r() failed") );
1301
1302 // make a copy so it isn't clobbered by the call to mktime() below
1303 struct tm tm1(*tm);
1304
1305 // adjust the time
1306 tm1.tm_hour = hour;
1307 tm1.tm_min = minute;
1308 tm1.tm_sec = second;
1309
1310 // and the DST in case it changes on this date
1311 struct tm tm2(tm1);
1312 mktime(&tm2);
1313 if ( tm2.tm_isdst != tm1.tm_isdst )
1314 tm1.tm_isdst = tm2.tm_isdst;
1315
1316 (void)Set(tm1);
1317
1318 // and finally adjust milliseconds
1319 return SetMillisecond(millisec);
1320 }
1321
1322 wxDateTime& wxDateTime::Set(wxDateTime_t day,
1323 Month month,
1324 int year,
1325 wxDateTime_t hour,
1326 wxDateTime_t minute,
1327 wxDateTime_t second,
1328 wxDateTime_t millisec)
1329 {
1330 wxDATETIME_CHECK( hour < 24 &&
1331 second < 62 &&
1332 minute < 60 &&
1333 millisec < 1000,
1334 _T("Invalid time in wxDateTime::Set()") );
1335
1336 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1337
1338 wxDATETIME_CHECK( (0 < day) && (day <= GetNumberOfDays(month, year)),
1339 _T("Invalid date in wxDateTime::Set()") );
1340
1341 // the range of time_t type (inclusive)
1342 static const int yearMinInRange = 1970;
1343 static const int yearMaxInRange = 2037;
1344
1345 // test only the year instead of testing for the exact end of the Unix
1346 // time_t range - it doesn't bring anything to do more precise checks
1347 if ( year >= yearMinInRange && year <= yearMaxInRange )
1348 {
1349 // use the standard library version if the date is in range - this is
1350 // probably more efficient than our code
1351 struct tm tm;
1352 tm.tm_year = year - 1900;
1353 tm.tm_mon = month;
1354 tm.tm_mday = day;
1355 tm.tm_hour = hour;
1356 tm.tm_min = minute;
1357 tm.tm_sec = second;
1358 tm.tm_isdst = -1; // mktime() will guess it
1359
1360 (void)Set(tm);
1361
1362 // and finally adjust milliseconds
1363 if (IsValid())
1364 SetMillisecond(millisec);
1365
1366 return *this;
1367 }
1368 else
1369 {
1370 // do time calculations ourselves: we want to calculate the number of
1371 // milliseconds between the given date and the epoch
1372
1373 // get the JDN for the midnight of this day
1374 m_time = GetTruncatedJDN(day, month, year);
1375 m_time -= EPOCH_JDN;
1376 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
1377
1378 // JDN corresponds to GMT, we take localtime
1379 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
1380 }
1381
1382 return *this;
1383 }
1384
1385 wxDateTime& wxDateTime::Set(double jdn)
1386 {
1387 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1388 // EPOCH_JDN + 0.5
1389 jdn -= EPOCH_JDN + 0.5;
1390
1391 m_time.Assign(jdn*MILLISECONDS_PER_DAY);
1392
1393 // JDNs always are in UTC, so we don't need any adjustments for time zone
1394
1395 return *this;
1396 }
1397
1398 wxDateTime& wxDateTime::ResetTime()
1399 {
1400 Tm tm = GetTm();
1401
1402 if ( tm.hour || tm.min || tm.sec || tm.msec )
1403 {
1404 tm.msec =
1405 tm.sec =
1406 tm.min =
1407 tm.hour = 0;
1408
1409 Set(tm);
1410 }
1411
1412 return *this;
1413 }
1414
1415 wxDateTime wxDateTime::GetDateOnly() const
1416 {
1417 Tm tm = GetTm();
1418 tm.msec =
1419 tm.sec =
1420 tm.min =
1421 tm.hour = 0;
1422 return wxDateTime(tm);
1423 }
1424
1425 // ----------------------------------------------------------------------------
1426 // DOS Date and Time Format functions
1427 // ----------------------------------------------------------------------------
1428 // the dos date and time value is an unsigned 32 bit value in the format:
1429 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1430 //
1431 // Y = year offset from 1980 (0-127)
1432 // M = month (1-12)
1433 // D = day of month (1-31)
1434 // h = hour (0-23)
1435 // m = minute (0-59)
1436 // s = bisecond (0-29) each bisecond indicates two seconds
1437 // ----------------------------------------------------------------------------
1438
1439 wxDateTime& wxDateTime::SetFromDOS(unsigned long ddt)
1440 {
1441 struct tm tm;
1442 InitTm(tm);
1443
1444 long year = ddt & 0xFE000000;
1445 year >>= 25;
1446 year += 80;
1447 tm.tm_year = year;
1448
1449 long month = ddt & 0x1E00000;
1450 month >>= 21;
1451 month -= 1;
1452 tm.tm_mon = month;
1453
1454 long day = ddt & 0x1F0000;
1455 day >>= 16;
1456 tm.tm_mday = day;
1457
1458 long hour = ddt & 0xF800;
1459 hour >>= 11;
1460 tm.tm_hour = hour;
1461
1462 long minute = ddt & 0x7E0;
1463 minute >>= 5;
1464 tm.tm_min = minute;
1465
1466 long second = ddt & 0x1F;
1467 tm.tm_sec = second * 2;
1468
1469 return Set(mktime(&tm));
1470 }
1471
1472 unsigned long wxDateTime::GetAsDOS() const
1473 {
1474 unsigned long ddt;
1475 time_t ticks = GetTicks();
1476 struct tm tmstruct;
1477 struct tm *tm = wxLocaltime_r(&ticks, &tmstruct);
1478 wxCHECK_MSG( tm, ULONG_MAX, _T("time can't be represented in DOS format") );
1479
1480 long year = tm->tm_year;
1481 year -= 80;
1482 year <<= 25;
1483
1484 long month = tm->tm_mon;
1485 month += 1;
1486 month <<= 21;
1487
1488 long day = tm->tm_mday;
1489 day <<= 16;
1490
1491 long hour = tm->tm_hour;
1492 hour <<= 11;
1493
1494 long minute = tm->tm_min;
1495 minute <<= 5;
1496
1497 long second = tm->tm_sec;
1498 second /= 2;
1499
1500 ddt = year | month | day | hour | minute | second;
1501 return ddt;
1502 }
1503
1504 // ----------------------------------------------------------------------------
1505 // time_t <-> broken down time conversions
1506 // ----------------------------------------------------------------------------
1507
1508 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
1509 {
1510 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1511
1512 time_t time = GetTicks();
1513 if ( time != (time_t)-1 )
1514 {
1515 // use C RTL functions
1516 struct tm tmstruct;
1517 tm *tm;
1518 if ( tz.GetOffset() == -GetTimeZone() )
1519 {
1520 // we are working with local time
1521 tm = wxLocaltime_r(&time, &tmstruct);
1522
1523 // should never happen
1524 wxCHECK_MSG( tm, Tm(), _T("wxLocaltime_r() failed") );
1525 }
1526 else
1527 {
1528 time += (time_t)tz.GetOffset();
1529 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1530 int time2 = (int) time;
1531 if ( time2 >= 0 )
1532 #else
1533 if ( time >= 0 )
1534 #endif
1535 {
1536 tm = wxGmtime_r(&time, &tmstruct);
1537
1538 // should never happen
1539 wxCHECK_MSG( tm, Tm(), _T("wxGmtime_r() failed") );
1540 }
1541 else
1542 {
1543 tm = (struct tm *)NULL;
1544 }
1545 }
1546
1547 if ( tm )
1548 {
1549 // adjust the milliseconds
1550 Tm tm2(*tm, tz);
1551 long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong();
1552 tm2.msec = (wxDateTime_t)(timeOnly % 1000);
1553 return tm2;
1554 }
1555 //else: use generic code below
1556 }
1557
1558 // remember the time and do the calculations with the date only - this
1559 // eliminates rounding errors of the floating point arithmetics
1560
1561 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
1562
1563 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1564
1565 // we want to always have positive time and timeMidnight to be really
1566 // the midnight before it
1567 if ( timeOnly < 0 )
1568 {
1569 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1570 }
1571
1572 timeMidnight -= timeOnly;
1573
1574 // calculate the Gregorian date from JDN for the midnight of our date:
1575 // this will yield day, month (in 1..12 range) and year
1576
1577 // actually, this is the JDN for the noon of the previous day
1578 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
1579
1580 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1581
1582 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
1583
1584 // calculate the century
1585 long temp = (jdn + JDN_OFFSET) * 4 - 1;
1586 long century = temp / DAYS_PER_400_YEARS;
1587
1588 // then the year and day of year (1 <= dayOfYear <= 366)
1589 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
1590 long year = (century * 100) + (temp / DAYS_PER_4_YEARS);
1591 long dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
1592
1593 // and finally the month and day of the month
1594 temp = dayOfYear * 5 - 3;
1595 long month = temp / DAYS_PER_5_MONTHS;
1596 long day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
1597
1598 // month is counted from March - convert to normal
1599 if ( month < 10 )
1600 {
1601 month += 3;
1602 }
1603 else
1604 {
1605 year += 1;
1606 month -= 9;
1607 }
1608
1609 // year is offset by 4800
1610 year -= 4800;
1611
1612 // check that the algorithm gave us something reasonable
1613 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
1614 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
1615
1616 // construct Tm from these values
1617 Tm tm;
1618 tm.year = (int)year;
1619 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1620 tm.mday = (wxDateTime_t)day;
1621 tm.msec = (wxDateTime_t)(timeOnly % 1000);
1622 timeOnly -= tm.msec;
1623 timeOnly /= 1000; // now we have time in seconds
1624
1625 tm.sec = (wxDateTime_t)(timeOnly % SEC_PER_MIN);
1626 timeOnly -= tm.sec;
1627 timeOnly /= SEC_PER_MIN; // now we have time in minutes
1628
1629 tm.min = (wxDateTime_t)(timeOnly % MIN_PER_HOUR);
1630 timeOnly -= tm.min;
1631
1632 tm.hour = (wxDateTime_t)(timeOnly / MIN_PER_HOUR);
1633
1634 return tm;
1635 }
1636
1637 wxDateTime& wxDateTime::SetYear(int year)
1638 {
1639 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1640
1641 Tm tm(GetTm());
1642 tm.year = year;
1643 Set(tm);
1644
1645 return *this;
1646 }
1647
1648 wxDateTime& wxDateTime::SetMonth(Month month)
1649 {
1650 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1651
1652 Tm tm(GetTm());
1653 tm.mon = month;
1654 Set(tm);
1655
1656 return *this;
1657 }
1658
1659 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
1660 {
1661 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1662
1663 Tm tm(GetTm());
1664 tm.mday = mday;
1665 Set(tm);
1666
1667 return *this;
1668 }
1669
1670 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
1671 {
1672 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1673
1674 Tm tm(GetTm());
1675 tm.hour = hour;
1676 Set(tm);
1677
1678 return *this;
1679 }
1680
1681 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
1682 {
1683 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1684
1685 Tm tm(GetTm());
1686 tm.min = min;
1687 Set(tm);
1688
1689 return *this;
1690 }
1691
1692 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
1693 {
1694 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1695
1696 Tm tm(GetTm());
1697 tm.sec = sec;
1698 Set(tm);
1699
1700 return *this;
1701 }
1702
1703 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
1704 {
1705 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1706
1707 // we don't need to use GetTm() for this one
1708 m_time -= m_time % 1000l;
1709 m_time += millisecond;
1710
1711 return *this;
1712 }
1713
1714 // ----------------------------------------------------------------------------
1715 // wxDateTime arithmetics
1716 // ----------------------------------------------------------------------------
1717
1718 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
1719 {
1720 Tm tm(GetTm());
1721
1722 tm.year += diff.GetYears();
1723 tm.AddMonths(diff.GetMonths());
1724
1725 // check that the resulting date is valid
1726 if ( tm.mday > GetNumOfDaysInMonth(tm.year, tm.mon) )
1727 {
1728 // We suppose that when adding one month to Jan 31 we want to get Feb
1729 // 28 (or 29), i.e. adding a month to the last day of the month should
1730 // give the last day of the next month which is quite logical.
1731 //
1732 // Unfortunately, there is no logic way to understand what should
1733 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1734 // We make it Feb 28 (last day too), but it is highly questionable.
1735 tm.mday = GetNumOfDaysInMonth(tm.year, tm.mon);
1736 }
1737
1738 tm.AddDays(diff.GetTotalDays());
1739
1740 Set(tm);
1741
1742 wxASSERT_MSG( IsSameTime(tm),
1743 _T("Add(wxDateSpan) shouldn't modify time") );
1744
1745 return *this;
1746 }
1747
1748 // ----------------------------------------------------------------------------
1749 // Weekday and monthday stuff
1750 // ----------------------------------------------------------------------------
1751
1752 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1753 static inline int ConvertWeekDayToMondayBase(int wd)
1754 {
1755 return wd == wxDateTime::Sun ? 6 : wd - 1;
1756 }
1757
1758 /* static */
1759 wxDateTime
1760 wxDateTime::SetToWeekOfYear(int year, wxDateTime_t numWeek, WeekDay wd)
1761 {
1762 wxASSERT_MSG( numWeek > 0,
1763 _T("invalid week number: weeks are counted from 1") );
1764
1765 // Jan 4 always lies in the 1st week of the year
1766 wxDateTime dt(4, Jan, year);
1767 dt.SetToWeekDayInSameWeek(wd);
1768 dt += wxDateSpan::Weeks(numWeek - 1);
1769
1770 return dt;
1771 }
1772
1773 #if WXWIN_COMPATIBILITY_2_6
1774 // use a separate function to avoid warnings about using deprecated
1775 // SetToTheWeek in GetWeek below
1776 static wxDateTime
1777 SetToTheWeek(int year,
1778 wxDateTime::wxDateTime_t numWeek,
1779 wxDateTime::WeekDay weekday,
1780 wxDateTime::WeekFlags flags)
1781 {
1782 // Jan 4 always lies in the 1st week of the year
1783 wxDateTime dt(4, wxDateTime::Jan, year);
1784 dt.SetToWeekDayInSameWeek(weekday, flags);
1785 dt += wxDateSpan::Weeks(numWeek - 1);
1786
1787 return dt;
1788 }
1789
1790 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek,
1791 WeekDay weekday,
1792 WeekFlags flags)
1793 {
1794 int year = GetYear();
1795 *this = ::SetToTheWeek(year, numWeek, weekday, flags);
1796 if ( GetYear() != year )
1797 {
1798 // oops... numWeek was too big
1799 return false;
1800 }
1801
1802 return true;
1803 }
1804
1805 wxDateTime wxDateTime::GetWeek(wxDateTime_t numWeek,
1806 WeekDay weekday,
1807 WeekFlags flags) const
1808 {
1809 return ::SetToTheWeek(GetYear(), numWeek, weekday, flags);
1810 }
1811 #endif // WXWIN_COMPATIBILITY_2_6
1812
1813 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
1814 int year)
1815 {
1816 // take the current month/year if none specified
1817 if ( year == Inv_Year )
1818 year = GetYear();
1819 if ( month == Inv_Month )
1820 month = GetMonth();
1821
1822 return Set(GetNumOfDaysInMonth(year, month), month, year);
1823 }
1824
1825 wxDateTime& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday, WeekFlags flags)
1826 {
1827 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1828
1829 int wdayDst = weekday,
1830 wdayThis = GetWeekDay();
1831 if ( wdayDst == wdayThis )
1832 {
1833 // nothing to do
1834 return *this;
1835 }
1836
1837 if ( flags == Default_First )
1838 {
1839 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1840 }
1841
1842 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1843 // is the first day in the week, but breaks down for Monday_First case so
1844 // we adjust the week days in this case
1845 if ( flags == Monday_First )
1846 {
1847 if ( wdayThis == Sun )
1848 wdayThis += 7;
1849 if ( wdayDst == Sun )
1850 wdayDst += 7;
1851 }
1852 //else: Sunday_First, nothing to do
1853
1854 // go forward or back in time to the day we want
1855 if ( wdayDst < wdayThis )
1856 {
1857 return Subtract(wxDateSpan::Days(wdayThis - wdayDst));
1858 }
1859 else // weekday > wdayThis
1860 {
1861 return Add(wxDateSpan::Days(wdayDst - wdayThis));
1862 }
1863 }
1864
1865 wxDateTime& wxDateTime::SetToNextWeekDay(WeekDay weekday)
1866 {
1867 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1868
1869 int diff;
1870 WeekDay wdayThis = GetWeekDay();
1871 if ( weekday == wdayThis )
1872 {
1873 // nothing to do
1874 return *this;
1875 }
1876 else if ( weekday < wdayThis )
1877 {
1878 // need to advance a week
1879 diff = 7 - (wdayThis - weekday);
1880 }
1881 else // weekday > wdayThis
1882 {
1883 diff = weekday - wdayThis;
1884 }
1885
1886 return Add(wxDateSpan::Days(diff));
1887 }
1888
1889 wxDateTime& wxDateTime::SetToPrevWeekDay(WeekDay weekday)
1890 {
1891 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1892
1893 int diff;
1894 WeekDay wdayThis = GetWeekDay();
1895 if ( weekday == wdayThis )
1896 {
1897 // nothing to do
1898 return *this;
1899 }
1900 else if ( weekday > wdayThis )
1901 {
1902 // need to go to previous week
1903 diff = 7 - (weekday - wdayThis);
1904 }
1905 else // weekday < wdayThis
1906 {
1907 diff = wdayThis - weekday;
1908 }
1909
1910 return Subtract(wxDateSpan::Days(diff));
1911 }
1912
1913 bool wxDateTime::SetToWeekDay(WeekDay weekday,
1914 int n,
1915 Month month,
1916 int year)
1917 {
1918 wxCHECK_MSG( weekday != Inv_WeekDay, false, _T("invalid weekday") );
1919
1920 // we don't check explicitly that -5 <= n <= 5 because we will return false
1921 // anyhow in such case - but may be should still give an assert for it?
1922
1923 // take the current month/year if none specified
1924 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1925
1926 wxDateTime dt;
1927
1928 // TODO this probably could be optimised somehow...
1929
1930 if ( n > 0 )
1931 {
1932 // get the first day of the month
1933 dt.Set(1, month, year);
1934
1935 // get its wday
1936 WeekDay wdayFirst = dt.GetWeekDay();
1937
1938 // go to the first weekday of the month
1939 int diff = weekday - wdayFirst;
1940 if ( diff < 0 )
1941 diff += 7;
1942
1943 // add advance n-1 weeks more
1944 diff += 7*(n - 1);
1945
1946 dt += wxDateSpan::Days(diff);
1947 }
1948 else // count from the end of the month
1949 {
1950 // get the last day of the month
1951 dt.SetToLastMonthDay(month, year);
1952
1953 // get its wday
1954 WeekDay wdayLast = dt.GetWeekDay();
1955
1956 // go to the last weekday of the month
1957 int diff = wdayLast - weekday;
1958 if ( diff < 0 )
1959 diff += 7;
1960
1961 // and rewind n-1 weeks from there
1962 diff += 7*(-n - 1);
1963
1964 dt -= wxDateSpan::Days(diff);
1965 }
1966
1967 // check that it is still in the same month
1968 if ( dt.GetMonth() == month )
1969 {
1970 *this = dt;
1971
1972 return true;
1973 }
1974 else
1975 {
1976 // no such day in this month
1977 return false;
1978 }
1979 }
1980
1981 static inline
1982 wxDateTime::wxDateTime_t GetDayOfYearFromTm(const wxDateTime::Tm& tm)
1983 {
1984 return (wxDateTime::wxDateTime_t)(gs_cumulatedDays[wxDateTime::IsLeapYear(tm.year)][tm.mon] + tm.mday);
1985 }
1986
1987 wxDateTime::wxDateTime_t wxDateTime::GetDayOfYear(const TimeZone& tz) const
1988 {
1989 return GetDayOfYearFromTm(GetTm(tz));
1990 }
1991
1992 wxDateTime::wxDateTime_t
1993 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags, const TimeZone& tz) const
1994 {
1995 if ( flags == Default_First )
1996 {
1997 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1998 }
1999
2000 Tm tm(GetTm(tz));
2001 wxDateTime_t nDayInYear = GetDayOfYearFromTm(tm);
2002
2003 int wdTarget = GetWeekDay(tz);
2004 int wdYearStart = wxDateTime(1, Jan, GetYear()).GetWeekDay();
2005 int week;
2006 if ( flags == Sunday_First )
2007 {
2008 // FIXME: First week is not calculated correctly.
2009 week = (nDayInYear - wdTarget + 7) / 7;
2010 if ( wdYearStart == Wed || wdYearStart == Thu )
2011 week++;
2012 }
2013 else // week starts with monday
2014 {
2015 // adjust the weekdays to non-US style.
2016 wdYearStart = ConvertWeekDayToMondayBase(wdYearStart);
2017 wdTarget = ConvertWeekDayToMondayBase(wdTarget);
2018
2019 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2020 //
2021 // Week 01 of a year is per definition the first week that has the
2022 // Thursday in this year, which is equivalent to the week that
2023 // contains the fourth day of January. In other words, the first
2024 // week of a new year is the week that has the majority of its
2025 // days in the new year. Week 01 might also contain days from the
2026 // previous year and the week before week 01 of a year is the last
2027 // week (52 or 53) of the previous year even if it contains days
2028 // from the new year. A week starts with Monday (day 1) and ends
2029 // with Sunday (day 7).
2030 //
2031
2032 // if Jan 1 is Thursday or less, it is in the first week of this year
2033 if ( wdYearStart < 4 )
2034 {
2035 // count the number of entire weeks between Jan 1 and this date
2036 week = (nDayInYear + wdYearStart + 6 - wdTarget)/7;
2037
2038 // be careful to check for overflow in the next year
2039 if ( week == 53 && tm.mday - wdTarget > 28 )
2040 week = 1;
2041 }
2042 else // Jan 1 is in the last week of the previous year
2043 {
2044 // check if we happen to be at the last week of previous year:
2045 if ( tm.mon == Jan && tm.mday < 8 - wdYearStart )
2046 week = wxDateTime(31, Dec, GetYear()-1).GetWeekOfYear();
2047 else
2048 week = (nDayInYear + wdYearStart - 1 - wdTarget)/7;
2049 }
2050 }
2051
2052 return (wxDateTime::wxDateTime_t)week;
2053 }
2054
2055 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags,
2056 const TimeZone& tz) const
2057 {
2058 Tm tm = GetTm(tz);
2059 wxDateTime dtMonthStart = wxDateTime(1, tm.mon, tm.year);
2060 int nWeek = GetWeekOfYear(flags) - dtMonthStart.GetWeekOfYear(flags) + 1;
2061 if ( nWeek < 0 )
2062 {
2063 // this may happen for January when Jan, 1 is the last week of the
2064 // previous year
2065 nWeek += IsLeapYear(tm.year - 1) ? 53 : 52;
2066 }
2067
2068 return (wxDateTime::wxDateTime_t)nWeek;
2069 }
2070
2071 wxDateTime& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday)
2072 {
2073 int year = GetYear();
2074 wxDATETIME_CHECK( (0 < yday) && (yday <= GetNumberOfDays(year)),
2075 _T("invalid year day") );
2076
2077 bool isLeap = IsLeapYear(year);
2078 for ( Month mon = Jan; mon < Inv_Month; wxNextMonth(mon) )
2079 {
2080 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2081 // don't need it neither - because of the CHECK above we know that
2082 // yday lies in December then
2083 if ( (mon == Dec) || (yday <= gs_cumulatedDays[isLeap][mon + 1]) )
2084 {
2085 Set((wxDateTime::wxDateTime_t)(yday - gs_cumulatedDays[isLeap][mon]), mon, year);
2086
2087 break;
2088 }
2089 }
2090
2091 return *this;
2092 }
2093
2094 // ----------------------------------------------------------------------------
2095 // Julian day number conversion and related stuff
2096 // ----------------------------------------------------------------------------
2097
2098 double wxDateTime::GetJulianDayNumber() const
2099 {
2100 return m_time.ToDouble() / MILLISECONDS_PER_DAY + EPOCH_JDN + 0.5;
2101 }
2102
2103 double wxDateTime::GetRataDie() const
2104 {
2105 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2106 return GetJulianDayNumber() - 1721119.5 - 306;
2107 }
2108
2109 // ----------------------------------------------------------------------------
2110 // timezone and DST stuff
2111 // ----------------------------------------------------------------------------
2112
2113 int wxDateTime::IsDST(wxDateTime::Country country) const
2114 {
2115 wxCHECK_MSG( country == Country_Default, -1,
2116 _T("country support not implemented") );
2117
2118 // use the C RTL for the dates in the standard range
2119 time_t timet = GetTicks();
2120 if ( timet != (time_t)-1 )
2121 {
2122 struct tm tmstruct;
2123 tm *tm = wxLocaltime_r(&timet, &tmstruct);
2124
2125 wxCHECK_MSG( tm, -1, _T("wxLocaltime_r() failed") );
2126
2127 return tm->tm_isdst;
2128 }
2129 else
2130 {
2131 int year = GetYear();
2132
2133 if ( !IsDSTApplicable(year, country) )
2134 {
2135 // no DST time in this year in this country
2136 return -1;
2137 }
2138
2139 return IsBetween(GetBeginDST(year, country), GetEndDST(year, country));
2140 }
2141 }
2142
2143 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz, bool noDST)
2144 {
2145 long secDiff = GetTimeZone() + tz.GetOffset();
2146
2147 // we need to know whether DST is or not in effect for this date unless
2148 // the test disabled by the caller
2149 if ( !noDST && (IsDST() == 1) )
2150 {
2151 // FIXME we assume that the DST is always shifted by 1 hour
2152 secDiff -= 3600;
2153 }
2154
2155 return Add(wxTimeSpan::Seconds(secDiff));
2156 }
2157
2158 wxDateTime& wxDateTime::MakeFromTimezone(const TimeZone& tz, bool noDST)
2159 {
2160 long secDiff = GetTimeZone() + tz.GetOffset();
2161
2162 // we need to know whether DST is or not in effect for this date unless
2163 // the test disabled by the caller
2164 if ( !noDST && (IsDST() == 1) )
2165 {
2166 // FIXME we assume that the DST is always shifted by 1 hour
2167 secDiff -= 3600;
2168 }
2169
2170 return Subtract(wxTimeSpan::Seconds(secDiff));
2171 }
2172
2173 // ============================================================================
2174 // wxDateTimeHolidayAuthority and related classes
2175 // ============================================================================
2176
2177 #include "wx/arrimpl.cpp"
2178
2179 WX_DEFINE_OBJARRAY(wxDateTimeArray)
2180
2181 static int wxCMPFUNC_CONV
2182 wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
2183 {
2184 wxDateTime dt1 = **first,
2185 dt2 = **second;
2186
2187 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
2188 }
2189
2190 // ----------------------------------------------------------------------------
2191 // wxDateTimeHolidayAuthority
2192 // ----------------------------------------------------------------------------
2193
2194 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
2195
2196 /* static */
2197 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
2198 {
2199 size_t count = ms_authorities.size();
2200 for ( size_t n = 0; n < count; n++ )
2201 {
2202 if ( ms_authorities[n]->DoIsHoliday(dt) )
2203 {
2204 return true;
2205 }
2206 }
2207
2208 return false;
2209 }
2210
2211 /* static */
2212 size_t
2213 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
2214 const wxDateTime& dtEnd,
2215 wxDateTimeArray& holidays)
2216 {
2217 wxDateTimeArray hol;
2218
2219 holidays.Clear();
2220
2221 const size_t countAuth = ms_authorities.size();
2222 for ( size_t nAuth = 0; nAuth < countAuth; nAuth++ )
2223 {
2224 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
2225
2226 WX_APPEND_ARRAY(holidays, hol);
2227 }
2228
2229 holidays.Sort(wxDateTimeCompareFunc);
2230
2231 return holidays.size();
2232 }
2233
2234 /* static */
2235 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2236 {
2237 WX_CLEAR_ARRAY(ms_authorities);
2238 }
2239
2240 /* static */
2241 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
2242 {
2243 ms_authorities.push_back(auth);
2244 }
2245
2246 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2247 {
2248 // required here for Darwin
2249 }
2250
2251 // ----------------------------------------------------------------------------
2252 // wxDateTimeWorkDays
2253 // ----------------------------------------------------------------------------
2254
2255 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
2256 {
2257 wxDateTime::WeekDay wd = dt.GetWeekDay();
2258
2259 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
2260 }
2261
2262 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
2263 const wxDateTime& dtEnd,
2264 wxDateTimeArray& holidays) const
2265 {
2266 if ( dtStart > dtEnd )
2267 {
2268 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
2269
2270 return 0u;
2271 }
2272
2273 holidays.Empty();
2274
2275 // instead of checking all days, start with the first Sat after dtStart and
2276 // end with the last Sun before dtEnd
2277 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
2278 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
2279 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
2280 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
2281 dt;
2282
2283 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
2284 {
2285 holidays.Add(dt);
2286 }
2287
2288 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
2289 {
2290 holidays.Add(dt);
2291 }
2292
2293 return holidays.GetCount();
2294 }
2295
2296 // ============================================================================
2297 // other helper functions
2298 // ============================================================================
2299
2300 // ----------------------------------------------------------------------------
2301 // iteration helpers: can be used to write a for loop over enum variable like
2302 // this:
2303 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2304 // ----------------------------------------------------------------------------
2305
2306 WXDLLIMPEXP_BASE void wxNextMonth(wxDateTime::Month& m)
2307 {
2308 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2309
2310 // no wrapping or the for loop above would never end!
2311 m = (wxDateTime::Month)(m + 1);
2312 }
2313
2314 WXDLLIMPEXP_BASE void wxPrevMonth(wxDateTime::Month& m)
2315 {
2316 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2317
2318 m = m == wxDateTime::Jan ? wxDateTime::Inv_Month
2319 : (wxDateTime::Month)(m - 1);
2320 }
2321
2322 WXDLLIMPEXP_BASE void wxNextWDay(wxDateTime::WeekDay& wd)
2323 {
2324 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2325
2326 // no wrapping or the for loop above would never end!
2327 wd = (wxDateTime::WeekDay)(wd + 1);
2328 }
2329
2330 WXDLLIMPEXP_BASE void wxPrevWDay(wxDateTime::WeekDay& wd)
2331 {
2332 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2333
2334 wd = wd == wxDateTime::Sun ? wxDateTime::Inv_WeekDay
2335 : (wxDateTime::WeekDay)(wd - 1);
2336 }
2337
2338 #ifdef __WXMSW__
2339
2340 wxDateTime& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME& st)
2341 {
2342 return Set(st.wDay,
2343 static_cast<wxDateTime::Month>(wxDateTime::Jan + st.wMonth - 1),
2344 st.wYear,
2345 0, 0, 0);
2346 }
2347
2348 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME* st) const
2349 {
2350 const wxDateTime::Tm tm(GetTm());
2351
2352 st->wYear = (WXWORD)tm.year;
2353 st->wMonth = (WXWORD)(tm.mon - wxDateTime::Jan + 1);
2354 st->wDay = tm.mday;
2355
2356 st->wDayOfWeek =
2357 st->wHour =
2358 st->wMinute =
2359 st->wSecond =
2360 st->wMilliseconds = 0;
2361 }
2362 #endif // __WXMSW__
2363
2364 #endif // wxUSE_DATETIME