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