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