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