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