no real changes: split the huge datetime.cpp in two parts: one dedicated to code...
[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 #ifdef HAVE_STRPTIME
505
506 #if wxUSE_UNIX && !defined(HAVE_STRPTIME_DECL)
507 // configure detected that we had strptime() but not its declaration,
508 // provide it ourselves
509 extern "C" char *strptime(const char *, const char *, struct tm *);
510 #endif
511
512 // Unicode-friendly strptime() wrapper
513 static const wxStringCharType *
514 CallStrptime(const wxStringCharType *input, const char *fmt, tm *tm)
515 {
516 // the problem here is that strptime() returns pointer into the string we
517 // passed to it while we're really interested in the pointer into the
518 // original, Unicode, string so we try to transform the pointer back
519 #if wxUSE_UNICODE_WCHAR
520 wxCharBuffer inputMB(wxConvertWX2MB(input));
521 #else // ASCII
522 const char * const inputMB = input;
523 #endif // Unicode/Ascii
524
525 const char *result = strptime(inputMB, fmt, tm);
526 if ( !result )
527 return NULL;
528
529 #if wxUSE_UNICODE_WCHAR
530 // FIXME: this is wrong in presence of surrogates &c
531 return input + (result - inputMB.data());
532 #else // ASCII
533 return result;
534 #endif // Unicode/Ascii
535 }
536
537 #endif // HAVE_STRPTIME
538
539 // if year and/or month have invalid values, replace them with the current ones
540 static void ReplaceDefaultYearMonthWithCurrent(int *year,
541 wxDateTime::Month *month)
542 {
543 struct tm *tmNow = NULL;
544 struct tm tmstruct;
545
546 if ( *year == wxDateTime::Inv_Year )
547 {
548 tmNow = wxDateTime::GetTmNow(&tmstruct);
549
550 *year = 1900 + tmNow->tm_year;
551 }
552
553 if ( *month == wxDateTime::Inv_Month )
554 {
555 if ( !tmNow )
556 tmNow = wxDateTime::GetTmNow(&tmstruct);
557
558 *month = (wxDateTime::Month)tmNow->tm_mon;
559 }
560 }
561
562 // fll the struct tm with default values
563 static void InitTm(struct tm& tm)
564 {
565 // struct tm may have etxra fields (undocumented and with unportable
566 // names) which, nevertheless, must be set to 0
567 memset(&tm, 0, sizeof(struct tm));
568
569 tm.tm_mday = 1; // mday 0 is invalid
570 tm.tm_year = 76; // any valid year
571 tm.tm_isdst = -1; // auto determine
572 }
573
574 // parsing helpers
575 // ---------------
576
577 // return the month if the string is a month name or Inv_Month otherwise
578 static wxDateTime::Month GetMonthFromName(const wxString& name, int flags)
579 {
580 wxDateTime::Month mon;
581 for ( mon = wxDateTime::Jan; mon < wxDateTime::Inv_Month; wxNextMonth(mon) )
582 {
583 // case-insensitive comparison either one of or with both abbreviated
584 // and not versions
585 if ( flags & wxDateTime::Name_Full )
586 {
587 if ( name.CmpNoCase(wxDateTime::
588 GetMonthName(mon, wxDateTime::Name_Full)) == 0 )
589 {
590 break;
591 }
592 }
593
594 if ( flags & wxDateTime::Name_Abbr )
595 {
596 if ( name.CmpNoCase(wxDateTime::
597 GetMonthName(mon, wxDateTime::Name_Abbr)) == 0 )
598 {
599 break;
600 }
601 }
602 }
603
604 return mon;
605 }
606
607 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
608 static wxDateTime::WeekDay GetWeekDayFromName(const wxString& name, int flags)
609 {
610 wxDateTime::WeekDay wd;
611 for ( wd = wxDateTime::Sun; wd < wxDateTime::Inv_WeekDay; wxNextWDay(wd) )
612 {
613 // case-insensitive comparison either one of or with both abbreviated
614 // and not versions
615 if ( flags & wxDateTime::Name_Full )
616 {
617 if ( name.CmpNoCase(wxDateTime::
618 GetWeekDayName(wd, wxDateTime::Name_Full)) == 0 )
619 {
620 break;
621 }
622 }
623
624 if ( flags & wxDateTime::Name_Abbr )
625 {
626 if ( name.CmpNoCase(wxDateTime::
627 GetWeekDayName(wd, wxDateTime::Name_Abbr)) == 0 )
628 {
629 break;
630 }
631 }
632 }
633
634 return wd;
635 }
636
637 /* static */
638 struct tm *wxDateTime::GetTmNow(struct tm *tmstruct)
639 {
640 time_t t = GetTimeNow();
641 return wxLocaltime_r(&t, tmstruct);
642 }
643
644 // scans all digits (but no more than len) and returns the resulting number
645 static bool GetNumericToken(size_t len,
646 const wxStringCharType*& p,
647 unsigned long *number)
648 {
649 size_t n = 1;
650 wxString s;
651 while ( wxIsdigit(*p) )
652 {
653 s += *p++;
654
655 if ( len && ++n > len )
656 break;
657 }
658
659 return !s.empty() && s.ToULong(number);
660 }
661
662 // scans all alphabetic characters and returns the resulting string
663 static wxString GetAlphaToken(const wxStringCharType*& p)
664 {
665 wxString s;
666 while ( wxIsalpha(*p) )
667 {
668 s += *p++;
669 }
670
671 return s;
672 }
673
674 // ============================================================================
675 // implementation of wxDateTime
676 // ============================================================================
677
678 // ----------------------------------------------------------------------------
679 // struct Tm
680 // ----------------------------------------------------------------------------
681
682 wxDateTime::Tm::Tm()
683 {
684 year = (wxDateTime_t)wxDateTime::Inv_Year;
685 mon = wxDateTime::Inv_Month;
686 mday = 0;
687 hour = min = sec = msec = 0;
688 wday = wxDateTime::Inv_WeekDay;
689 }
690
691 wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
692 : m_tz(tz)
693 {
694 msec = 0;
695 sec = (wxDateTime::wxDateTime_t)tm.tm_sec;
696 min = (wxDateTime::wxDateTime_t)tm.tm_min;
697 hour = (wxDateTime::wxDateTime_t)tm.tm_hour;
698 mday = (wxDateTime::wxDateTime_t)tm.tm_mday;
699 mon = (wxDateTime::Month)tm.tm_mon;
700 year = 1900 + tm.tm_year;
701 wday = (wxDateTime::wxDateTime_t)tm.tm_wday;
702 yday = (wxDateTime::wxDateTime_t)tm.tm_yday;
703 }
704
705 bool wxDateTime::Tm::IsValid() const
706 {
707 // we allow for the leap seconds, although we don't use them (yet)
708 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
709 (mday <= GetNumOfDaysInMonth(year, mon)) &&
710 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
711 }
712
713 void wxDateTime::Tm::ComputeWeekDay()
714 {
715 // compute the week day from day/month/year: we use the dumbest algorithm
716 // possible: just compute our JDN and then use the (simple to derive)
717 // formula: weekday = (JDN + 1.5) % 7
718 wday = (wxDateTime::wxDateTime_t)((GetTruncatedJDN(mday, mon, year) + 2) % 7);
719 }
720
721 void wxDateTime::Tm::AddMonths(int monDiff)
722 {
723 // normalize the months field
724 while ( monDiff < -mon )
725 {
726 year--;
727
728 monDiff += MONTHS_IN_YEAR;
729 }
730
731 while ( monDiff + mon >= MONTHS_IN_YEAR )
732 {
733 year++;
734
735 monDiff -= MONTHS_IN_YEAR;
736 }
737
738 mon = (wxDateTime::Month)(mon + monDiff);
739
740 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
741
742 // NB: we don't check here that the resulting date is valid, this function
743 // is private and the caller must check it if needed
744 }
745
746 void wxDateTime::Tm::AddDays(int dayDiff)
747 {
748 // normalize the days field
749 while ( dayDiff + mday < 1 )
750 {
751 AddMonths(-1);
752
753 dayDiff += GetNumOfDaysInMonth(year, mon);
754 }
755
756 mday = (wxDateTime::wxDateTime_t)( mday + dayDiff );
757 while ( mday > GetNumOfDaysInMonth(year, mon) )
758 {
759 mday -= GetNumOfDaysInMonth(year, mon);
760
761 AddMonths(1);
762 }
763
764 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
765 _T("logic error") );
766 }
767
768 // ----------------------------------------------------------------------------
769 // class TimeZone
770 // ----------------------------------------------------------------------------
771
772 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
773 {
774 switch ( tz )
775 {
776 case wxDateTime::Local:
777 // get the offset from C RTL: it returns the difference GMT-local
778 // while we want to have the offset _from_ GMT, hence the '-'
779 m_offset = -GetTimeZone();
780 break;
781
782 case wxDateTime::GMT_12:
783 case wxDateTime::GMT_11:
784 case wxDateTime::GMT_10:
785 case wxDateTime::GMT_9:
786 case wxDateTime::GMT_8:
787 case wxDateTime::GMT_7:
788 case wxDateTime::GMT_6:
789 case wxDateTime::GMT_5:
790 case wxDateTime::GMT_4:
791 case wxDateTime::GMT_3:
792 case wxDateTime::GMT_2:
793 case wxDateTime::GMT_1:
794 m_offset = -3600*(wxDateTime::GMT0 - tz);
795 break;
796
797 case wxDateTime::GMT0:
798 case wxDateTime::GMT1:
799 case wxDateTime::GMT2:
800 case wxDateTime::GMT3:
801 case wxDateTime::GMT4:
802 case wxDateTime::GMT5:
803 case wxDateTime::GMT6:
804 case wxDateTime::GMT7:
805 case wxDateTime::GMT8:
806 case wxDateTime::GMT9:
807 case wxDateTime::GMT10:
808 case wxDateTime::GMT11:
809 case wxDateTime::GMT12:
810 case wxDateTime::GMT13:
811 m_offset = 3600*(tz - wxDateTime::GMT0);
812 break;
813
814 case wxDateTime::A_CST:
815 // Central Standard Time in use in Australia = UTC + 9.5
816 m_offset = 60l*(9*MIN_PER_HOUR + MIN_PER_HOUR/2);
817 break;
818
819 default:
820 wxFAIL_MSG( _T("unknown time zone") );
821 }
822 }
823
824 // ----------------------------------------------------------------------------
825 // static functions
826 // ----------------------------------------------------------------------------
827
828 /* static */
829 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
830 {
831 if ( year == Inv_Year )
832 year = GetCurrentYear();
833
834 if ( cal == Gregorian )
835 {
836 // in Gregorian calendar leap years are those divisible by 4 except
837 // those divisible by 100 unless they're also divisible by 400
838 // (in some countries, like Russia and Greece, additional corrections
839 // exist, but they won't manifest themselves until 2700)
840 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
841 }
842 else if ( cal == Julian )
843 {
844 // in Julian calendar the rule is simpler
845 return year % 4 == 0;
846 }
847 else
848 {
849 wxFAIL_MSG(_T("unknown calendar"));
850
851 return false;
852 }
853 }
854
855 /* static */
856 int wxDateTime::GetCentury(int year)
857 {
858 return year > 0 ? year / 100 : year / 100 - 1;
859 }
860
861 /* static */
862 int wxDateTime::ConvertYearToBC(int year)
863 {
864 // year 0 is BC 1
865 return year > 0 ? year : year - 1;
866 }
867
868 /* static */
869 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
870 {
871 switch ( cal )
872 {
873 case Gregorian:
874 return Now().GetYear();
875
876 case Julian:
877 wxFAIL_MSG(_T("TODO"));
878 break;
879
880 default:
881 wxFAIL_MSG(_T("unsupported calendar"));
882 break;
883 }
884
885 return Inv_Year;
886 }
887
888 /* static */
889 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
890 {
891 switch ( cal )
892 {
893 case Gregorian:
894 return Now().GetMonth();
895
896 case Julian:
897 wxFAIL_MSG(_T("TODO"));
898 break;
899
900 default:
901 wxFAIL_MSG(_T("unsupported calendar"));
902 break;
903 }
904
905 return Inv_Month;
906 }
907
908 /* static */
909 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
910 {
911 if ( year == Inv_Year )
912 {
913 // take the current year if none given
914 year = GetCurrentYear();
915 }
916
917 switch ( cal )
918 {
919 case Gregorian:
920 case Julian:
921 return IsLeapYear(year) ? 366 : 365;
922
923 default:
924 wxFAIL_MSG(_T("unsupported calendar"));
925 break;
926 }
927
928 return 0;
929 }
930
931 /* static */
932 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
933 int year,
934 wxDateTime::Calendar cal)
935 {
936 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
937
938 if ( cal == Gregorian || cal == Julian )
939 {
940 if ( year == Inv_Year )
941 {
942 // take the current year if none given
943 year = GetCurrentYear();
944 }
945
946 return GetNumOfDaysInMonth(year, month);
947 }
948 else
949 {
950 wxFAIL_MSG(_T("unsupported calendar"));
951
952 return 0;
953 }
954 }
955
956 /* static */
957 wxString wxDateTime::GetMonthName(wxDateTime::Month month,
958 wxDateTime::NameFlags flags)
959 {
960 wxCHECK_MSG( month != Inv_Month, wxEmptyString, _T("invalid month") );
961 #ifdef HAVE_STRFTIME
962 // notice that we must set all the fields to avoid confusing libc (GNU one
963 // gets confused to a crash if we don't do this)
964 tm tm;
965 InitTm(tm);
966 tm.tm_mon = month;
967
968 return CallStrftime(flags == Name_Abbr ? _T("%b") : _T("%B"), &tm);
969 #else // !HAVE_STRFTIME
970 wxString ret;
971 switch(month)
972 {
973 case Jan:
974 ret = (flags == Name_Abbr ? wxT("Jan"): wxT("January"));
975 break;
976 case Feb:
977 ret = (flags == Name_Abbr ? wxT("Feb"): wxT("Febuary"));
978 break;
979 case Mar:
980 ret = (flags == Name_Abbr ? wxT("Mar"): wxT("March"));
981 break;
982 case Apr:
983 ret = (flags == Name_Abbr ? wxT("Apr"): wxT("April"));
984 break;
985 case May:
986 ret = (flags == Name_Abbr ? wxT("May"): wxT("May"));
987 break;
988 case Jun:
989 ret = (flags == Name_Abbr ? wxT("Jun"): wxT("June"));
990 break;
991 case Jul:
992 ret = (flags == Name_Abbr ? wxT("Jul"): wxT("July"));
993 break;
994 case Aug:
995 ret = (flags == Name_Abbr ? wxT("Aug"): wxT("August"));
996 break;
997 case Sep:
998 ret = (flags == Name_Abbr ? wxT("Sep"): wxT("September"));
999 break;
1000 case Oct:
1001 ret = (flags == Name_Abbr ? wxT("Oct"): wxT("October"));
1002 break;
1003 case Nov:
1004 ret = (flags == Name_Abbr ? wxT("Nov"): wxT("November"));
1005 break;
1006 case Dec:
1007 ret = (flags == Name_Abbr ? wxT("Dec"): wxT("December"));
1008 break;
1009 }
1010 return ret;
1011 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
1012 }
1013
1014 /* static */
1015 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday,
1016 wxDateTime::NameFlags flags)
1017 {
1018 wxCHECK_MSG( wday != Inv_WeekDay, wxEmptyString, _T("invalid weekday") );
1019 #ifdef HAVE_STRFTIME
1020 // take some arbitrary Sunday (but notice that the day should be such that
1021 // after adding wday to it below we still have a valid date, e.g. don't
1022 // take 28 here!)
1023 tm tm;
1024 InitTm(tm);
1025 tm.tm_mday = 21;
1026 tm.tm_mon = Nov;
1027 tm.tm_year = 99;
1028
1029 // and offset it by the number of days needed to get the correct wday
1030 tm.tm_mday += wday;
1031
1032 // call mktime() to normalize it...
1033 (void)mktime(&tm);
1034
1035 // ... and call strftime()
1036 return CallStrftime(flags == Name_Abbr ? _T("%a") : _T("%A"), &tm);
1037 #else // !HAVE_STRFTIME
1038 wxString ret;
1039 switch(wday)
1040 {
1041 case Sun:
1042 ret = (flags == Name_Abbr ? wxT("Sun") : wxT("Sunday"));
1043 break;
1044 case Mon:
1045 ret = (flags == Name_Abbr ? wxT("Mon") : wxT("Monday"));
1046 break;
1047 case Tue:
1048 ret = (flags == Name_Abbr ? wxT("Tue") : wxT("Tuesday"));
1049 break;
1050 case Wed:
1051 ret = (flags == Name_Abbr ? wxT("Wed") : wxT("Wednesday"));
1052 break;
1053 case Thu:
1054 ret = (flags == Name_Abbr ? wxT("Thu") : wxT("Thursday"));
1055 break;
1056 case Fri:
1057 ret = (flags == Name_Abbr ? wxT("Fri") : wxT("Friday"));
1058 break;
1059 case Sat:
1060 ret = (flags == Name_Abbr ? wxT("Sat") : wxT("Saturday"));
1061 break;
1062 }
1063 return ret;
1064 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
1065 }
1066
1067 /* static */
1068 void wxDateTime::GetAmPmStrings(wxString *am, wxString *pm)
1069 {
1070 tm tm;
1071 InitTm(tm);
1072 wxChar buffer[64];
1073 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
1074 // and causes an assertion failed if the buffer is to small (which is good) - OR -
1075 // if strftime does not return anything because the format string is invalid - OR -
1076 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
1077 // wxDateTime::ParseTime will try several different formats to parse the time.
1078 // As a result, GetAmPmStrings might get called, even if the current locale
1079 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
1080 // assert, even though it is a perfectly legal use.
1081 if ( am )
1082 {
1083 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
1084 *am = wxString(buffer);
1085 else
1086 *am = wxString();
1087 }
1088 if ( pm )
1089 {
1090 tm.tm_hour = 13;
1091 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
1092 *pm = wxString(buffer);
1093 else
1094 *pm = wxString();
1095 }
1096 }
1097
1098 // ----------------------------------------------------------------------------
1099 // Country stuff: date calculations depend on the country (DST, work days,
1100 // ...), so we need to know which rules to follow.
1101 // ----------------------------------------------------------------------------
1102
1103 /* static */
1104 wxDateTime::Country wxDateTime::GetCountry()
1105 {
1106 // TODO use LOCALE_ICOUNTRY setting under Win32
1107 #ifndef __WXWINCE__
1108 if ( ms_country == Country_Unknown )
1109 {
1110 // try to guess from the time zone name
1111 time_t t = time(NULL);
1112 struct tm tmstruct;
1113 struct tm *tm = wxLocaltime_r(&t, &tmstruct);
1114
1115 wxString tz = CallStrftime(_T("%Z"), tm);
1116 if ( tz == _T("WET") || tz == _T("WEST") )
1117 {
1118 ms_country = UK;
1119 }
1120 else if ( tz == _T("CET") || tz == _T("CEST") )
1121 {
1122 ms_country = Country_EEC;
1123 }
1124 else if ( tz == _T("MSK") || tz == _T("MSD") )
1125 {
1126 ms_country = Russia;
1127 }
1128 else if ( tz == _T("AST") || tz == _T("ADT") ||
1129 tz == _T("EST") || tz == _T("EDT") ||
1130 tz == _T("CST") || tz == _T("CDT") ||
1131 tz == _T("MST") || tz == _T("MDT") ||
1132 tz == _T("PST") || tz == _T("PDT") )
1133 {
1134 ms_country = USA;
1135 }
1136 else
1137 {
1138 // well, choose a default one
1139 ms_country = USA;
1140 }
1141 }
1142 #else // __WXWINCE__
1143 ms_country = USA;
1144 #endif // !__WXWINCE__/__WXWINCE__
1145
1146 return ms_country;
1147 }
1148
1149 /* static */
1150 void wxDateTime::SetCountry(wxDateTime::Country country)
1151 {
1152 ms_country = country;
1153 }
1154
1155 /* static */
1156 bool wxDateTime::IsWestEuropeanCountry(Country country)
1157 {
1158 if ( country == Country_Default )
1159 {
1160 country = GetCountry();
1161 }
1162
1163 return (Country_WesternEurope_Start <= country) &&
1164 (country <= Country_WesternEurope_End);
1165 }
1166
1167 // ----------------------------------------------------------------------------
1168 // DST calculations: we use 3 different rules for the West European countries,
1169 // USA and for the rest of the world. This is undoubtedly false for many
1170 // countries, but I lack the necessary info (and the time to gather it),
1171 // please add the other rules here!
1172 // ----------------------------------------------------------------------------
1173
1174 /* static */
1175 bool wxDateTime::IsDSTApplicable(int year, Country country)
1176 {
1177 if ( year == Inv_Year )
1178 {
1179 // take the current year if none given
1180 year = GetCurrentYear();
1181 }
1182
1183 if ( country == Country_Default )
1184 {
1185 country = GetCountry();
1186 }
1187
1188 switch ( country )
1189 {
1190 case USA:
1191 case UK:
1192 // DST was first observed in the US and UK during WWI, reused
1193 // during WWII and used again since 1966
1194 return year >= 1966 ||
1195 (year >= 1942 && year <= 1945) ||
1196 (year == 1918 || year == 1919);
1197
1198 default:
1199 // assume that it started after WWII
1200 return year > 1950;
1201 }
1202 }
1203
1204 /* static */
1205 wxDateTime wxDateTime::GetBeginDST(int year, Country country)
1206 {
1207 if ( year == Inv_Year )
1208 {
1209 // take the current year if none given
1210 year = GetCurrentYear();
1211 }
1212
1213 if ( country == Country_Default )
1214 {
1215 country = GetCountry();
1216 }
1217
1218 if ( !IsDSTApplicable(year, country) )
1219 {
1220 return wxInvalidDateTime;
1221 }
1222
1223 wxDateTime dt;
1224
1225 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1226 {
1227 // DST begins at 1 a.m. GMT on the last Sunday of March
1228 if ( !dt.SetToLastWeekDay(Sun, Mar, year) )
1229 {
1230 // weird...
1231 wxFAIL_MSG( _T("no last Sunday in March?") );
1232 }
1233
1234 dt += wxTimeSpan::Hours(1);
1235 }
1236 else switch ( country )
1237 {
1238 case USA:
1239 switch ( year )
1240 {
1241 case 1918:
1242 case 1919:
1243 // don't know for sure - assume it was in effect all year
1244
1245 case 1943:
1246 case 1944:
1247 case 1945:
1248 dt.Set(1, Jan, year);
1249 break;
1250
1251 case 1942:
1252 // DST was installed Feb 2, 1942 by the Congress
1253 dt.Set(2, Feb, year);
1254 break;
1255
1256 // Oil embargo changed the DST period in the US
1257 case 1974:
1258 dt.Set(6, Jan, 1974);
1259 break;
1260
1261 case 1975:
1262 dt.Set(23, Feb, 1975);
1263 break;
1264
1265 default:
1266 // before 1986, DST begun on the last Sunday of April, but
1267 // in 1986 Reagan changed it to begin at 2 a.m. of the
1268 // first Sunday in April
1269 if ( year < 1986 )
1270 {
1271 if ( !dt.SetToLastWeekDay(Sun, Apr, year) )
1272 {
1273 // weird...
1274 wxFAIL_MSG( _T("no first Sunday in April?") );
1275 }
1276 }
1277 else if ( year > 2006 )
1278 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1279 // Starting in 2007, daylight time begins in the United States on the
1280 // second Sunday in March and ends on the first Sunday in November
1281 {
1282 if ( !dt.SetToWeekDay(Sun, 2, Mar, year) )
1283 {
1284 // weird...
1285 wxFAIL_MSG( _T("no second Sunday in March?") );
1286 }
1287 }
1288 else
1289 {
1290 if ( !dt.SetToWeekDay(Sun, 1, Apr, year) )
1291 {
1292 // weird...
1293 wxFAIL_MSG( _T("no first Sunday in April?") );
1294 }
1295 }
1296
1297 dt += wxTimeSpan::Hours(2);
1298
1299 // TODO what about timezone??
1300 }
1301
1302 break;
1303
1304 default:
1305 // assume Mar 30 as the start of the DST for the rest of the world
1306 // - totally bogus, of course
1307 dt.Set(30, Mar, year);
1308 }
1309
1310 return dt;
1311 }
1312
1313 /* static */
1314 wxDateTime wxDateTime::GetEndDST(int year, Country country)
1315 {
1316 if ( year == Inv_Year )
1317 {
1318 // take the current year if none given
1319 year = GetCurrentYear();
1320 }
1321
1322 if ( country == Country_Default )
1323 {
1324 country = GetCountry();
1325 }
1326
1327 if ( !IsDSTApplicable(year, country) )
1328 {
1329 return wxInvalidDateTime;
1330 }
1331
1332 wxDateTime dt;
1333
1334 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1335 {
1336 // DST ends at 1 a.m. GMT on the last Sunday of October
1337 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1338 {
1339 // weirder and weirder...
1340 wxFAIL_MSG( _T("no last Sunday in October?") );
1341 }
1342
1343 dt += wxTimeSpan::Hours(1);
1344 }
1345 else switch ( country )
1346 {
1347 case USA:
1348 switch ( year )
1349 {
1350 case 1918:
1351 case 1919:
1352 // don't know for sure - assume it was in effect all year
1353
1354 case 1943:
1355 case 1944:
1356 dt.Set(31, Dec, year);
1357 break;
1358
1359 case 1945:
1360 // the time was reset after the end of the WWII
1361 dt.Set(30, Sep, year);
1362 break;
1363
1364 default: // default for switch (year)
1365 if ( year > 2006 )
1366 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1367 // Starting in 2007, daylight time begins in the United States on the
1368 // second Sunday in March and ends on the first Sunday in November
1369 {
1370 if ( !dt.SetToWeekDay(Sun, 1, Nov, year) )
1371 {
1372 // weird...
1373 wxFAIL_MSG( _T("no first Sunday in November?") );
1374 }
1375 }
1376 else
1377 // pre-2007
1378 // DST ends at 2 a.m. on the last Sunday of October
1379 {
1380 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1381 {
1382 // weirder and weirder...
1383 wxFAIL_MSG( _T("no last Sunday in October?") );
1384 }
1385 }
1386
1387 dt += wxTimeSpan::Hours(2);
1388
1389 // TODO: what about timezone??
1390 }
1391 break;
1392
1393 default: // default for switch (country)
1394 // assume October 26th as the end of the DST - totally bogus too
1395 dt.Set(26, Oct, year);
1396 }
1397
1398 return dt;
1399 }
1400
1401 // ----------------------------------------------------------------------------
1402 // constructors and assignment operators
1403 // ----------------------------------------------------------------------------
1404
1405 // return the current time with ms precision
1406 /* static */ wxDateTime wxDateTime::UNow()
1407 {
1408 return wxDateTime(wxGetLocalTimeMillis());
1409 }
1410
1411 // the values in the tm structure contain the local time
1412 wxDateTime& wxDateTime::Set(const struct tm& tm)
1413 {
1414 struct tm tm2(tm);
1415 time_t timet = mktime(&tm2);
1416
1417 if ( timet == (time_t)-1 )
1418 {
1419 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1420 // less than timezone - try to make it work for this case
1421 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
1422 {
1423 return Set((time_t)(
1424 GetTimeZone() +
1425 tm2.tm_hour * MIN_PER_HOUR * SEC_PER_MIN +
1426 tm2.tm_min * SEC_PER_MIN +
1427 tm2.tm_sec));
1428 }
1429
1430 wxFAIL_MSG( _T("mktime() failed") );
1431
1432 *this = wxInvalidDateTime;
1433
1434 return *this;
1435 }
1436 else
1437 {
1438 return Set(timet);
1439 }
1440 }
1441
1442 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
1443 wxDateTime_t minute,
1444 wxDateTime_t second,
1445 wxDateTime_t millisec)
1446 {
1447 // we allow seconds to be 61 to account for the leap seconds, even if we
1448 // don't use them really
1449 wxDATETIME_CHECK( hour < 24 &&
1450 second < 62 &&
1451 minute < 60 &&
1452 millisec < 1000,
1453 _T("Invalid time in wxDateTime::Set()") );
1454
1455 // get the current date from system
1456 struct tm tmstruct;
1457 struct tm *tm = GetTmNow(&tmstruct);
1458
1459 wxDATETIME_CHECK( tm, _T("wxLocaltime_r() failed") );
1460
1461 // make a copy so it isn't clobbered by the call to mktime() below
1462 struct tm tm1(*tm);
1463
1464 // adjust the time
1465 tm1.tm_hour = hour;
1466 tm1.tm_min = minute;
1467 tm1.tm_sec = second;
1468
1469 // and the DST in case it changes on this date
1470 struct tm tm2(tm1);
1471 mktime(&tm2);
1472 if ( tm2.tm_isdst != tm1.tm_isdst )
1473 tm1.tm_isdst = tm2.tm_isdst;
1474
1475 (void)Set(tm1);
1476
1477 // and finally adjust milliseconds
1478 return SetMillisecond(millisec);
1479 }
1480
1481 wxDateTime& wxDateTime::Set(wxDateTime_t day,
1482 Month month,
1483 int year,
1484 wxDateTime_t hour,
1485 wxDateTime_t minute,
1486 wxDateTime_t second,
1487 wxDateTime_t millisec)
1488 {
1489 wxDATETIME_CHECK( hour < 24 &&
1490 second < 62 &&
1491 minute < 60 &&
1492 millisec < 1000,
1493 _T("Invalid time in wxDateTime::Set()") );
1494
1495 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1496
1497 wxDATETIME_CHECK( (0 < day) && (day <= GetNumberOfDays(month, year)),
1498 _T("Invalid date in wxDateTime::Set()") );
1499
1500 // the range of time_t type (inclusive)
1501 static const int yearMinInRange = 1970;
1502 static const int yearMaxInRange = 2037;
1503
1504 // test only the year instead of testing for the exact end of the Unix
1505 // time_t range - it doesn't bring anything to do more precise checks
1506 if ( year >= yearMinInRange && year <= yearMaxInRange )
1507 {
1508 // use the standard library version if the date is in range - this is
1509 // probably more efficient than our code
1510 struct tm tm;
1511 tm.tm_year = year - 1900;
1512 tm.tm_mon = month;
1513 tm.tm_mday = day;
1514 tm.tm_hour = hour;
1515 tm.tm_min = minute;
1516 tm.tm_sec = second;
1517 tm.tm_isdst = -1; // mktime() will guess it
1518
1519 (void)Set(tm);
1520
1521 // and finally adjust milliseconds
1522 if (IsValid())
1523 SetMillisecond(millisec);
1524
1525 return *this;
1526 }
1527 else
1528 {
1529 // do time calculations ourselves: we want to calculate the number of
1530 // milliseconds between the given date and the epoch
1531
1532 // get the JDN for the midnight of this day
1533 m_time = GetTruncatedJDN(day, month, year);
1534 m_time -= EPOCH_JDN;
1535 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
1536
1537 // JDN corresponds to GMT, we take localtime
1538 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
1539 }
1540
1541 return *this;
1542 }
1543
1544 wxDateTime& wxDateTime::Set(double jdn)
1545 {
1546 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1547 // EPOCH_JDN + 0.5
1548 jdn -= EPOCH_JDN + 0.5;
1549
1550 m_time.Assign(jdn*MILLISECONDS_PER_DAY);
1551
1552 // JDNs always are in UTC, so we don't need any adjustments for time zone
1553
1554 return *this;
1555 }
1556
1557 wxDateTime& wxDateTime::ResetTime()
1558 {
1559 Tm tm = GetTm();
1560
1561 if ( tm.hour || tm.min || tm.sec || tm.msec )
1562 {
1563 tm.msec =
1564 tm.sec =
1565 tm.min =
1566 tm.hour = 0;
1567
1568 Set(tm);
1569 }
1570
1571 return *this;
1572 }
1573
1574 wxDateTime wxDateTime::GetDateOnly() const
1575 {
1576 Tm tm = GetTm();
1577 tm.msec =
1578 tm.sec =
1579 tm.min =
1580 tm.hour = 0;
1581 return wxDateTime(tm);
1582 }
1583
1584 // ----------------------------------------------------------------------------
1585 // DOS Date and Time Format functions
1586 // ----------------------------------------------------------------------------
1587 // the dos date and time value is an unsigned 32 bit value in the format:
1588 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1589 //
1590 // Y = year offset from 1980 (0-127)
1591 // M = month (1-12)
1592 // D = day of month (1-31)
1593 // h = hour (0-23)
1594 // m = minute (0-59)
1595 // s = bisecond (0-29) each bisecond indicates two seconds
1596 // ----------------------------------------------------------------------------
1597
1598 wxDateTime& wxDateTime::SetFromDOS(unsigned long ddt)
1599 {
1600 struct tm tm;
1601 InitTm(tm);
1602
1603 long year = ddt & 0xFE000000;
1604 year >>= 25;
1605 year += 80;
1606 tm.tm_year = year;
1607
1608 long month = ddt & 0x1E00000;
1609 month >>= 21;
1610 month -= 1;
1611 tm.tm_mon = month;
1612
1613 long day = ddt & 0x1F0000;
1614 day >>= 16;
1615 tm.tm_mday = day;
1616
1617 long hour = ddt & 0xF800;
1618 hour >>= 11;
1619 tm.tm_hour = hour;
1620
1621 long minute = ddt & 0x7E0;
1622 minute >>= 5;
1623 tm.tm_min = minute;
1624
1625 long second = ddt & 0x1F;
1626 tm.tm_sec = second * 2;
1627
1628 return Set(mktime(&tm));
1629 }
1630
1631 unsigned long wxDateTime::GetAsDOS() const
1632 {
1633 unsigned long ddt;
1634 time_t ticks = GetTicks();
1635 struct tm tmstruct;
1636 struct tm *tm = wxLocaltime_r(&ticks, &tmstruct);
1637 wxCHECK_MSG( tm, ULONG_MAX, _T("time can't be represented in DOS format") );
1638
1639 long year = tm->tm_year;
1640 year -= 80;
1641 year <<= 25;
1642
1643 long month = tm->tm_mon;
1644 month += 1;
1645 month <<= 21;
1646
1647 long day = tm->tm_mday;
1648 day <<= 16;
1649
1650 long hour = tm->tm_hour;
1651 hour <<= 11;
1652
1653 long minute = tm->tm_min;
1654 minute <<= 5;
1655
1656 long second = tm->tm_sec;
1657 second /= 2;
1658
1659 ddt = year | month | day | hour | minute | second;
1660 return ddt;
1661 }
1662
1663 // ----------------------------------------------------------------------------
1664 // time_t <-> broken down time conversions
1665 // ----------------------------------------------------------------------------
1666
1667 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
1668 {
1669 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1670
1671 time_t time = GetTicks();
1672 if ( time != (time_t)-1 )
1673 {
1674 // use C RTL functions
1675 struct tm tmstruct;
1676 tm *tm;
1677 if ( tz.GetOffset() == -GetTimeZone() )
1678 {
1679 // we are working with local time
1680 tm = wxLocaltime_r(&time, &tmstruct);
1681
1682 // should never happen
1683 wxCHECK_MSG( tm, Tm(), _T("wxLocaltime_r() failed") );
1684 }
1685 else
1686 {
1687 time += (time_t)tz.GetOffset();
1688 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1689 int time2 = (int) time;
1690 if ( time2 >= 0 )
1691 #else
1692 if ( time >= 0 )
1693 #endif
1694 {
1695 tm = wxGmtime_r(&time, &tmstruct);
1696
1697 // should never happen
1698 wxCHECK_MSG( tm, Tm(), _T("wxGmtime_r() failed") );
1699 }
1700 else
1701 {
1702 tm = (struct tm *)NULL;
1703 }
1704 }
1705
1706 if ( tm )
1707 {
1708 // adjust the milliseconds
1709 Tm tm2(*tm, tz);
1710 long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong();
1711 tm2.msec = (wxDateTime_t)(timeOnly % 1000);
1712 return tm2;
1713 }
1714 //else: use generic code below
1715 }
1716
1717 // remember the time and do the calculations with the date only - this
1718 // eliminates rounding errors of the floating point arithmetics
1719
1720 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
1721
1722 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1723
1724 // we want to always have positive time and timeMidnight to be really
1725 // the midnight before it
1726 if ( timeOnly < 0 )
1727 {
1728 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1729 }
1730
1731 timeMidnight -= timeOnly;
1732
1733 // calculate the Gregorian date from JDN for the midnight of our date:
1734 // this will yield day, month (in 1..12 range) and year
1735
1736 // actually, this is the JDN for the noon of the previous day
1737 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
1738
1739 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1740
1741 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
1742
1743 // calculate the century
1744 long temp = (jdn + JDN_OFFSET) * 4 - 1;
1745 long century = temp / DAYS_PER_400_YEARS;
1746
1747 // then the year and day of year (1 <= dayOfYear <= 366)
1748 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
1749 long year = (century * 100) + (temp / DAYS_PER_4_YEARS);
1750 long dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
1751
1752 // and finally the month and day of the month
1753 temp = dayOfYear * 5 - 3;
1754 long month = temp / DAYS_PER_5_MONTHS;
1755 long day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
1756
1757 // month is counted from March - convert to normal
1758 if ( month < 10 )
1759 {
1760 month += 3;
1761 }
1762 else
1763 {
1764 year += 1;
1765 month -= 9;
1766 }
1767
1768 // year is offset by 4800
1769 year -= 4800;
1770
1771 // check that the algorithm gave us something reasonable
1772 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
1773 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
1774
1775 // construct Tm from these values
1776 Tm tm;
1777 tm.year = (int)year;
1778 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1779 tm.mday = (wxDateTime_t)day;
1780 tm.msec = (wxDateTime_t)(timeOnly % 1000);
1781 timeOnly -= tm.msec;
1782 timeOnly /= 1000; // now we have time in seconds
1783
1784 tm.sec = (wxDateTime_t)(timeOnly % SEC_PER_MIN);
1785 timeOnly -= tm.sec;
1786 timeOnly /= SEC_PER_MIN; // now we have time in minutes
1787
1788 tm.min = (wxDateTime_t)(timeOnly % MIN_PER_HOUR);
1789 timeOnly -= tm.min;
1790
1791 tm.hour = (wxDateTime_t)(timeOnly / MIN_PER_HOUR);
1792
1793 return tm;
1794 }
1795
1796 wxDateTime& wxDateTime::SetYear(int year)
1797 {
1798 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1799
1800 Tm tm(GetTm());
1801 tm.year = year;
1802 Set(tm);
1803
1804 return *this;
1805 }
1806
1807 wxDateTime& wxDateTime::SetMonth(Month month)
1808 {
1809 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1810
1811 Tm tm(GetTm());
1812 tm.mon = month;
1813 Set(tm);
1814
1815 return *this;
1816 }
1817
1818 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
1819 {
1820 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1821
1822 Tm tm(GetTm());
1823 tm.mday = mday;
1824 Set(tm);
1825
1826 return *this;
1827 }
1828
1829 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
1830 {
1831 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1832
1833 Tm tm(GetTm());
1834 tm.hour = hour;
1835 Set(tm);
1836
1837 return *this;
1838 }
1839
1840 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
1841 {
1842 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1843
1844 Tm tm(GetTm());
1845 tm.min = min;
1846 Set(tm);
1847
1848 return *this;
1849 }
1850
1851 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
1852 {
1853 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1854
1855 Tm tm(GetTm());
1856 tm.sec = sec;
1857 Set(tm);
1858
1859 return *this;
1860 }
1861
1862 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
1863 {
1864 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1865
1866 // we don't need to use GetTm() for this one
1867 m_time -= m_time % 1000l;
1868 m_time += millisecond;
1869
1870 return *this;
1871 }
1872
1873 // ----------------------------------------------------------------------------
1874 // wxDateTime arithmetics
1875 // ----------------------------------------------------------------------------
1876
1877 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
1878 {
1879 Tm tm(GetTm());
1880
1881 tm.year += diff.GetYears();
1882 tm.AddMonths(diff.GetMonths());
1883
1884 // check that the resulting date is valid
1885 if ( tm.mday > GetNumOfDaysInMonth(tm.year, tm.mon) )
1886 {
1887 // We suppose that when adding one month to Jan 31 we want to get Feb
1888 // 28 (or 29), i.e. adding a month to the last day of the month should
1889 // give the last day of the next month which is quite logical.
1890 //
1891 // Unfortunately, there is no logic way to understand what should
1892 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1893 // We make it Feb 28 (last day too), but it is highly questionable.
1894 tm.mday = GetNumOfDaysInMonth(tm.year, tm.mon);
1895 }
1896
1897 tm.AddDays(diff.GetTotalDays());
1898
1899 Set(tm);
1900
1901 wxASSERT_MSG( IsSameTime(tm),
1902 _T("Add(wxDateSpan) shouldn't modify time") );
1903
1904 return *this;
1905 }
1906
1907 // ----------------------------------------------------------------------------
1908 // Weekday and monthday stuff
1909 // ----------------------------------------------------------------------------
1910
1911 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1912 static inline int ConvertWeekDayToMondayBase(int wd)
1913 {
1914 return wd == wxDateTime::Sun ? 6 : wd - 1;
1915 }
1916
1917 /* static */
1918 wxDateTime
1919 wxDateTime::SetToWeekOfYear(int year, wxDateTime_t numWeek, WeekDay wd)
1920 {
1921 wxASSERT_MSG( numWeek > 0,
1922 _T("invalid week number: weeks are counted from 1") );
1923
1924 // Jan 4 always lies in the 1st week of the year
1925 wxDateTime dt(4, Jan, year);
1926 dt.SetToWeekDayInSameWeek(wd);
1927 dt += wxDateSpan::Weeks(numWeek - 1);
1928
1929 return dt;
1930 }
1931
1932 #if WXWIN_COMPATIBILITY_2_6
1933 // use a separate function to avoid warnings about using deprecated
1934 // SetToTheWeek in GetWeek below
1935 static wxDateTime
1936 SetToTheWeek(int year,
1937 wxDateTime::wxDateTime_t numWeek,
1938 wxDateTime::WeekDay weekday,
1939 wxDateTime::WeekFlags flags)
1940 {
1941 // Jan 4 always lies in the 1st week of the year
1942 wxDateTime dt(4, wxDateTime::Jan, year);
1943 dt.SetToWeekDayInSameWeek(weekday, flags);
1944 dt += wxDateSpan::Weeks(numWeek - 1);
1945
1946 return dt;
1947 }
1948
1949 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek,
1950 WeekDay weekday,
1951 WeekFlags flags)
1952 {
1953 int year = GetYear();
1954 *this = ::SetToTheWeek(year, numWeek, weekday, flags);
1955 if ( GetYear() != year )
1956 {
1957 // oops... numWeek was too big
1958 return false;
1959 }
1960
1961 return true;
1962 }
1963
1964 wxDateTime wxDateTime::GetWeek(wxDateTime_t numWeek,
1965 WeekDay weekday,
1966 WeekFlags flags) const
1967 {
1968 return ::SetToTheWeek(GetYear(), numWeek, weekday, flags);
1969 }
1970 #endif // WXWIN_COMPATIBILITY_2_6
1971
1972 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
1973 int year)
1974 {
1975 // take the current month/year if none specified
1976 if ( year == Inv_Year )
1977 year = GetYear();
1978 if ( month == Inv_Month )
1979 month = GetMonth();
1980
1981 return Set(GetNumOfDaysInMonth(year, month), month, year);
1982 }
1983
1984 wxDateTime& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday, WeekFlags flags)
1985 {
1986 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1987
1988 int wdayDst = weekday,
1989 wdayThis = GetWeekDay();
1990 if ( wdayDst == wdayThis )
1991 {
1992 // nothing to do
1993 return *this;
1994 }
1995
1996 if ( flags == Default_First )
1997 {
1998 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1999 }
2000
2001 // the logic below based on comparing weekday and wdayThis works if Sun (0)
2002 // is the first day in the week, but breaks down for Monday_First case so
2003 // we adjust the week days in this case
2004 if ( flags == Monday_First )
2005 {
2006 if ( wdayThis == Sun )
2007 wdayThis += 7;
2008 if ( wdayDst == Sun )
2009 wdayDst += 7;
2010 }
2011 //else: Sunday_First, nothing to do
2012
2013 // go forward or back in time to the day we want
2014 if ( wdayDst < wdayThis )
2015 {
2016 return Subtract(wxDateSpan::Days(wdayThis - wdayDst));
2017 }
2018 else // weekday > wdayThis
2019 {
2020 return Add(wxDateSpan::Days(wdayDst - wdayThis));
2021 }
2022 }
2023
2024 wxDateTime& wxDateTime::SetToNextWeekDay(WeekDay weekday)
2025 {
2026 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
2027
2028 int diff;
2029 WeekDay wdayThis = GetWeekDay();
2030 if ( weekday == wdayThis )
2031 {
2032 // nothing to do
2033 return *this;
2034 }
2035 else if ( weekday < wdayThis )
2036 {
2037 // need to advance a week
2038 diff = 7 - (wdayThis - weekday);
2039 }
2040 else // weekday > wdayThis
2041 {
2042 diff = weekday - wdayThis;
2043 }
2044
2045 return Add(wxDateSpan::Days(diff));
2046 }
2047
2048 wxDateTime& wxDateTime::SetToPrevWeekDay(WeekDay weekday)
2049 {
2050 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
2051
2052 int diff;
2053 WeekDay wdayThis = GetWeekDay();
2054 if ( weekday == wdayThis )
2055 {
2056 // nothing to do
2057 return *this;
2058 }
2059 else if ( weekday > wdayThis )
2060 {
2061 // need to go to previous week
2062 diff = 7 - (weekday - wdayThis);
2063 }
2064 else // weekday < wdayThis
2065 {
2066 diff = wdayThis - weekday;
2067 }
2068
2069 return Subtract(wxDateSpan::Days(diff));
2070 }
2071
2072 bool wxDateTime::SetToWeekDay(WeekDay weekday,
2073 int n,
2074 Month month,
2075 int year)
2076 {
2077 wxCHECK_MSG( weekday != Inv_WeekDay, false, _T("invalid weekday") );
2078
2079 // we don't check explicitly that -5 <= n <= 5 because we will return false
2080 // anyhow in such case - but may be should still give an assert for it?
2081
2082 // take the current month/year if none specified
2083 ReplaceDefaultYearMonthWithCurrent(&year, &month);
2084
2085 wxDateTime dt;
2086
2087 // TODO this probably could be optimised somehow...
2088
2089 if ( n > 0 )
2090 {
2091 // get the first day of the month
2092 dt.Set(1, month, year);
2093
2094 // get its wday
2095 WeekDay wdayFirst = dt.GetWeekDay();
2096
2097 // go to the first weekday of the month
2098 int diff = weekday - wdayFirst;
2099 if ( diff < 0 )
2100 diff += 7;
2101
2102 // add advance n-1 weeks more
2103 diff += 7*(n - 1);
2104
2105 dt += wxDateSpan::Days(diff);
2106 }
2107 else // count from the end of the month
2108 {
2109 // get the last day of the month
2110 dt.SetToLastMonthDay(month, year);
2111
2112 // get its wday
2113 WeekDay wdayLast = dt.GetWeekDay();
2114
2115 // go to the last weekday of the month
2116 int diff = wdayLast - weekday;
2117 if ( diff < 0 )
2118 diff += 7;
2119
2120 // and rewind n-1 weeks from there
2121 diff += 7*(-n - 1);
2122
2123 dt -= wxDateSpan::Days(diff);
2124 }
2125
2126 // check that it is still in the same month
2127 if ( dt.GetMonth() == month )
2128 {
2129 *this = dt;
2130
2131 return true;
2132 }
2133 else
2134 {
2135 // no such day in this month
2136 return false;
2137 }
2138 }
2139
2140 static inline
2141 wxDateTime::wxDateTime_t GetDayOfYearFromTm(const wxDateTime::Tm& tm)
2142 {
2143 return (wxDateTime::wxDateTime_t)(gs_cumulatedDays[wxDateTime::IsLeapYear(tm.year)][tm.mon] + tm.mday);
2144 }
2145
2146 wxDateTime::wxDateTime_t wxDateTime::GetDayOfYear(const TimeZone& tz) const
2147 {
2148 return GetDayOfYearFromTm(GetTm(tz));
2149 }
2150
2151 wxDateTime::wxDateTime_t
2152 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags, const TimeZone& tz) const
2153 {
2154 if ( flags == Default_First )
2155 {
2156 flags = GetCountry() == USA ? Sunday_First : Monday_First;
2157 }
2158
2159 Tm tm(GetTm(tz));
2160 wxDateTime_t nDayInYear = GetDayOfYearFromTm(tm);
2161
2162 int wdTarget = GetWeekDay(tz);
2163 int wdYearStart = wxDateTime(1, Jan, GetYear()).GetWeekDay();
2164 int week;
2165 if ( flags == Sunday_First )
2166 {
2167 // FIXME: First week is not calculated correctly.
2168 week = (nDayInYear - wdTarget + 7) / 7;
2169 if ( wdYearStart == Wed || wdYearStart == Thu )
2170 week++;
2171 }
2172 else // week starts with monday
2173 {
2174 // adjust the weekdays to non-US style.
2175 wdYearStart = ConvertWeekDayToMondayBase(wdYearStart);
2176 wdTarget = ConvertWeekDayToMondayBase(wdTarget);
2177
2178 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2179 //
2180 // Week 01 of a year is per definition the first week that has the
2181 // Thursday in this year, which is equivalent to the week that
2182 // contains the fourth day of January. In other words, the first
2183 // week of a new year is the week that has the majority of its
2184 // days in the new year. Week 01 might also contain days from the
2185 // previous year and the week before week 01 of a year is the last
2186 // week (52 or 53) of the previous year even if it contains days
2187 // from the new year. A week starts with Monday (day 1) and ends
2188 // with Sunday (day 7).
2189 //
2190
2191 // if Jan 1 is Thursday or less, it is in the first week of this year
2192 if ( wdYearStart < 4 )
2193 {
2194 // count the number of entire weeks between Jan 1 and this date
2195 week = (nDayInYear + wdYearStart + 6 - wdTarget)/7;
2196
2197 // be careful to check for overflow in the next year
2198 if ( week == 53 && tm.mday - wdTarget > 28 )
2199 week = 1;
2200 }
2201 else // Jan 1 is in the last week of the previous year
2202 {
2203 // check if we happen to be at the last week of previous year:
2204 if ( tm.mon == Jan && tm.mday < 8 - wdYearStart )
2205 week = wxDateTime(31, Dec, GetYear()-1).GetWeekOfYear();
2206 else
2207 week = (nDayInYear + wdYearStart - 1 - wdTarget)/7;
2208 }
2209 }
2210
2211 return (wxDateTime::wxDateTime_t)week;
2212 }
2213
2214 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags,
2215 const TimeZone& tz) const
2216 {
2217 Tm tm = GetTm(tz);
2218 wxDateTime dtMonthStart = wxDateTime(1, tm.mon, tm.year);
2219 int nWeek = GetWeekOfYear(flags) - dtMonthStart.GetWeekOfYear(flags) + 1;
2220 if ( nWeek < 0 )
2221 {
2222 // this may happen for January when Jan, 1 is the last week of the
2223 // previous year
2224 nWeek += IsLeapYear(tm.year - 1) ? 53 : 52;
2225 }
2226
2227 return (wxDateTime::wxDateTime_t)nWeek;
2228 }
2229
2230 wxDateTime& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday)
2231 {
2232 int year = GetYear();
2233 wxDATETIME_CHECK( (0 < yday) && (yday <= GetNumberOfDays(year)),
2234 _T("invalid year day") );
2235
2236 bool isLeap = IsLeapYear(year);
2237 for ( Month mon = Jan; mon < Inv_Month; wxNextMonth(mon) )
2238 {
2239 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2240 // don't need it neither - because of the CHECK above we know that
2241 // yday lies in December then
2242 if ( (mon == Dec) || (yday <= gs_cumulatedDays[isLeap][mon + 1]) )
2243 {
2244 Set((wxDateTime::wxDateTime_t)(yday - gs_cumulatedDays[isLeap][mon]), mon, year);
2245
2246 break;
2247 }
2248 }
2249
2250 return *this;
2251 }
2252
2253 // ----------------------------------------------------------------------------
2254 // Julian day number conversion and related stuff
2255 // ----------------------------------------------------------------------------
2256
2257 double wxDateTime::GetJulianDayNumber() const
2258 {
2259 return m_time.ToDouble() / MILLISECONDS_PER_DAY + EPOCH_JDN + 0.5;
2260 }
2261
2262 double wxDateTime::GetRataDie() const
2263 {
2264 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2265 return GetJulianDayNumber() - 1721119.5 - 306;
2266 }
2267
2268 // ----------------------------------------------------------------------------
2269 // timezone and DST stuff
2270 // ----------------------------------------------------------------------------
2271
2272 int wxDateTime::IsDST(wxDateTime::Country country) const
2273 {
2274 wxCHECK_MSG( country == Country_Default, -1,
2275 _T("country support not implemented") );
2276
2277 // use the C RTL for the dates in the standard range
2278 time_t timet = GetTicks();
2279 if ( timet != (time_t)-1 )
2280 {
2281 struct tm tmstruct;
2282 tm *tm = wxLocaltime_r(&timet, &tmstruct);
2283
2284 wxCHECK_MSG( tm, -1, _T("wxLocaltime_r() failed") );
2285
2286 return tm->tm_isdst;
2287 }
2288 else
2289 {
2290 int year = GetYear();
2291
2292 if ( !IsDSTApplicable(year, country) )
2293 {
2294 // no DST time in this year in this country
2295 return -1;
2296 }
2297
2298 return IsBetween(GetBeginDST(year, country), GetEndDST(year, country));
2299 }
2300 }
2301
2302 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz, bool noDST)
2303 {
2304 long secDiff = GetTimeZone() + tz.GetOffset();
2305
2306 // we need to know whether DST is or not in effect for this date unless
2307 // the test disabled by the caller
2308 if ( !noDST && (IsDST() == 1) )
2309 {
2310 // FIXME we assume that the DST is always shifted by 1 hour
2311 secDiff -= 3600;
2312 }
2313
2314 return Add(wxTimeSpan::Seconds(secDiff));
2315 }
2316
2317 wxDateTime& wxDateTime::MakeFromTimezone(const TimeZone& tz, bool noDST)
2318 {
2319 long secDiff = GetTimeZone() + tz.GetOffset();
2320
2321 // we need to know whether DST is or not in effect for this date unless
2322 // the test disabled by the caller
2323 if ( !noDST && (IsDST() == 1) )
2324 {
2325 // FIXME we assume that the DST is always shifted by 1 hour
2326 secDiff -= 3600;
2327 }
2328
2329 return Subtract(wxTimeSpan::Seconds(secDiff));
2330 }
2331
2332 // ============================================================================
2333 // wxDateTimeHolidayAuthority and related classes
2334 // ============================================================================
2335
2336 #include "wx/arrimpl.cpp"
2337
2338 WX_DEFINE_OBJARRAY(wxDateTimeArray)
2339
2340 static int wxCMPFUNC_CONV
2341 wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
2342 {
2343 wxDateTime dt1 = **first,
2344 dt2 = **second;
2345
2346 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
2347 }
2348
2349 // ----------------------------------------------------------------------------
2350 // wxDateTimeHolidayAuthority
2351 // ----------------------------------------------------------------------------
2352
2353 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
2354
2355 /* static */
2356 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
2357 {
2358 size_t count = ms_authorities.size();
2359 for ( size_t n = 0; n < count; n++ )
2360 {
2361 if ( ms_authorities[n]->DoIsHoliday(dt) )
2362 {
2363 return true;
2364 }
2365 }
2366
2367 return false;
2368 }
2369
2370 /* static */
2371 size_t
2372 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
2373 const wxDateTime& dtEnd,
2374 wxDateTimeArray& holidays)
2375 {
2376 wxDateTimeArray hol;
2377
2378 holidays.Clear();
2379
2380 const size_t countAuth = ms_authorities.size();
2381 for ( size_t nAuth = 0; nAuth < countAuth; nAuth++ )
2382 {
2383 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
2384
2385 WX_APPEND_ARRAY(holidays, hol);
2386 }
2387
2388 holidays.Sort(wxDateTimeCompareFunc);
2389
2390 return holidays.size();
2391 }
2392
2393 /* static */
2394 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2395 {
2396 WX_CLEAR_ARRAY(ms_authorities);
2397 }
2398
2399 /* static */
2400 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
2401 {
2402 ms_authorities.push_back(auth);
2403 }
2404
2405 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2406 {
2407 // required here for Darwin
2408 }
2409
2410 // ----------------------------------------------------------------------------
2411 // wxDateTimeWorkDays
2412 // ----------------------------------------------------------------------------
2413
2414 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
2415 {
2416 wxDateTime::WeekDay wd = dt.GetWeekDay();
2417
2418 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
2419 }
2420
2421 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
2422 const wxDateTime& dtEnd,
2423 wxDateTimeArray& holidays) const
2424 {
2425 if ( dtStart > dtEnd )
2426 {
2427 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
2428
2429 return 0u;
2430 }
2431
2432 holidays.Empty();
2433
2434 // instead of checking all days, start with the first Sat after dtStart and
2435 // end with the last Sun before dtEnd
2436 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
2437 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
2438 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
2439 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
2440 dt;
2441
2442 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
2443 {
2444 holidays.Add(dt);
2445 }
2446
2447 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
2448 {
2449 holidays.Add(dt);
2450 }
2451
2452 return holidays.GetCount();
2453 }
2454
2455 // ============================================================================
2456 // other helper functions
2457 // ============================================================================
2458
2459 // ----------------------------------------------------------------------------
2460 // iteration helpers: can be used to write a for loop over enum variable like
2461 // this:
2462 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2463 // ----------------------------------------------------------------------------
2464
2465 WXDLLIMPEXP_BASE void wxNextMonth(wxDateTime::Month& m)
2466 {
2467 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2468
2469 // no wrapping or the for loop above would never end!
2470 m = (wxDateTime::Month)(m + 1);
2471 }
2472
2473 WXDLLIMPEXP_BASE void wxPrevMonth(wxDateTime::Month& m)
2474 {
2475 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2476
2477 m = m == wxDateTime::Jan ? wxDateTime::Inv_Month
2478 : (wxDateTime::Month)(m - 1);
2479 }
2480
2481 WXDLLIMPEXP_BASE void wxNextWDay(wxDateTime::WeekDay& wd)
2482 {
2483 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2484
2485 // no wrapping or the for loop above would never end!
2486 wd = (wxDateTime::WeekDay)(wd + 1);
2487 }
2488
2489 WXDLLIMPEXP_BASE void wxPrevWDay(wxDateTime::WeekDay& wd)
2490 {
2491 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2492
2493 wd = wd == wxDateTime::Sun ? wxDateTime::Inv_WeekDay
2494 : (wxDateTime::WeekDay)(wd - 1);
2495 }
2496
2497 #ifdef __WXMSW__
2498
2499 wxDateTime& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME& st)
2500 {
2501 return Set(st.wDay,
2502 static_cast<wxDateTime::Month>(wxDateTime::Jan + st.wMonth - 1),
2503 st.wYear,
2504 0, 0, 0);
2505 }
2506
2507 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME* st) const
2508 {
2509 const wxDateTime::Tm tm(GetTm());
2510
2511 st->wYear = (WXWORD)tm.year;
2512 st->wMonth = (WXWORD)(tm.mon - wxDateTime::Jan + 1);
2513 st->wDay = tm.mday;
2514
2515 st->wDayOfWeek =
2516 st->wHour =
2517 st->wMinute =
2518 st->wSecond =
2519 st->wMilliseconds = 0;
2520 }
2521 #endif // __WXMSW__
2522
2523 #endif // wxUSE_DATETIME