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