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