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