]> git.saurik.com Git - wxWidgets.git/blob - src/common/datetime.cpp
When saving the editable state, use the real state (m_editable)
[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 licence
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 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
67
68 #ifndef WX_PRECOMP
69 #include "wx/string.h"
70 #include "wx/log.h"
71 #endif // WX_PRECOMP
72
73 #include "wx/intl.h"
74 #include "wx/thread.h"
75 #include "wx/tokenzr.h"
76 #include "wx/module.h"
77
78 #define wxDEFINE_TIME_CONSTANTS // before including datetime.h
79
80 #include <ctype.h>
81
82 #include "wx/datetime.h"
83 #include "wx/timer.h" // for wxGetLocalTimeMillis()
84
85 const long wxDateTime::TIME_T_FACTOR = 1000l;
86
87 // ----------------------------------------------------------------------------
88 // conditional compilation
89 // ----------------------------------------------------------------------------
90
91 #if defined(HAVE_STRPTIME) && defined(__LINUX__)
92 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
93 // crash (instead of just failing):
94 //
95 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
96 // strptime(buf, "%x", &tm);
97 //
98 // so don't use it
99 #undef HAVE_STRPTIME
100 #endif // broken strptime()
101
102 #if defined(__MWERKS__) && wxUSE_UNICODE
103 #include <wtime.h>
104 #endif
105
106 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
107 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
108 #define WX_TIMEZONE _timezone
109 #elif defined(__MWERKS__)
110 long wxmw_timezone = 28800;
111 #define WX_TIMEZONE wxmw_timezone
112 #elif defined(__DJGPP__) || defined(__WINE__)
113 #include <sys/timeb.h>
114 #include <values.h>
115 static long wxGetTimeZone()
116 {
117 static long timezone = MAXLONG; // invalid timezone
118 if (timezone == MAXLONG)
119 {
120 struct timeb tb;
121 ftime(&tb);
122 timezone = tb.timezone;
123 }
124 return timezone;
125 }
126 #define WX_TIMEZONE wxGetTimeZone()
127 #elif defined(__DARWIN__)
128 #define WX_GMTOFF_IN_TM
129 #else // unknown platform - try timezone
130 #define WX_TIMEZONE timezone
131 #endif
132 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
133
134 // ----------------------------------------------------------------------------
135 // macros
136 // ----------------------------------------------------------------------------
137
138 // debugging helper: just a convenient replacement of wxCHECK()
139 #define wxDATETIME_CHECK(expr, msg) \
140 if ( !(expr) ) \
141 { \
142 wxFAIL_MSG(msg); \
143 *this = wxInvalidDateTime; \
144 return *this; \
145 }
146
147 // ----------------------------------------------------------------------------
148 // private classes
149 // ----------------------------------------------------------------------------
150
151 class wxDateTimeHolidaysModule : public wxModule
152 {
153 public:
154 virtual bool OnInit()
155 {
156 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays);
157
158 return TRUE;
159 }
160
161 virtual void OnExit()
162 {
163 wxDateTimeHolidayAuthority::ClearAllAuthorities();
164 wxDateTimeHolidayAuthority::ms_authorities.Clear();
165 }
166
167 private:
168 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule)
169 };
170
171 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule, wxModule)
172
173 // ----------------------------------------------------------------------------
174 // constants
175 // ----------------------------------------------------------------------------
176
177 // some trivial ones
178 static const int MONTHS_IN_YEAR = 12;
179
180 static const int SEC_PER_MIN = 60;
181
182 static const int MIN_PER_HOUR = 60;
183
184 static const int HOURS_PER_DAY = 24;
185
186 static const long SECONDS_PER_DAY = 86400l;
187
188 static const int DAYS_PER_WEEK = 7;
189
190 static const long MILLISECONDS_PER_DAY = 86400000l;
191
192 // this is the integral part of JDN of the midnight of Jan 1, 1970
193 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
194 static const long EPOCH_JDN = 2440587l;
195
196 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
197 // reference date for us) is Nov 24, 4714BC
198 static const int JDN_0_YEAR = -4713;
199 static const int JDN_0_MONTH = wxDateTime::Nov;
200 static const int JDN_0_DAY = 24;
201
202 // the constants used for JDN calculations
203 static const long JDN_OFFSET = 32046l;
204 static const long DAYS_PER_5_MONTHS = 153l;
205 static const long DAYS_PER_4_YEARS = 1461l;
206 static const long DAYS_PER_400_YEARS = 146097l;
207
208 // this array contains the cumulated number of days in all previous months for
209 // normal and leap years
210 static const wxDateTime::wxDateTime_t gs_cumulatedDays[2][MONTHS_IN_YEAR] =
211 {
212 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
213 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
214 };
215
216 // ----------------------------------------------------------------------------
217 // global data
218 // ----------------------------------------------------------------------------
219
220 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
221 // indicate an invalid wxDateTime object
222 const wxDateTime wxDefaultDateTime;
223
224 wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
225
226 // ----------------------------------------------------------------------------
227 // private globals
228 // ----------------------------------------------------------------------------
229
230 // a critical section is needed to protect GetTimeZone() static
231 // variable in MT case
232 #if wxUSE_THREADS
233 static wxCriticalSection gs_critsectTimezone;
234 #endif // wxUSE_THREADS
235
236 // ----------------------------------------------------------------------------
237 // private functions
238 // ----------------------------------------------------------------------------
239
240 // debugger helper: shows what the date really is
241 #ifdef __WXDEBUG__
242 extern const wxChar *wxDumpDate(const wxDateTime* dt)
243 {
244 static wxChar buf[128];
245
246 wxStrcpy(buf, dt->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
247
248 return buf;
249 }
250 #endif // Debug
251
252 // get the number of days in the given month of the given year
253 static inline
254 wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
255 {
256 // the number of days in month in Julian/Gregorian calendar: the first line
257 // is for normal years, the second one is for the leap ones
258 static wxDateTime::wxDateTime_t daysInMonth[2][MONTHS_IN_YEAR] =
259 {
260 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
261 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
262 };
263
264 return daysInMonth[wxDateTime::IsLeapYear(year)][month];
265 }
266
267 // returns the time zone in the C sense, i.e. the difference UTC - local
268 // (in seconds)
269 static int GetTimeZone()
270 {
271 // set to TRUE when the timezone is set
272 static bool s_timezoneSet = FALSE;
273 #ifdef WX_GMTOFF_IN_TM
274 static long gmtoffset = LONG_MAX; // invalid timezone
275 #endif
276
277 wxCRIT_SECT_LOCKER(lock, gs_critsectTimezone);
278
279 // ensure that the timezone variable is set by calling localtime
280 if ( !s_timezoneSet )
281 {
282 // just call localtime() instead of figuring out whether this system
283 // supports tzset(), _tzset() or something else
284 time_t t = 0;
285 struct tm *tm;
286
287 tm = localtime(&t);
288 s_timezoneSet = TRUE;
289
290 #ifdef WX_GMTOFF_IN_TM
291 // note that GMT offset is the opposite of time zone and so to return
292 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
293 // cases we have to negate it
294 gmtoffset = -tm->tm_gmtoff;
295 #endif
296 }
297
298 #ifdef WX_GMTOFF_IN_TM
299 return (int)gmtoffset;
300 #else
301 return (int)WX_TIMEZONE;
302 #endif
303 }
304
305 // return the integral part of the JDN for the midnight of the given date (to
306 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
307 // noon of the previous day)
308 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day,
309 wxDateTime::Month mon,
310 int year)
311 {
312 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
313
314 // check the date validity
315 wxASSERT_MSG(
316 (year > JDN_0_YEAR) ||
317 ((year == JDN_0_YEAR) && (mon > JDN_0_MONTH)) ||
318 ((year == JDN_0_YEAR) && (mon == JDN_0_MONTH) && (day >= JDN_0_DAY)),
319 _T("date out of range - can't convert to JDN")
320 );
321
322 // make the year positive to avoid problems with negative numbers division
323 year += 4800;
324
325 // months are counted from March here
326 int month;
327 if ( mon >= wxDateTime::Mar )
328 {
329 month = mon - 2;
330 }
331 else
332 {
333 month = mon + 10;
334 year--;
335 }
336
337 // now we can simply add all the contributions together
338 return ((year / 100) * DAYS_PER_400_YEARS) / 4
339 + ((year % 100) * DAYS_PER_4_YEARS) / 4
340 + (month * DAYS_PER_5_MONTHS + 2) / 5
341 + day
342 - JDN_OFFSET;
343 }
344
345 // this function is a wrapper around strftime(3)
346 static wxString CallStrftime(const wxChar *format, const tm* tm)
347 {
348 wxChar buf[4096];
349 if ( !wxStrftime(buf, WXSIZEOF(buf), format, tm) )
350 {
351 // buffer is too small?
352 wxFAIL_MSG(_T("strftime() failed"));
353 }
354
355 return wxString(buf);
356 }
357
358 // if year and/or month have invalid values, replace them with the current ones
359 static void ReplaceDefaultYearMonthWithCurrent(int *year,
360 wxDateTime::Month *month)
361 {
362 struct tm *tmNow = NULL;
363
364 if ( *year == wxDateTime::Inv_Year )
365 {
366 tmNow = wxDateTime::GetTmNow();
367
368 *year = 1900 + tmNow->tm_year;
369 }
370
371 if ( *month == wxDateTime::Inv_Month )
372 {
373 if ( !tmNow )
374 tmNow = wxDateTime::GetTmNow();
375
376 *month = (wxDateTime::Month)tmNow->tm_mon;
377 }
378 }
379
380 // fll the struct tm with default values
381 static void InitTm(struct tm& tm)
382 {
383 // struct tm may have etxra fields (undocumented and with unportable
384 // names) which, nevertheless, must be set to 0
385 memset(&tm, 0, sizeof(struct tm));
386
387 tm.tm_mday = 1; // mday 0 is invalid
388 tm.tm_year = 76; // any valid year
389 tm.tm_isdst = -1; // auto determine
390 }
391
392 // parsing helpers
393 // ---------------
394
395 // return the month if the string is a month name or Inv_Month otherwise
396 static wxDateTime::Month GetMonthFromName(const wxString& name, int flags)
397 {
398 wxDateTime::Month mon;
399 for ( mon = wxDateTime::Jan; mon < wxDateTime::Inv_Month; wxNextMonth(mon) )
400 {
401 // case-insensitive comparison either one of or with both abbreviated
402 // and not versions
403 if ( flags & wxDateTime::Name_Full )
404 {
405 if ( name.CmpNoCase(wxDateTime::
406 GetMonthName(mon, wxDateTime::Name_Full)) == 0 )
407 {
408 break;
409 }
410 }
411
412 if ( flags & wxDateTime::Name_Abbr )
413 {
414 if ( name.CmpNoCase(wxDateTime::
415 GetMonthName(mon, wxDateTime::Name_Abbr)) == 0 )
416 {
417 break;
418 }
419 }
420 }
421
422 return mon;
423 }
424
425 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
426 static wxDateTime::WeekDay GetWeekDayFromName(const wxString& name, int flags)
427 {
428 wxDateTime::WeekDay wd;
429 for ( wd = wxDateTime::Sun; wd < wxDateTime::Inv_WeekDay; wxNextWDay(wd) )
430 {
431 // case-insensitive comparison either one of or with both abbreviated
432 // and not versions
433 if ( flags & wxDateTime::Name_Full )
434 {
435 if ( name.CmpNoCase(wxDateTime::
436 GetWeekDayName(wd, wxDateTime::Name_Full)) == 0 )
437 {
438 break;
439 }
440 }
441
442 if ( flags & wxDateTime::Name_Abbr )
443 {
444 if ( name.CmpNoCase(wxDateTime::
445 GetWeekDayName(wd, wxDateTime::Name_Abbr)) == 0 )
446 {
447 break;
448 }
449 }
450 }
451
452 return wd;
453 }
454
455 // scans all digits (but no more than len) and returns the resulting number
456 static bool GetNumericToken(size_t len, const wxChar*& p, unsigned long *number)
457 {
458 size_t n = 1;
459 wxString s;
460 while ( wxIsdigit(*p) )
461 {
462 s += *p++;
463
464 if ( len && ++n > len )
465 break;
466 }
467
468 return !!s && s.ToULong(number);
469 }
470
471 // scans all alphabetic characters and returns the resulting string
472 static wxString GetAlphaToken(const wxChar*& p)
473 {
474 wxString s;
475 while ( wxIsalpha(*p) )
476 {
477 s += *p++;
478 }
479
480 return s;
481 }
482
483 // ============================================================================
484 // implementation of wxDateTime
485 // ============================================================================
486
487 // ----------------------------------------------------------------------------
488 // struct Tm
489 // ----------------------------------------------------------------------------
490
491 wxDateTime::Tm::Tm()
492 {
493 year = (wxDateTime_t)wxDateTime::Inv_Year;
494 mon = wxDateTime::Inv_Month;
495 mday = 0;
496 hour = min = sec = msec = 0;
497 wday = wxDateTime::Inv_WeekDay;
498 }
499
500 wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
501 : m_tz(tz)
502 {
503 msec = 0;
504 sec = tm.tm_sec;
505 min = tm.tm_min;
506 hour = tm.tm_hour;
507 mday = tm.tm_mday;
508 mon = (wxDateTime::Month)tm.tm_mon;
509 year = 1900 + tm.tm_year;
510 wday = tm.tm_wday;
511 yday = tm.tm_yday;
512 }
513
514 bool wxDateTime::Tm::IsValid() const
515 {
516 // we allow for the leap seconds, although we don't use them (yet)
517 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
518 (mday <= GetNumOfDaysInMonth(year, mon)) &&
519 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
520 }
521
522 void wxDateTime::Tm::ComputeWeekDay()
523 {
524 // compute the week day from day/month/year: we use the dumbest algorithm
525 // possible: just compute our JDN and then use the (simple to derive)
526 // formula: weekday = (JDN + 1.5) % 7
527 wday = (wxDateTime::WeekDay)(GetTruncatedJDN(mday, mon, year) + 2) % 7;
528 }
529
530 void wxDateTime::Tm::AddMonths(int monDiff)
531 {
532 // normalize the months field
533 while ( monDiff < -mon )
534 {
535 year--;
536
537 monDiff += MONTHS_IN_YEAR;
538 }
539
540 while ( monDiff + mon >= MONTHS_IN_YEAR )
541 {
542 year++;
543
544 monDiff -= MONTHS_IN_YEAR;
545 }
546
547 mon = (wxDateTime::Month)(mon + monDiff);
548
549 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
550
551 // NB: we don't check here that the resulting date is valid, this function
552 // is private and the caller must check it if needed
553 }
554
555 void wxDateTime::Tm::AddDays(int dayDiff)
556 {
557 // normalize the days field
558 while ( dayDiff + mday < 1 )
559 {
560 AddMonths(-1);
561
562 dayDiff += GetNumOfDaysInMonth(year, mon);
563 }
564
565 mday += dayDiff;
566 while ( mday > GetNumOfDaysInMonth(year, mon) )
567 {
568 mday -= GetNumOfDaysInMonth(year, mon);
569
570 AddMonths(1);
571 }
572
573 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
574 _T("logic error") );
575 }
576
577 // ----------------------------------------------------------------------------
578 // class TimeZone
579 // ----------------------------------------------------------------------------
580
581 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
582 {
583 switch ( tz )
584 {
585 case wxDateTime::Local:
586 // get the offset from C RTL: it returns the difference GMT-local
587 // while we want to have the offset _from_ GMT, hence the '-'
588 m_offset = -GetTimeZone();
589 break;
590
591 case wxDateTime::GMT_12:
592 case wxDateTime::GMT_11:
593 case wxDateTime::GMT_10:
594 case wxDateTime::GMT_9:
595 case wxDateTime::GMT_8:
596 case wxDateTime::GMT_7:
597 case wxDateTime::GMT_6:
598 case wxDateTime::GMT_5:
599 case wxDateTime::GMT_4:
600 case wxDateTime::GMT_3:
601 case wxDateTime::GMT_2:
602 case wxDateTime::GMT_1:
603 m_offset = -3600*(wxDateTime::GMT0 - tz);
604 break;
605
606 case wxDateTime::GMT0:
607 case wxDateTime::GMT1:
608 case wxDateTime::GMT2:
609 case wxDateTime::GMT3:
610 case wxDateTime::GMT4:
611 case wxDateTime::GMT5:
612 case wxDateTime::GMT6:
613 case wxDateTime::GMT7:
614 case wxDateTime::GMT8:
615 case wxDateTime::GMT9:
616 case wxDateTime::GMT10:
617 case wxDateTime::GMT11:
618 case wxDateTime::GMT12:
619 m_offset = 3600*(tz - wxDateTime::GMT0);
620 break;
621
622 case wxDateTime::A_CST:
623 // Central Standard Time in use in Australia = UTC + 9.5
624 m_offset = 60l*(9*60 + 30);
625 break;
626
627 default:
628 wxFAIL_MSG( _T("unknown time zone") );
629 }
630 }
631
632 // ----------------------------------------------------------------------------
633 // static functions
634 // ----------------------------------------------------------------------------
635
636 /* static */
637 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
638 {
639 if ( year == Inv_Year )
640 year = GetCurrentYear();
641
642 if ( cal == Gregorian )
643 {
644 // in Gregorian calendar leap years are those divisible by 4 except
645 // those divisible by 100 unless they're also divisible by 400
646 // (in some countries, like Russia and Greece, additional corrections
647 // exist, but they won't manifest themselves until 2700)
648 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
649 }
650 else if ( cal == Julian )
651 {
652 // in Julian calendar the rule is simpler
653 return year % 4 == 0;
654 }
655 else
656 {
657 wxFAIL_MSG(_T("unknown calendar"));
658
659 return FALSE;
660 }
661 }
662
663 /* static */
664 int wxDateTime::GetCentury(int year)
665 {
666 return year > 0 ? year / 100 : year / 100 - 1;
667 }
668
669 /* static */
670 int wxDateTime::ConvertYearToBC(int year)
671 {
672 // year 0 is BC 1
673 return year > 0 ? year : year - 1;
674 }
675
676 /* static */
677 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
678 {
679 switch ( cal )
680 {
681 case Gregorian:
682 return Now().GetYear();
683
684 case Julian:
685 wxFAIL_MSG(_T("TODO"));
686 break;
687
688 default:
689 wxFAIL_MSG(_T("unsupported calendar"));
690 break;
691 }
692
693 return Inv_Year;
694 }
695
696 /* static */
697 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
698 {
699 switch ( cal )
700 {
701 case Gregorian:
702 return Now().GetMonth();
703
704 case Julian:
705 wxFAIL_MSG(_T("TODO"));
706 break;
707
708 default:
709 wxFAIL_MSG(_T("unsupported calendar"));
710 break;
711 }
712
713 return Inv_Month;
714 }
715
716 /* static */
717 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
718 {
719 if ( year == Inv_Year )
720 {
721 // take the current year if none given
722 year = GetCurrentYear();
723 }
724
725 switch ( cal )
726 {
727 case Gregorian:
728 case Julian:
729 return IsLeapYear(year) ? 366 : 365;
730
731 default:
732 wxFAIL_MSG(_T("unsupported calendar"));
733 break;
734 }
735
736 return 0;
737 }
738
739 /* static */
740 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
741 int year,
742 wxDateTime::Calendar cal)
743 {
744 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
745
746 if ( cal == Gregorian || cal == Julian )
747 {
748 if ( year == Inv_Year )
749 {
750 // take the current year if none given
751 year = GetCurrentYear();
752 }
753
754 return GetNumOfDaysInMonth(year, month);
755 }
756 else
757 {
758 wxFAIL_MSG(_T("unsupported calendar"));
759
760 return 0;
761 }
762 }
763
764 /* static */
765 wxString wxDateTime::GetMonthName(wxDateTime::Month month,
766 wxDateTime::NameFlags flags)
767 {
768 wxCHECK_MSG( month != Inv_Month, _T(""), _T("invalid month") );
769
770 // notice that we must set all the fields to avoid confusing libc (GNU one
771 // gets confused to a crash if we don't do this)
772 tm tm;
773 InitTm(tm);
774 tm.tm_mon = month;
775
776 return CallStrftime(flags == Name_Abbr ? _T("%b") : _T("%B"), &tm);
777 }
778
779 /* static */
780 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday,
781 wxDateTime::NameFlags flags)
782 {
783 wxCHECK_MSG( wday != Inv_WeekDay, _T(""), _T("invalid weekday") );
784
785 // take some arbitrary Sunday
786 tm tm;
787 InitTm(tm);
788 tm.tm_mday = 28;
789 tm.tm_mon = Nov;
790 tm.tm_year = 99;
791
792 // and offset it by the number of days needed to get the correct wday
793 tm.tm_mday += wday;
794
795 // call mktime() to normalize it...
796 (void)mktime(&tm);
797
798 // ... and call strftime()
799 return CallStrftime(flags == Name_Abbr ? _T("%a") : _T("%A"), &tm);
800 }
801
802 /* static */
803 void wxDateTime::GetAmPmStrings(wxString *am, wxString *pm)
804 {
805 tm tm;
806 InitTm(tm);
807 if ( am )
808 {
809 *am = CallStrftime(_T("%p"), &tm);
810 }
811 if ( pm )
812 {
813 tm.tm_hour = 13;
814 *pm = CallStrftime(_T("%p"), &tm);
815 }
816 }
817
818 // ----------------------------------------------------------------------------
819 // Country stuff: date calculations depend on the country (DST, work days,
820 // ...), so we need to know which rules to follow.
821 // ----------------------------------------------------------------------------
822
823 /* static */
824 wxDateTime::Country wxDateTime::GetCountry()
825 {
826 // TODO use LOCALE_ICOUNTRY setting under Win32
827
828 if ( ms_country == Country_Unknown )
829 {
830 // try to guess from the time zone name
831 time_t t = time(NULL);
832 struct tm *tm = localtime(&t);
833
834 wxString tz = CallStrftime(_T("%Z"), tm);
835 if ( tz == _T("WET") || tz == _T("WEST") )
836 {
837 ms_country = UK;
838 }
839 else if ( tz == _T("CET") || tz == _T("CEST") )
840 {
841 ms_country = Country_EEC;
842 }
843 else if ( tz == _T("MSK") || tz == _T("MSD") )
844 {
845 ms_country = Russia;
846 }
847 else if ( tz == _T("AST") || tz == _T("ADT") ||
848 tz == _T("EST") || tz == _T("EDT") ||
849 tz == _T("CST") || tz == _T("CDT") ||
850 tz == _T("MST") || tz == _T("MDT") ||
851 tz == _T("PST") || tz == _T("PDT") )
852 {
853 ms_country = USA;
854 }
855 else
856 {
857 // well, choose a default one
858 ms_country = USA;
859 }
860 }
861
862 return ms_country;
863 }
864
865 /* static */
866 void wxDateTime::SetCountry(wxDateTime::Country country)
867 {
868 ms_country = country;
869 }
870
871 /* static */
872 bool wxDateTime::IsWestEuropeanCountry(Country country)
873 {
874 if ( country == Country_Default )
875 {
876 country = GetCountry();
877 }
878
879 return (Country_WesternEurope_Start <= country) &&
880 (country <= Country_WesternEurope_End);
881 }
882
883 // ----------------------------------------------------------------------------
884 // DST calculations: we use 3 different rules for the West European countries,
885 // USA and for the rest of the world. This is undoubtedly false for many
886 // countries, but I lack the necessary info (and the time to gather it),
887 // please add the other rules here!
888 // ----------------------------------------------------------------------------
889
890 /* static */
891 bool wxDateTime::IsDSTApplicable(int year, Country country)
892 {
893 if ( year == Inv_Year )
894 {
895 // take the current year if none given
896 year = GetCurrentYear();
897 }
898
899 if ( country == Country_Default )
900 {
901 country = GetCountry();
902 }
903
904 switch ( country )
905 {
906 case USA:
907 case UK:
908 // DST was first observed in the US and UK during WWI, reused
909 // during WWII and used again since 1966
910 return year >= 1966 ||
911 (year >= 1942 && year <= 1945) ||
912 (year == 1918 || year == 1919);
913
914 default:
915 // assume that it started after WWII
916 return year > 1950;
917 }
918 }
919
920 /* static */
921 wxDateTime wxDateTime::GetBeginDST(int year, Country country)
922 {
923 if ( year == Inv_Year )
924 {
925 // take the current year if none given
926 year = GetCurrentYear();
927 }
928
929 if ( country == Country_Default )
930 {
931 country = GetCountry();
932 }
933
934 if ( !IsDSTApplicable(year, country) )
935 {
936 return wxInvalidDateTime;
937 }
938
939 wxDateTime dt;
940
941 if ( IsWestEuropeanCountry(country) || (country == Russia) )
942 {
943 // DST begins at 1 a.m. GMT on the last Sunday of March
944 if ( !dt.SetToLastWeekDay(Sun, Mar, year) )
945 {
946 // weird...
947 wxFAIL_MSG( _T("no last Sunday in March?") );
948 }
949
950 dt += wxTimeSpan::Hours(1);
951
952 // disable DST tests because it could result in an infinite recursion!
953 dt.MakeGMT(TRUE);
954 }
955 else switch ( country )
956 {
957 case USA:
958 switch ( year )
959 {
960 case 1918:
961 case 1919:
962 // don't know for sure - assume it was in effect all year
963
964 case 1943:
965 case 1944:
966 case 1945:
967 dt.Set(1, Jan, year);
968 break;
969
970 case 1942:
971 // DST was installed Feb 2, 1942 by the Congress
972 dt.Set(2, Feb, year);
973 break;
974
975 // Oil embargo changed the DST period in the US
976 case 1974:
977 dt.Set(6, Jan, 1974);
978 break;
979
980 case 1975:
981 dt.Set(23, Feb, 1975);
982 break;
983
984 default:
985 // before 1986, DST begun on the last Sunday of April, but
986 // in 1986 Reagan changed it to begin at 2 a.m. of the
987 // first Sunday in April
988 if ( year < 1986 )
989 {
990 if ( !dt.SetToLastWeekDay(Sun, Apr, year) )
991 {
992 // weird...
993 wxFAIL_MSG( _T("no first Sunday in April?") );
994 }
995 }
996 else
997 {
998 if ( !dt.SetToWeekDay(Sun, 1, Apr, year) )
999 {
1000 // weird...
1001 wxFAIL_MSG( _T("no first Sunday in April?") );
1002 }
1003 }
1004
1005 dt += wxTimeSpan::Hours(2);
1006
1007 // TODO what about timezone??
1008 }
1009
1010 break;
1011
1012 default:
1013 // assume Mar 30 as the start of the DST for the rest of the world
1014 // - totally bogus, of course
1015 dt.Set(30, Mar, year);
1016 }
1017
1018 return dt;
1019 }
1020
1021 /* static */
1022 wxDateTime wxDateTime::GetEndDST(int year, Country country)
1023 {
1024 if ( year == Inv_Year )
1025 {
1026 // take the current year if none given
1027 year = GetCurrentYear();
1028 }
1029
1030 if ( country == Country_Default )
1031 {
1032 country = GetCountry();
1033 }
1034
1035 if ( !IsDSTApplicable(year, country) )
1036 {
1037 return wxInvalidDateTime;
1038 }
1039
1040 wxDateTime dt;
1041
1042 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1043 {
1044 // DST ends at 1 a.m. GMT on the last Sunday of October
1045 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1046 {
1047 // weirder and weirder...
1048 wxFAIL_MSG( _T("no last Sunday in October?") );
1049 }
1050
1051 dt += wxTimeSpan::Hours(1);
1052
1053 // disable DST tests because it could result in an infinite recursion!
1054 dt.MakeGMT(TRUE);
1055 }
1056 else switch ( country )
1057 {
1058 case USA:
1059 switch ( year )
1060 {
1061 case 1918:
1062 case 1919:
1063 // don't know for sure - assume it was in effect all year
1064
1065 case 1943:
1066 case 1944:
1067 dt.Set(31, Dec, year);
1068 break;
1069
1070 case 1945:
1071 // the time was reset after the end of the WWII
1072 dt.Set(30, Sep, year);
1073 break;
1074
1075 default:
1076 // DST ends at 2 a.m. on the last Sunday of October
1077 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1078 {
1079 // weirder and weirder...
1080 wxFAIL_MSG( _T("no last Sunday in October?") );
1081 }
1082
1083 dt += wxTimeSpan::Hours(2);
1084
1085 // TODO what about timezone??
1086 }
1087 break;
1088
1089 default:
1090 // assume October 26th as the end of the DST - totally bogus too
1091 dt.Set(26, Oct, year);
1092 }
1093
1094 return dt;
1095 }
1096
1097 // ----------------------------------------------------------------------------
1098 // constructors and assignment operators
1099 // ----------------------------------------------------------------------------
1100
1101 // return the current time with ms precision
1102 /* static */ wxDateTime wxDateTime::UNow()
1103 {
1104 return wxDateTime(wxGetLocalTimeMillis());
1105 }
1106
1107 // the values in the tm structure contain the local time
1108 wxDateTime& wxDateTime::Set(const struct tm& tm)
1109 {
1110 struct tm tm2(tm);
1111 time_t timet = mktime(&tm2);
1112
1113 if ( timet == (time_t)-1 )
1114 {
1115 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1116 // less than timezone - try to make it work for this case
1117 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
1118 {
1119 // add timezone to make sure that date is in range
1120 tm2.tm_sec -= GetTimeZone();
1121
1122 timet = mktime(&tm2);
1123 if ( timet != (time_t)-1 )
1124 {
1125 timet += GetTimeZone();
1126
1127 return Set(timet);
1128 }
1129 }
1130
1131 wxFAIL_MSG( _T("mktime() failed") );
1132
1133 *this = wxInvalidDateTime;
1134
1135 return *this;
1136 }
1137 else
1138 {
1139 return Set(timet);
1140 }
1141 }
1142
1143 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
1144 wxDateTime_t minute,
1145 wxDateTime_t second,
1146 wxDateTime_t millisec)
1147 {
1148 // we allow seconds to be 61 to account for the leap seconds, even if we
1149 // don't use them really
1150 wxDATETIME_CHECK( hour < 24 &&
1151 second < 62 &&
1152 minute < 60 &&
1153 millisec < 1000,
1154 _T("Invalid time in wxDateTime::Set()") );
1155
1156 // get the current date from system
1157 struct tm *tm = GetTmNow();
1158
1159 wxDATETIME_CHECK( tm, _T("localtime() failed") );
1160
1161 // adjust the time
1162 tm->tm_hour = hour;
1163 tm->tm_min = minute;
1164 tm->tm_sec = second;
1165
1166 (void)Set(*tm);
1167
1168 // and finally adjust milliseconds
1169 return SetMillisecond(millisec);
1170 }
1171
1172 wxDateTime& wxDateTime::Set(wxDateTime_t day,
1173 Month month,
1174 int year,
1175 wxDateTime_t hour,
1176 wxDateTime_t minute,
1177 wxDateTime_t second,
1178 wxDateTime_t millisec)
1179 {
1180 wxDATETIME_CHECK( hour < 24 &&
1181 second < 62 &&
1182 minute < 60 &&
1183 millisec < 1000,
1184 _T("Invalid time in wxDateTime::Set()") );
1185
1186 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1187
1188 wxDATETIME_CHECK( (0 < day) && (day <= GetNumberOfDays(month, year)),
1189 _T("Invalid date in wxDateTime::Set()") );
1190
1191 // the range of time_t type (inclusive)
1192 static const int yearMinInRange = 1970;
1193 static const int yearMaxInRange = 2037;
1194
1195 // test only the year instead of testing for the exact end of the Unix
1196 // time_t range - it doesn't bring anything to do more precise checks
1197 if ( year >= yearMinInRange && year <= yearMaxInRange )
1198 {
1199 // use the standard library version if the date is in range - this is
1200 // probably more efficient than our code
1201 struct tm tm;
1202 tm.tm_year = year - 1900;
1203 tm.tm_mon = month;
1204 tm.tm_mday = day;
1205 tm.tm_hour = hour;
1206 tm.tm_min = minute;
1207 tm.tm_sec = second;
1208 tm.tm_isdst = -1; // mktime() will guess it
1209
1210 (void)Set(tm);
1211
1212 // and finally adjust milliseconds
1213 return SetMillisecond(millisec);
1214 }
1215 else
1216 {
1217 // do time calculations ourselves: we want to calculate the number of
1218 // milliseconds between the given date and the epoch
1219
1220 // get the JDN for the midnight of this day
1221 m_time = GetTruncatedJDN(day, month, year);
1222 m_time -= EPOCH_JDN;
1223 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
1224
1225 // JDN corresponds to GMT, we take localtime
1226 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
1227 }
1228
1229 return *this;
1230 }
1231
1232 wxDateTime& wxDateTime::Set(double jdn)
1233 {
1234 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1235 // EPOCH_JDN + 0.5
1236 jdn -= EPOCH_JDN + 0.5;
1237
1238 jdn *= MILLISECONDS_PER_DAY;
1239
1240 m_time.Assign(jdn);
1241
1242 return *this;
1243 }
1244
1245 wxDateTime& wxDateTime::ResetTime()
1246 {
1247 Tm tm = GetTm();
1248
1249 if ( tm.hour || tm.min || tm.sec || tm.msec )
1250 {
1251 tm.msec =
1252 tm.sec =
1253 tm.min =
1254 tm.hour = 0;
1255
1256 Set(tm);
1257 }
1258
1259 return *this;
1260 }
1261
1262 // ----------------------------------------------------------------------------
1263 // DOS Date and Time Format functions
1264 // ----------------------------------------------------------------------------
1265 // the dos date and time value is an unsigned 32 bit value in the format:
1266 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1267 //
1268 // Y = year offset from 1980 (0-127)
1269 // M = month (1-12)
1270 // D = day of month (1-31)
1271 // h = hour (0-23)
1272 // m = minute (0-59)
1273 // s = bisecond (0-29) each bisecond indicates two seconds
1274 // ----------------------------------------------------------------------------
1275
1276 wxDateTime& wxDateTime::SetFromDOS(unsigned long ddt)
1277 {
1278 struct tm tm;
1279
1280 long year = ddt & 0xFE000000;
1281 year >>= 25;
1282 year += 80;
1283 tm.tm_year = year;
1284
1285 long month = ddt & 0x1E00000;
1286 month >>= 21;
1287 month -= 1;
1288 tm.tm_mon = month;
1289
1290 long day = ddt & 0x1F0000;
1291 day >>= 16;
1292 tm.tm_mday = day;
1293
1294 long hour = ddt & 0xF800;
1295 hour >>= 11;
1296 tm.tm_hour = hour;
1297
1298 long minute = ddt & 0x7E0;
1299 minute >>= 5;
1300 tm.tm_min = minute;
1301
1302 long second = ddt & 0x1F;
1303 tm.tm_sec = second * 2;
1304
1305 return Set(mktime(&tm));
1306 }
1307
1308 unsigned long wxDateTime::GetAsDOS() const
1309 {
1310 unsigned long ddt;
1311 time_t ticks = GetTicks();
1312 struct tm *tm = localtime(&ticks);
1313
1314 long year = tm->tm_year;
1315 year -= 80;
1316 year <<= 25;
1317
1318 long month = tm->tm_mon;
1319 month += 1;
1320 month <<= 21;
1321
1322 long day = tm->tm_mday;
1323 day <<= 16;
1324
1325 long hour = tm->tm_hour;
1326 hour <<= 11;
1327
1328 long minute = tm->tm_min;
1329 minute <<= 5;
1330
1331 long second = tm->tm_sec;
1332 second /= 2;
1333
1334 ddt = year | month | day | hour | minute | second;
1335 return ddt;
1336 }
1337
1338 // ----------------------------------------------------------------------------
1339 // time_t <-> broken down time conversions
1340 // ----------------------------------------------------------------------------
1341
1342 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
1343 {
1344 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1345
1346 time_t time = GetTicks();
1347 if ( time != (time_t)-1 )
1348 {
1349 // use C RTL functions
1350 tm *tm;
1351 if ( tz.GetOffset() == -GetTimeZone() )
1352 {
1353 // we are working with local time
1354 tm = localtime(&time);
1355
1356 // should never happen
1357 wxCHECK_MSG( tm, Tm(), _T("localtime() failed") );
1358 }
1359 else
1360 {
1361 time += (time_t)tz.GetOffset();
1362 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1363 int time2 = (int) time;
1364 if ( time2 >= 0 )
1365 #else
1366 if ( time >= 0 )
1367 #endif
1368 {
1369 tm = gmtime(&time);
1370
1371 // should never happen
1372 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
1373 }
1374 else
1375 {
1376 tm = (struct tm *)NULL;
1377 }
1378 }
1379
1380 if ( tm )
1381 {
1382 // adjust the milliseconds
1383 Tm tm2(*tm, tz);
1384 long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong();
1385 tm2.msec = (wxDateTime_t)(timeOnly % 1000);
1386 return tm2;
1387 }
1388 //else: use generic code below
1389 }
1390
1391 // remember the time and do the calculations with the date only - this
1392 // eliminates rounding errors of the floating point arithmetics
1393
1394 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
1395
1396 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1397
1398 // we want to always have positive time and timeMidnight to be really
1399 // the midnight before it
1400 if ( timeOnly < 0 )
1401 {
1402 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1403 }
1404
1405 timeMidnight -= timeOnly;
1406
1407 // calculate the Gregorian date from JDN for the midnight of our date:
1408 // this will yield day, month (in 1..12 range) and year
1409
1410 // actually, this is the JDN for the noon of the previous day
1411 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
1412
1413 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1414
1415 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
1416
1417 // calculate the century
1418 long temp = (jdn + JDN_OFFSET) * 4 - 1;
1419 long century = temp / DAYS_PER_400_YEARS;
1420
1421 // then the year and day of year (1 <= dayOfYear <= 366)
1422 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
1423 long year = (century * 100) + (temp / DAYS_PER_4_YEARS);
1424 long dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
1425
1426 // and finally the month and day of the month
1427 temp = dayOfYear * 5 - 3;
1428 long month = temp / DAYS_PER_5_MONTHS;
1429 long day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
1430
1431 // month is counted from March - convert to normal
1432 if ( month < 10 )
1433 {
1434 month += 3;
1435 }
1436 else
1437 {
1438 year += 1;
1439 month -= 9;
1440 }
1441
1442 // year is offset by 4800
1443 year -= 4800;
1444
1445 // check that the algorithm gave us something reasonable
1446 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
1447 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
1448
1449 // construct Tm from these values
1450 Tm tm;
1451 tm.year = (int)year;
1452 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1453 tm.mday = (wxDateTime_t)day;
1454 tm.msec = (wxDateTime_t)(timeOnly % 1000);
1455 timeOnly -= tm.msec;
1456 timeOnly /= 1000; // now we have time in seconds
1457
1458 tm.sec = (wxDateTime_t)(timeOnly % 60);
1459 timeOnly -= tm.sec;
1460 timeOnly /= 60; // now we have time in minutes
1461
1462 tm.min = (wxDateTime_t)(timeOnly % 60);
1463 timeOnly -= tm.min;
1464
1465 tm.hour = (wxDateTime_t)(timeOnly / 60);
1466
1467 return tm;
1468 }
1469
1470 wxDateTime& wxDateTime::SetYear(int year)
1471 {
1472 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1473
1474 Tm tm(GetTm());
1475 tm.year = year;
1476 Set(tm);
1477
1478 return *this;
1479 }
1480
1481 wxDateTime& wxDateTime::SetMonth(Month month)
1482 {
1483 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1484
1485 Tm tm(GetTm());
1486 tm.mon = month;
1487 Set(tm);
1488
1489 return *this;
1490 }
1491
1492 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
1493 {
1494 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1495
1496 Tm tm(GetTm());
1497 tm.mday = mday;
1498 Set(tm);
1499
1500 return *this;
1501 }
1502
1503 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
1504 {
1505 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1506
1507 Tm tm(GetTm());
1508 tm.hour = hour;
1509 Set(tm);
1510
1511 return *this;
1512 }
1513
1514 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
1515 {
1516 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1517
1518 Tm tm(GetTm());
1519 tm.min = min;
1520 Set(tm);
1521
1522 return *this;
1523 }
1524
1525 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
1526 {
1527 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1528
1529 Tm tm(GetTm());
1530 tm.sec = sec;
1531 Set(tm);
1532
1533 return *this;
1534 }
1535
1536 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
1537 {
1538 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1539
1540 // we don't need to use GetTm() for this one
1541 m_time -= m_time % 1000l;
1542 m_time += millisecond;
1543
1544 return *this;
1545 }
1546
1547 // ----------------------------------------------------------------------------
1548 // wxDateTime arithmetics
1549 // ----------------------------------------------------------------------------
1550
1551 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
1552 {
1553 Tm tm(GetTm());
1554
1555 tm.year += diff.GetYears();
1556 tm.AddMonths(diff.GetMonths());
1557
1558 // check that the resulting date is valid
1559 if ( tm.mday > GetNumOfDaysInMonth(tm.year, tm.mon) )
1560 {
1561 // We suppose that when adding one month to Jan 31 we want to get Feb
1562 // 28 (or 29), i.e. adding a month to the last day of the month should
1563 // give the last day of the next month which is quite logical.
1564 //
1565 // Unfortunately, there is no logic way to understand what should
1566 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1567 // We make it Feb 28 (last day too), but it is highly questionable.
1568 tm.mday = GetNumOfDaysInMonth(tm.year, tm.mon);
1569 }
1570
1571 tm.AddDays(diff.GetTotalDays());
1572
1573 Set(tm);
1574
1575 wxASSERT_MSG( IsSameTime(tm),
1576 _T("Add(wxDateSpan) shouldn't modify time") );
1577
1578 return *this;
1579 }
1580
1581 // ----------------------------------------------------------------------------
1582 // Weekday and monthday stuff
1583 // ----------------------------------------------------------------------------
1584
1585 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek,
1586 WeekDay weekday,
1587 WeekFlags flags)
1588 {
1589 wxASSERT_MSG( numWeek > 0,
1590 _T("invalid week number: weeks are counted from 1") );
1591
1592 int year = GetYear();
1593
1594 // Jan 4 always lies in the 1st week of the year
1595 Set(4, Jan, year);
1596 SetToWeekDayInSameWeek(weekday, flags) += wxDateSpan::Weeks(numWeek - 1);
1597
1598 if ( GetYear() != year )
1599 {
1600 // oops... numWeek was too big
1601 return FALSE;
1602 }
1603
1604 return TRUE;
1605 }
1606
1607 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
1608 int year)
1609 {
1610 // take the current month/year if none specified
1611 if ( year == Inv_Year )
1612 year = GetYear();
1613 if ( month == Inv_Month )
1614 month = GetMonth();
1615
1616 return Set(GetNumOfDaysInMonth(year, month), month, year);
1617 }
1618
1619 wxDateTime& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday, WeekFlags flags)
1620 {
1621 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1622
1623 int wdayThis = GetWeekDay();
1624 if ( weekday == wdayThis )
1625 {
1626 // nothing to do
1627 return *this;
1628 }
1629
1630 if ( flags == Default_First )
1631 {
1632 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1633 }
1634
1635 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1636 // is the first day in the week, but breaks down for Monday_First case so
1637 // we adjust the week days in this case
1638 if( flags == Monday_First )
1639 {
1640 if ( wdayThis == Sun )
1641 wdayThis += 7;
1642 }
1643 //else: Sunday_First, nothing to do
1644
1645 // go forward or back in time to the day we want
1646 if ( weekday < wdayThis )
1647 {
1648 return Subtract(wxDateSpan::Days(wdayThis - weekday));
1649 }
1650 else // weekday > wdayThis
1651 {
1652 return Add(wxDateSpan::Days(weekday - wdayThis));
1653 }
1654 }
1655
1656 wxDateTime& wxDateTime::SetToNextWeekDay(WeekDay weekday)
1657 {
1658 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1659
1660 int diff;
1661 WeekDay wdayThis = GetWeekDay();
1662 if ( weekday == wdayThis )
1663 {
1664 // nothing to do
1665 return *this;
1666 }
1667 else if ( weekday < wdayThis )
1668 {
1669 // need to advance a week
1670 diff = 7 - (wdayThis - weekday);
1671 }
1672 else // weekday > wdayThis
1673 {
1674 diff = weekday - wdayThis;
1675 }
1676
1677 return Add(wxDateSpan::Days(diff));
1678 }
1679
1680 wxDateTime& wxDateTime::SetToPrevWeekDay(WeekDay weekday)
1681 {
1682 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
1683
1684 int diff;
1685 WeekDay wdayThis = GetWeekDay();
1686 if ( weekday == wdayThis )
1687 {
1688 // nothing to do
1689 return *this;
1690 }
1691 else if ( weekday > wdayThis )
1692 {
1693 // need to go to previous week
1694 diff = 7 - (weekday - wdayThis);
1695 }
1696 else // weekday < wdayThis
1697 {
1698 diff = wdayThis - weekday;
1699 }
1700
1701 return Subtract(wxDateSpan::Days(diff));
1702 }
1703
1704 bool wxDateTime::SetToWeekDay(WeekDay weekday,
1705 int n,
1706 Month month,
1707 int year)
1708 {
1709 wxCHECK_MSG( weekday != Inv_WeekDay, FALSE, _T("invalid weekday") );
1710
1711 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1712 // anyhow in such case - but may be should still give an assert for it?
1713
1714 // take the current month/year if none specified
1715 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1716
1717 wxDateTime dt;
1718
1719 // TODO this probably could be optimised somehow...
1720
1721 if ( n > 0 )
1722 {
1723 // get the first day of the month
1724 dt.Set(1, month, year);
1725
1726 // get its wday
1727 WeekDay wdayFirst = dt.GetWeekDay();
1728
1729 // go to the first weekday of the month
1730 int diff = weekday - wdayFirst;
1731 if ( diff < 0 )
1732 diff += 7;
1733
1734 // add advance n-1 weeks more
1735 diff += 7*(n - 1);
1736
1737 dt += wxDateSpan::Days(diff);
1738 }
1739 else // count from the end of the month
1740 {
1741 // get the last day of the month
1742 dt.SetToLastMonthDay(month, year);
1743
1744 // get its wday
1745 WeekDay wdayLast = dt.GetWeekDay();
1746
1747 // go to the last weekday of the month
1748 int diff = wdayLast - weekday;
1749 if ( diff < 0 )
1750 diff += 7;
1751
1752 // and rewind n-1 weeks from there
1753 diff += 7*(-n - 1);
1754
1755 dt -= wxDateSpan::Days(diff);
1756 }
1757
1758 // check that it is still in the same month
1759 if ( dt.GetMonth() == month )
1760 {
1761 *this = dt;
1762
1763 return TRUE;
1764 }
1765 else
1766 {
1767 // no such day in this month
1768 return FALSE;
1769 }
1770 }
1771
1772 wxDateTime::wxDateTime_t wxDateTime::GetDayOfYear(const TimeZone& tz) const
1773 {
1774 Tm tm(GetTm(tz));
1775
1776 return gs_cumulatedDays[IsLeapYear(tm.year)][tm.mon] + tm.mday;
1777 }
1778
1779 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags,
1780 const TimeZone& tz) const
1781 {
1782 if ( flags == Default_First )
1783 {
1784 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1785 }
1786
1787 wxDateTime_t nDayInYear = GetDayOfYear(tz);
1788 wxDateTime_t week;
1789
1790 WeekDay wd = GetWeekDay(tz);
1791 if ( flags == Sunday_First )
1792 {
1793 week = (nDayInYear - wd + 7) / 7;
1794 }
1795 else
1796 {
1797 // have to shift the week days values
1798 week = (nDayInYear - (wd - 1 + 7) % 7 + 7) / 7;
1799 }
1800
1801 // FIXME some more elegant way??
1802 WeekDay wdYearStart = wxDateTime(1, Jan, GetYear()).GetWeekDay();
1803 if ( wdYearStart == Wed || wdYearStart == Thu )
1804 {
1805 week++;
1806 }
1807
1808 return week;
1809 }
1810
1811 wxDateTime::wxDateTime_t wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags,
1812 const TimeZone& tz) const
1813 {
1814 Tm tm = GetTm(tz);
1815 wxDateTime dtMonthStart = wxDateTime(1, tm.mon, tm.year);
1816 int nWeek = GetWeekOfYear(flags) - dtMonthStart.GetWeekOfYear(flags) + 1;
1817 if ( nWeek < 0 )
1818 {
1819 // this may happen for January when Jan, 1 is the last week of the
1820 // previous year
1821 nWeek += IsLeapYear(tm.year - 1) ? 53 : 52;
1822 }
1823
1824 return (wxDateTime::wxDateTime_t)nWeek;
1825 }
1826
1827 wxDateTime& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday)
1828 {
1829 int year = GetYear();
1830 wxDATETIME_CHECK( (0 < yday) && (yday <= GetNumberOfDays(year)),
1831 _T("invalid year day") );
1832
1833 bool isLeap = IsLeapYear(year);
1834 for ( Month mon = Jan; mon < Inv_Month; wxNextMonth(mon) )
1835 {
1836 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1837 // don't need it neither - because of the CHECK above we know that
1838 // yday lies in December then
1839 if ( (mon == Dec) || (yday < gs_cumulatedDays[isLeap][mon + 1]) )
1840 {
1841 Set(yday - gs_cumulatedDays[isLeap][mon], mon, year);
1842
1843 break;
1844 }
1845 }
1846
1847 return *this;
1848 }
1849
1850 // ----------------------------------------------------------------------------
1851 // Julian day number conversion and related stuff
1852 // ----------------------------------------------------------------------------
1853
1854 double wxDateTime::GetJulianDayNumber() const
1855 {
1856 // JDN are always expressed for the GMT dates
1857 Tm tm(ToTimezone(GMT0).GetTm(GMT0));
1858
1859 double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
1860
1861 // add the part GetTruncatedJDN() neglected
1862 result += 0.5;
1863
1864 // and now add the time: 86400 sec = 1 JDN
1865 return result + ((double)(60*(60*tm.hour + tm.min) + tm.sec)) / 86400;
1866 }
1867
1868 double wxDateTime::GetRataDie() const
1869 {
1870 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1871 return GetJulianDayNumber() - 1721119.5 - 306;
1872 }
1873
1874 // ----------------------------------------------------------------------------
1875 // timezone and DST stuff
1876 // ----------------------------------------------------------------------------
1877
1878 int wxDateTime::IsDST(wxDateTime::Country country) const
1879 {
1880 wxCHECK_MSG( country == Country_Default, -1,
1881 _T("country support not implemented") );
1882
1883 // use the C RTL for the dates in the standard range
1884 time_t timet = GetTicks();
1885 if ( timet != (time_t)-1 )
1886 {
1887 tm *tm = localtime(&timet);
1888
1889 wxCHECK_MSG( tm, -1, _T("localtime() failed") );
1890
1891 return tm->tm_isdst;
1892 }
1893 else
1894 {
1895 int year = GetYear();
1896
1897 if ( !IsDSTApplicable(year, country) )
1898 {
1899 // no DST time in this year in this country
1900 return -1;
1901 }
1902
1903 return IsBetween(GetBeginDST(year, country), GetEndDST(year, country));
1904 }
1905 }
1906
1907 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz, bool noDST)
1908 {
1909 long secDiff = GetTimeZone() + tz.GetOffset();
1910
1911 // we need to know whether DST is or not in effect for this date unless
1912 // the test disabled by the caller
1913 if ( !noDST && (IsDST() == 1) )
1914 {
1915 // FIXME we assume that the DST is always shifted by 1 hour
1916 secDiff -= 3600;
1917 }
1918
1919 return Subtract(wxTimeSpan::Seconds(secDiff));
1920 }
1921
1922 // ----------------------------------------------------------------------------
1923 // wxDateTime to/from text representations
1924 // ----------------------------------------------------------------------------
1925
1926 wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
1927 {
1928 wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
1929
1930 // we have to use our own implementation if the date is out of range of
1931 // strftime() or if we use non standard specificators
1932 time_t time = GetTicks();
1933 if ( (time != (time_t)-1) && !wxStrstr(format, _T("%l")) )
1934 {
1935 // use strftime()
1936 tm *tm;
1937 if ( tz.GetOffset() == -GetTimeZone() )
1938 {
1939 // we are working with local time
1940 tm = localtime(&time);
1941
1942 // should never happen
1943 wxCHECK_MSG( tm, wxEmptyString, _T("localtime() failed") );
1944 }
1945 else
1946 {
1947 time += (int)tz.GetOffset();
1948
1949 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1950 int time2 = (int) time;
1951 if ( time2 >= 0 )
1952 #else
1953 if ( time >= 0 )
1954 #endif
1955 {
1956 tm = gmtime(&time);
1957
1958 // should never happen
1959 wxCHECK_MSG( tm, wxEmptyString, _T("gmtime() failed") );
1960 }
1961 else
1962 {
1963 tm = (struct tm *)NULL;
1964 }
1965 }
1966
1967 if ( tm )
1968 {
1969 return CallStrftime(format, tm);
1970 }
1971 //else: use generic code below
1972 }
1973
1974 // we only parse ANSI C format specifications here, no POSIX 2
1975 // complications, no GNU extensions but we do add support for a "%l" format
1976 // specifier allowing to get the number of milliseconds
1977 Tm tm = GetTm(tz);
1978
1979 // used for calls to strftime() when we only deal with time
1980 struct tm tmTimeOnly;
1981 tmTimeOnly.tm_hour = tm.hour;
1982 tmTimeOnly.tm_min = tm.min;
1983 tmTimeOnly.tm_sec = tm.sec;
1984 tmTimeOnly.tm_wday = 0;
1985 tmTimeOnly.tm_yday = 0;
1986 tmTimeOnly.tm_mday = 1; // any date will do
1987 tmTimeOnly.tm_mon = 0;
1988 tmTimeOnly.tm_year = 76;
1989 tmTimeOnly.tm_isdst = 0; // no DST, we adjust for tz ourselves
1990
1991 wxString tmp, res, fmt;
1992 for ( const wxChar *p = format; *p; p++ )
1993 {
1994 if ( *p != _T('%') )
1995 {
1996 // copy as is
1997 res += *p;
1998
1999 continue;
2000 }
2001
2002 // set the default format
2003 switch ( *++p )
2004 {
2005 case _T('Y'): // year has 4 digits
2006 fmt = _T("%04d");
2007 break;
2008
2009 case _T('j'): // day of year has 3 digits
2010 case _T('l'): // milliseconds have 3 digits
2011 fmt = _T("%03d");
2012 break;
2013
2014 case _T('w'): // week day as number has only one
2015 fmt = _T("%d");
2016 break;
2017
2018 default:
2019 // it's either another valid format specifier in which case
2020 // the format is "%02d" (for all the rest) or we have the
2021 // field width preceding the format in which case it will
2022 // override the default format anyhow
2023 fmt = _T("%02d");
2024 }
2025
2026 bool restart = TRUE;
2027 while ( restart )
2028 {
2029 restart = FALSE;
2030
2031 // start of the format specification
2032 switch ( *p )
2033 {
2034 case _T('a'): // a weekday name
2035 case _T('A'):
2036 // second parameter should be TRUE for abbreviated names
2037 res += GetWeekDayName(tm.GetWeekDay(),
2038 *p == _T('a') ? Name_Abbr : Name_Full);
2039 break;
2040
2041 case _T('b'): // a month name
2042 case _T('B'):
2043 res += GetMonthName(tm.mon,
2044 *p == _T('b') ? Name_Abbr : Name_Full);
2045 break;
2046
2047 case _T('c'): // locale default date and time representation
2048 case _T('x'): // locale default date representation
2049 //
2050 // the problem: there is no way to know what do these format
2051 // specifications correspond to for the current locale.
2052 //
2053 // the solution: use a hack and still use strftime(): first
2054 // find the YEAR which is a year in the strftime() range (1970
2055 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
2056 // of the real year. Then make a copy of the format and
2057 // replace all occurences of YEAR in it with some unique
2058 // string not appearing anywhere else in it, then use
2059 // strftime() to format the date in year YEAR and then replace
2060 // YEAR back by the real year and the unique replacement
2061 // string back with YEAR. Notice that "all occurences of YEAR"
2062 // means all occurences of 4 digit as well as 2 digit form!
2063 //
2064 // the bugs: we assume that neither of %c nor %x contains any
2065 // fields which may change between the YEAR and real year. For
2066 // example, the week number (%U, %W) and the day number (%j)
2067 // will change if one of these years is leap and the other one
2068 // is not!
2069 {
2070 // find the YEAR: normally, for any year X, Jan 1 or the
2071 // year X + 28 is the same weekday as Jan 1 of X (because
2072 // the weekday advances by 1 for each normal X and by 2
2073 // for each leap X, hence by 5 every 4 years or by 35
2074 // which is 0 mod 7 every 28 years) but this rule breaks
2075 // down if there are years between X and Y which are
2076 // divisible by 4 but not leap (i.e. divisible by 100 but
2077 // not 400), hence the correction.
2078
2079 int yearReal = GetYear(tz);
2080 int mod28 = yearReal % 28;
2081
2082 // be careful to not go too far - we risk to leave the
2083 // supported range
2084 int year;
2085 if ( mod28 < 10 )
2086 {
2087 year = 1988 + mod28; // 1988 == 0 (mod 28)
2088 }
2089 else
2090 {
2091 year = 1970 + mod28 - 10; // 1970 == 10 (mod 28)
2092 }
2093
2094 int nCentury = year / 100,
2095 nCenturyReal = yearReal / 100;
2096
2097 // need to adjust for the years divisble by 400 which are
2098 // not leap but are counted like leap ones if we just take
2099 // the number of centuries in between for nLostWeekDays
2100 int nLostWeekDays = (nCentury - nCenturyReal) -
2101 (nCentury / 4 - nCenturyReal / 4);
2102
2103 // we have to gain back the "lost" weekdays: note that the
2104 // effect of this loop is to not do anything to
2105 // nLostWeekDays (which we won't use any more), but to
2106 // (indirectly) set the year correctly
2107 while ( (nLostWeekDays % 7) != 0 )
2108 {
2109 nLostWeekDays += year++ % 4 ? 1 : 2;
2110 }
2111
2112 // at any rate, we couldn't go further than 1988 + 9 + 28!
2113 wxASSERT_MSG( year < 2030,
2114 _T("logic error in wxDateTime::Format") );
2115
2116 wxString strYear, strYear2;
2117 strYear.Printf(_T("%d"), year);
2118 strYear2.Printf(_T("%d"), year % 100);
2119
2120 // find two strings not occuring in format (this is surely
2121 // not optimal way of doing it... improvements welcome!)
2122 wxString fmt = format;
2123 wxString replacement = (wxChar)-1;
2124 while ( fmt.Find(replacement) != wxNOT_FOUND )
2125 {
2126 replacement << (wxChar)-1;
2127 }
2128
2129 wxString replacement2 = (wxChar)-2;
2130 while ( fmt.Find(replacement) != wxNOT_FOUND )
2131 {
2132 replacement << (wxChar)-2;
2133 }
2134
2135 // replace all occurences of year with it
2136 bool wasReplaced = fmt.Replace(strYear, replacement) > 0;
2137 if ( !wasReplaced )
2138 wasReplaced = fmt.Replace(strYear2, replacement2) > 0;
2139
2140 // use strftime() to format the same date but in supported
2141 // year
2142 //
2143 // NB: we assume that strftime() doesn't check for the
2144 // date validity and will happily format the date
2145 // corresponding to Feb 29 of a non leap year (which
2146 // may happen if yearReal was leap and year is not)
2147 struct tm tmAdjusted;
2148 InitTm(tmAdjusted);
2149 tmAdjusted.tm_hour = tm.hour;
2150 tmAdjusted.tm_min = tm.min;
2151 tmAdjusted.tm_sec = tm.sec;
2152 tmAdjusted.tm_wday = tm.GetWeekDay();
2153 tmAdjusted.tm_yday = GetDayOfYear();
2154 tmAdjusted.tm_mday = tm.mday;
2155 tmAdjusted.tm_mon = tm.mon;
2156 tmAdjusted.tm_year = year - 1900;
2157 tmAdjusted.tm_isdst = 0; // no DST, already adjusted
2158 wxString str = CallStrftime(*p == _T('c') ? _T("%c")
2159 : _T("%x"),
2160 &tmAdjusted);
2161
2162 // now replace the occurence of 1999 with the real year
2163 wxString strYearReal, strYearReal2;
2164 strYearReal.Printf(_T("%04d"), yearReal);
2165 strYearReal2.Printf(_T("%02d"), yearReal % 100);
2166 str.Replace(strYear, strYearReal);
2167 str.Replace(strYear2, strYearReal2);
2168
2169 // and replace back all occurences of replacement string
2170 if ( wasReplaced )
2171 {
2172 str.Replace(replacement2, strYear2);
2173 str.Replace(replacement, strYear);
2174 }
2175
2176 res += str;
2177 }
2178 break;
2179
2180 case _T('d'): // day of a month (01-31)
2181 res += wxString::Format(fmt, tm.mday);
2182 break;
2183
2184 case _T('H'): // hour in 24h format (00-23)
2185 res += wxString::Format(fmt, tm.hour);
2186 break;
2187
2188 case _T('I'): // hour in 12h format (01-12)
2189 {
2190 // 24h -> 12h, 0h -> 12h too
2191 int hour12 = tm.hour > 12 ? tm.hour - 12
2192 : tm.hour ? tm.hour : 12;
2193 res += wxString::Format(fmt, hour12);
2194 }
2195 break;
2196
2197 case _T('j'): // day of the year
2198 res += wxString::Format(fmt, GetDayOfYear(tz));
2199 break;
2200
2201 case _T('l'): // milliseconds (NOT STANDARD)
2202 res += wxString::Format(fmt, GetMillisecond(tz));
2203 break;
2204
2205 case _T('m'): // month as a number (01-12)
2206 res += wxString::Format(fmt, tm.mon + 1);
2207 break;
2208
2209 case _T('M'): // minute as a decimal number (00-59)
2210 res += wxString::Format(fmt, tm.min);
2211 break;
2212
2213 case _T('p'): // AM or PM string
2214 res += CallStrftime(_T("%p"), &tmTimeOnly);
2215 break;
2216
2217 case _T('S'): // second as a decimal number (00-61)
2218 res += wxString::Format(fmt, tm.sec);
2219 break;
2220
2221 case _T('U'): // week number in the year (Sunday 1st week day)
2222 res += wxString::Format(fmt, GetWeekOfYear(Sunday_First, tz));
2223 break;
2224
2225 case _T('W'): // week number in the year (Monday 1st week day)
2226 res += wxString::Format(fmt, GetWeekOfYear(Monday_First, tz));
2227 break;
2228
2229 case _T('w'): // weekday as a number (0-6), Sunday = 0
2230 res += wxString::Format(fmt, tm.GetWeekDay());
2231 break;
2232
2233 // case _T('x'): -- handled with "%c"
2234
2235 case _T('X'): // locale default time representation
2236 // just use strftime() to format the time for us
2237 res += CallStrftime(_T("%X"), &tmTimeOnly);
2238 break;
2239
2240 case _T('y'): // year without century (00-99)
2241 res += wxString::Format(fmt, tm.year % 100);
2242 break;
2243
2244 case _T('Y'): // year with century
2245 res += wxString::Format(fmt, tm.year);
2246 break;
2247
2248 case _T('Z'): // timezone name
2249 res += CallStrftime(_T("%Z"), &tmTimeOnly);
2250 break;
2251
2252 default:
2253 // is it the format width?
2254 fmt.Empty();
2255 while ( *p == _T('-') || *p == _T('+') ||
2256 *p == _T(' ') || wxIsdigit(*p) )
2257 {
2258 fmt += *p;
2259 }
2260
2261 if ( !fmt.IsEmpty() )
2262 {
2263 // we've only got the flags and width so far in fmt
2264 fmt.Prepend(_T('%'));
2265 fmt.Append(_T('d'));
2266
2267 restart = TRUE;
2268
2269 break;
2270 }
2271
2272 // no, it wasn't the width
2273 wxFAIL_MSG(_T("unknown format specificator"));
2274
2275 // fall through and just copy it nevertheless
2276
2277 case _T('%'): // a percent sign
2278 res += *p;
2279 break;
2280
2281 case 0: // the end of string
2282 wxFAIL_MSG(_T("missing format at the end of string"));
2283
2284 // just put the '%' which was the last char in format
2285 res += _T('%');
2286 break;
2287 }
2288 }
2289 }
2290
2291 return res;
2292 }
2293
2294 // this function parses a string in (strict) RFC 822 format: see the section 5
2295 // of the RFC for the detailed description, but briefly it's something of the
2296 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2297 //
2298 // this function is "strict" by design - it must reject anything except true
2299 // RFC822 time specs.
2300 //
2301 // TODO a great candidate for using reg exps
2302 const wxChar *wxDateTime::ParseRfc822Date(const wxChar* date)
2303 {
2304 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
2305
2306 const wxChar *p = date;
2307 const wxChar *comma = wxStrchr(p, _T(','));
2308 if ( comma )
2309 {
2310 // the part before comma is the weekday
2311
2312 // skip it for now - we don't use but might check that it really
2313 // corresponds to the specfied date
2314 p = comma + 1;
2315
2316 if ( *p != _T(' ') )
2317 {
2318 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2319
2320 return (wxChar *)NULL;
2321 }
2322
2323 p++; // skip space
2324 }
2325
2326 // the following 1 or 2 digits are the day number
2327 if ( !wxIsdigit(*p) )
2328 {
2329 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2330
2331 return (wxChar *)NULL;
2332 }
2333
2334 wxDateTime_t day = *p++ - _T('0');
2335 if ( wxIsdigit(*p) )
2336 {
2337 day *= 10;
2338 day += *p++ - _T('0');
2339 }
2340
2341 if ( *p++ != _T(' ') )
2342 {
2343 return (wxChar *)NULL;
2344 }
2345
2346 // the following 3 letters specify the month
2347 wxString monName(p, 3);
2348 Month mon;
2349 if ( monName == _T("Jan") )
2350 mon = Jan;
2351 else if ( monName == _T("Feb") )
2352 mon = Feb;
2353 else if ( monName == _T("Mar") )
2354 mon = Mar;
2355 else if ( monName == _T("Apr") )
2356 mon = Apr;
2357 else if ( monName == _T("May") )
2358 mon = May;
2359 else if ( monName == _T("Jun") )
2360 mon = Jun;
2361 else if ( monName == _T("Jul") )
2362 mon = Jul;
2363 else if ( monName == _T("Aug") )
2364 mon = Aug;
2365 else if ( monName == _T("Sep") )
2366 mon = Sep;
2367 else if ( monName == _T("Oct") )
2368 mon = Oct;
2369 else if ( monName == _T("Nov") )
2370 mon = Nov;
2371 else if ( monName == _T("Dec") )
2372 mon = Dec;
2373 else
2374 {
2375 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName.c_str());
2376
2377 return (wxChar *)NULL;
2378 }
2379
2380 p += 3;
2381
2382 if ( *p++ != _T(' ') )
2383 {
2384 return (wxChar *)NULL;
2385 }
2386
2387 // next is the year
2388 if ( !wxIsdigit(*p) )
2389 {
2390 // no year?
2391 return (wxChar *)NULL;
2392 }
2393
2394 int year = *p++ - _T('0');
2395
2396 if ( !wxIsdigit(*p) )
2397 {
2398 // should have at least 2 digits in the year
2399 return (wxChar *)NULL;
2400 }
2401
2402 year *= 10;
2403 year += *p++ - _T('0');
2404
2405 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2406 if ( wxIsdigit(*p) )
2407 {
2408 year *= 10;
2409 year += *p++ - _T('0');
2410
2411 if ( !wxIsdigit(*p) )
2412 {
2413 // no 3 digit years please
2414 return (wxChar *)NULL;
2415 }
2416
2417 year *= 10;
2418 year += *p++ - _T('0');
2419 }
2420
2421 if ( *p++ != _T(' ') )
2422 {
2423 return (wxChar *)NULL;
2424 }
2425
2426 // time is in the format hh:mm:ss and seconds are optional
2427 if ( !wxIsdigit(*p) )
2428 {
2429 return (wxChar *)NULL;
2430 }
2431
2432 wxDateTime_t hour = *p++ - _T('0');
2433
2434 if ( !wxIsdigit(*p) )
2435 {
2436 return (wxChar *)NULL;
2437 }
2438
2439 hour *= 10;
2440 hour += *p++ - _T('0');
2441
2442 if ( *p++ != _T(':') )
2443 {
2444 return (wxChar *)NULL;
2445 }
2446
2447 if ( !wxIsdigit(*p) )
2448 {
2449 return (wxChar *)NULL;
2450 }
2451
2452 wxDateTime_t min = *p++ - _T('0');
2453
2454 if ( !wxIsdigit(*p) )
2455 {
2456 return (wxChar *)NULL;
2457 }
2458
2459 min *= 10;
2460 min += *p++ - _T('0');
2461
2462 wxDateTime_t sec = 0;
2463 if ( *p++ == _T(':') )
2464 {
2465 if ( !wxIsdigit(*p) )
2466 {
2467 return (wxChar *)NULL;
2468 }
2469
2470 sec = *p++ - _T('0');
2471
2472 if ( !wxIsdigit(*p) )
2473 {
2474 return (wxChar *)NULL;
2475 }
2476
2477 sec *= 10;
2478 sec += *p++ - _T('0');
2479 }
2480
2481 if ( *p++ != _T(' ') )
2482 {
2483 return (wxChar *)NULL;
2484 }
2485
2486 // and now the interesting part: the timezone
2487 int offset;
2488 if ( *p == _T('-') || *p == _T('+') )
2489 {
2490 // the explicit offset given: it has the form of hhmm
2491 bool plus = *p++ == _T('+');
2492
2493 if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
2494 {
2495 return (wxChar *)NULL;
2496 }
2497
2498 // hours
2499 offset = 60*(10*(*p - _T('0')) + (*(p + 1) - _T('0')));
2500
2501 p += 2;
2502
2503 if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
2504 {
2505 return (wxChar *)NULL;
2506 }
2507
2508 // minutes
2509 offset += 10*(*p - _T('0')) + (*(p + 1) - _T('0'));
2510
2511 if ( !plus )
2512 {
2513 offset = -offset;
2514 }
2515
2516 p += 2;
2517 }
2518 else
2519 {
2520 // the symbolic timezone given: may be either military timezone or one
2521 // of standard abbreviations
2522 if ( !*(p + 1) )
2523 {
2524 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2525 static const int offsets[26] =
2526 {
2527 //A B C D E F G H I J K L M
2528 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2529 //N O P R Q S T U V W Z Y Z
2530 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2531 };
2532
2533 if ( *p < _T('A') || *p > _T('Z') || *p == _T('J') )
2534 {
2535 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p);
2536
2537 return (wxChar *)NULL;
2538 }
2539
2540 offset = offsets[*p++ - _T('A')];
2541 }
2542 else
2543 {
2544 // abbreviation
2545 wxString tz = p;
2546 if ( tz == _T("UT") || tz == _T("UTC") || tz == _T("GMT") )
2547 offset = 0;
2548 else if ( tz == _T("AST") )
2549 offset = AST - GMT0;
2550 else if ( tz == _T("ADT") )
2551 offset = ADT - GMT0;
2552 else if ( tz == _T("EST") )
2553 offset = EST - GMT0;
2554 else if ( tz == _T("EDT") )
2555 offset = EDT - GMT0;
2556 else if ( tz == _T("CST") )
2557 offset = CST - GMT0;
2558 else if ( tz == _T("CDT") )
2559 offset = CDT - GMT0;
2560 else if ( tz == _T("MST") )
2561 offset = MST - GMT0;
2562 else if ( tz == _T("MDT") )
2563 offset = MDT - GMT0;
2564 else if ( tz == _T("PST") )
2565 offset = PST - GMT0;
2566 else if ( tz == _T("PDT") )
2567 offset = PDT - GMT0;
2568 else
2569 {
2570 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p);
2571
2572 return (wxChar *)NULL;
2573 }
2574
2575 p += tz.length();
2576 }
2577
2578 // make it minutes
2579 offset *= 60;
2580 }
2581
2582 // the spec was correct
2583 Set(day, mon, year, hour, min, sec);
2584 MakeTimezone((wxDateTime_t)(60*offset));
2585
2586 return p;
2587 }
2588
2589 const wxChar *wxDateTime::ParseFormat(const wxChar *date,
2590 const wxChar *format,
2591 const wxDateTime& dateDef)
2592 {
2593 wxCHECK_MSG( date && format, (wxChar *)NULL,
2594 _T("NULL pointer in wxDateTime::ParseFormat()") );
2595
2596 wxString str;
2597 unsigned long num;
2598
2599 // what fields have we found?
2600 bool haveWDay = FALSE,
2601 haveYDay = FALSE,
2602 haveDay = FALSE,
2603 haveMon = FALSE,
2604 haveYear = FALSE,
2605 haveHour = FALSE,
2606 haveMin = FALSE,
2607 haveSec = FALSE;
2608
2609 bool hourIsIn12hFormat = FALSE, // or in 24h one?
2610 isPM = FALSE; // AM by default
2611
2612 // and the value of the items we have (init them to get rid of warnings)
2613 wxDateTime_t sec = 0,
2614 min = 0,
2615 hour = 0;
2616 WeekDay wday = Inv_WeekDay;
2617 wxDateTime_t yday = 0,
2618 mday = 0;
2619 wxDateTime::Month mon = Inv_Month;
2620 int year = 0;
2621
2622 const wxChar *input = date;
2623 for ( const wxChar *fmt = format; *fmt; fmt++ )
2624 {
2625 if ( *fmt != _T('%') )
2626 {
2627 if ( wxIsspace(*fmt) )
2628 {
2629 // a white space in the format string matches 0 or more white
2630 // spaces in the input
2631 while ( wxIsspace(*input) )
2632 {
2633 input++;
2634 }
2635 }
2636 else // !space
2637 {
2638 // any other character (not whitespace, not '%') must be
2639 // matched by itself in the input
2640 if ( *input++ != *fmt )
2641 {
2642 // no match
2643 return (wxChar *)NULL;
2644 }
2645 }
2646
2647 // done with this format char
2648 continue;
2649 }
2650
2651 // start of a format specification
2652
2653 // parse the optional width
2654 size_t width = 0;
2655 while ( isdigit(*++fmt) )
2656 {
2657 width *= 10;
2658 width += *fmt - _T('0');
2659 }
2660
2661 // the default widths for the various fields
2662 if ( !width )
2663 {
2664 switch ( *fmt )
2665 {
2666 case _T('Y'): // year has 4 digits
2667 width = 4;
2668 break;
2669
2670 case _T('j'): // day of year has 3 digits
2671 case _T('l'): // milliseconds have 3 digits
2672 width = 3;
2673 break;
2674
2675 case _T('w'): // week day as number has only one
2676 width = 1;
2677 break;
2678
2679 default:
2680 // default for all other fields
2681 width = 2;
2682 }
2683 }
2684
2685 // then the format itself
2686 switch ( *fmt )
2687 {
2688 case _T('a'): // a weekday name
2689 case _T('A'):
2690 {
2691 int flag = *fmt == _T('a') ? Name_Abbr : Name_Full;
2692 wday = GetWeekDayFromName(GetAlphaToken(input), flag);
2693 if ( wday == Inv_WeekDay )
2694 {
2695 // no match
2696 return (wxChar *)NULL;
2697 }
2698 }
2699 haveWDay = TRUE;
2700 break;
2701
2702 case _T('b'): // a month name
2703 case _T('B'):
2704 {
2705 int flag = *fmt == _T('b') ? Name_Abbr : Name_Full;
2706 mon = GetMonthFromName(GetAlphaToken(input), flag);
2707 if ( mon == Inv_Month )
2708 {
2709 // no match
2710 return (wxChar *)NULL;
2711 }
2712 }
2713 haveMon = TRUE;
2714 break;
2715
2716 case _T('c'): // locale default date and time representation
2717 {
2718 wxDateTime dt;
2719
2720 // this is the format which corresponds to ctime() output
2721 // and strptime("%c") should parse it, so try it first
2722 static const wxChar *fmtCtime = _T("%a %b %d %H:%M:%S %Y");
2723
2724 const wxChar *result = dt.ParseFormat(input, fmtCtime);
2725 if ( !result )
2726 {
2727 result = dt.ParseFormat(input, _T("%x %X"));
2728 }
2729
2730 if ( !result )
2731 {
2732 result = dt.ParseFormat(input, _T("%X %x"));
2733 }
2734
2735 if ( !result )
2736 {
2737 // we've tried everything and still no match
2738 return (wxChar *)NULL;
2739 }
2740
2741 Tm tm = dt.GetTm();
2742
2743 haveDay = haveMon = haveYear =
2744 haveHour = haveMin = haveSec = TRUE;
2745
2746 hour = tm.hour;
2747 min = tm.min;
2748 sec = tm.sec;
2749
2750 year = tm.year;
2751 mon = tm.mon;
2752 mday = tm.mday;
2753
2754 input = result;
2755 }
2756 break;
2757
2758 case _T('d'): // day of a month (01-31)
2759 if ( !GetNumericToken(width, input, &num) ||
2760 (num > 31) || (num < 1) )
2761 {
2762 // no match
2763 return (wxChar *)NULL;
2764 }
2765
2766 // we can't check whether the day range is correct yet, will
2767 // do it later - assume ok for now
2768 haveDay = TRUE;
2769 mday = (wxDateTime_t)num;
2770 break;
2771
2772 case _T('H'): // hour in 24h format (00-23)
2773 if ( !GetNumericToken(width, input, &num) || (num > 23) )
2774 {
2775 // no match
2776 return (wxChar *)NULL;
2777 }
2778
2779 haveHour = TRUE;
2780 hour = (wxDateTime_t)num;
2781 break;
2782
2783 case _T('I'): // hour in 12h format (01-12)
2784 if ( !GetNumericToken(width, input, &num) || !num || (num > 12) )
2785 {
2786 // no match
2787 return (wxChar *)NULL;
2788 }
2789
2790 haveHour = TRUE;
2791 hourIsIn12hFormat = TRUE;
2792 hour = (wxDateTime_t)(num % 12); // 12 should be 0
2793 break;
2794
2795 case _T('j'): // day of the year
2796 if ( !GetNumericToken(width, input, &num) || !num || (num > 366) )
2797 {
2798 // no match
2799 return (wxChar *)NULL;
2800 }
2801
2802 haveYDay = TRUE;
2803 yday = (wxDateTime_t)num;
2804 break;
2805
2806 case _T('m'): // month as a number (01-12)
2807 if ( !GetNumericToken(width, input, &num) || !num || (num > 12) )
2808 {
2809 // no match
2810 return (wxChar *)NULL;
2811 }
2812
2813 haveMon = TRUE;
2814 mon = (Month)(num - 1);
2815 break;
2816
2817 case _T('M'): // minute as a decimal number (00-59)
2818 if ( !GetNumericToken(width, input, &num) || (num > 59) )
2819 {
2820 // no match
2821 return (wxChar *)NULL;
2822 }
2823
2824 haveMin = TRUE;
2825 min = (wxDateTime_t)num;
2826 break;
2827
2828 case _T('p'): // AM or PM string
2829 {
2830 wxString am, pm, token = GetAlphaToken(input);
2831
2832 GetAmPmStrings(&am, &pm);
2833 if ( token.CmpNoCase(pm) == 0 )
2834 {
2835 isPM = TRUE;
2836 }
2837 else if ( token.CmpNoCase(am) != 0 )
2838 {
2839 // no match
2840 return (wxChar *)NULL;
2841 }
2842 }
2843 break;
2844
2845 case _T('r'): // time as %I:%M:%S %p
2846 {
2847 wxDateTime dt;
2848 input = dt.ParseFormat(input, _T("%I:%M:%S %p"));
2849 if ( !input )
2850 {
2851 // no match
2852 return (wxChar *)NULL;
2853 }
2854
2855 haveHour = haveMin = haveSec = TRUE;
2856
2857 Tm tm = dt.GetTm();
2858 hour = tm.hour;
2859 min = tm.min;
2860 sec = tm.sec;
2861 }
2862 break;
2863
2864 case _T('R'): // time as %H:%M
2865 {
2866 wxDateTime dt;
2867 input = dt.ParseFormat(input, _T("%H:%M"));
2868 if ( !input )
2869 {
2870 // no match
2871 return (wxChar *)NULL;
2872 }
2873
2874 haveHour = haveMin = TRUE;
2875
2876 Tm tm = dt.GetTm();
2877 hour = tm.hour;
2878 min = tm.min;
2879 }
2880
2881 case _T('S'): // second as a decimal number (00-61)
2882 if ( !GetNumericToken(width, input, &num) || (num > 61) )
2883 {
2884 // no match
2885 return (wxChar *)NULL;
2886 }
2887
2888 haveSec = TRUE;
2889 sec = (wxDateTime_t)num;
2890 break;
2891
2892 case _T('T'): // time as %H:%M:%S
2893 {
2894 wxDateTime dt;
2895 input = dt.ParseFormat(input, _T("%H:%M:%S"));
2896 if ( !input )
2897 {
2898 // no match
2899 return (wxChar *)NULL;
2900 }
2901
2902 haveHour = haveMin = haveSec = TRUE;
2903
2904 Tm tm = dt.GetTm();
2905 hour = tm.hour;
2906 min = tm.min;
2907 sec = tm.sec;
2908 }
2909 break;
2910
2911 case _T('w'): // weekday as a number (0-6), Sunday = 0
2912 if ( !GetNumericToken(width, input, &num) || (wday > 6) )
2913 {
2914 // no match
2915 return (wxChar *)NULL;
2916 }
2917
2918 haveWDay = TRUE;
2919 wday = (WeekDay)num;
2920 break;
2921
2922 case _T('x'): // locale default date representation
2923 #ifdef HAVE_STRPTIME
2924 // try using strptime() - it may fail even if the input is
2925 // correct but the date is out of range, so we will fall back
2926 // to our generic code anyhow (FIXME !Unicode friendly)
2927 {
2928 struct tm tm;
2929 const wxChar *result = strptime(input, "%x", &tm);
2930 if ( result )
2931 {
2932 input = result;
2933
2934 haveDay = haveMon = haveYear = TRUE;
2935
2936 year = 1900 + tm.tm_year;
2937 mon = (Month)tm.tm_mon;
2938 mday = tm.tm_mday;
2939
2940 break;
2941 }
2942 }
2943 #endif // HAVE_STRPTIME
2944
2945 // TODO query the LOCALE_IDATE setting under Win32
2946 {
2947 wxDateTime dt;
2948
2949 wxString fmtDate, fmtDateAlt;
2950 if ( IsWestEuropeanCountry(GetCountry()) ||
2951 GetCountry() == Russia )
2952 {
2953 fmtDate = _T("%d/%m/%y");
2954 fmtDateAlt = _T("%m/%d/%y");
2955 }
2956 else // assume USA
2957 {
2958 fmtDate = _T("%m/%d/%y");
2959 fmtDateAlt = _T("%d/%m/%y");
2960 }
2961
2962 const wxChar *result = dt.ParseFormat(input, fmtDate);
2963
2964 if ( !result )
2965 {
2966 // ok, be nice and try another one
2967 result = dt.ParseFormat(input, fmtDateAlt);
2968 }
2969
2970 if ( !result )
2971 {
2972 // bad luck
2973 return (wxChar *)NULL;
2974 }
2975
2976 Tm tm = dt.GetTm();
2977
2978 haveDay = haveMon = haveYear = TRUE;
2979
2980 year = tm.year;
2981 mon = tm.mon;
2982 mday = tm.mday;
2983
2984 input = result;
2985 }
2986
2987 break;
2988
2989 case _T('X'): // locale default time representation
2990 #ifdef HAVE_STRPTIME
2991 {
2992 // use strptime() to do it for us (FIXME !Unicode friendly)
2993 struct tm tm;
2994 input = strptime(input, "%X", &tm);
2995 if ( !input )
2996 {
2997 return (wxChar *)NULL;
2998 }
2999
3000 haveHour = haveMin = haveSec = TRUE;
3001
3002 hour = tm.tm_hour;
3003 min = tm.tm_min;
3004 sec = tm.tm_sec;
3005 }
3006 #else // !HAVE_STRPTIME
3007 // TODO under Win32 we can query the LOCALE_ITIME system
3008 // setting which says whether the default time format is
3009 // 24 or 12 hour
3010 {
3011 // try to parse what follows as "%H:%M:%S" and, if this
3012 // fails, as "%I:%M:%S %p" - this should catch the most
3013 // common cases
3014 wxDateTime dt;
3015
3016 const wxChar *result = dt.ParseFormat(input, _T("%T"));
3017 if ( !result )
3018 {
3019 result = dt.ParseFormat(input, _T("%r"));
3020 }
3021
3022 if ( !result )
3023 {
3024 // no match
3025 return (wxChar *)NULL;
3026 }
3027
3028 haveHour = haveMin = haveSec = TRUE;
3029
3030 Tm tm = dt.GetTm();
3031 hour = tm.hour;
3032 min = tm.min;
3033 sec = tm.sec;
3034
3035 input = result;
3036 }
3037 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3038 break;
3039
3040 case _T('y'): // year without century (00-99)
3041 if ( !GetNumericToken(width, input, &num) || (num > 99) )
3042 {
3043 // no match
3044 return (wxChar *)NULL;
3045 }
3046
3047 haveYear = TRUE;
3048
3049 // TODO should have an option for roll over date instead of
3050 // hard coding it here
3051 year = (num > 30 ? 1900 : 2000) + (wxDateTime_t)num;
3052 break;
3053
3054 case _T('Y'): // year with century
3055 if ( !GetNumericToken(width, input, &num) )
3056 {
3057 // no match
3058 return (wxChar *)NULL;
3059 }
3060
3061 haveYear = TRUE;
3062 year = (wxDateTime_t)num;
3063 break;
3064
3065 case _T('Z'): // timezone name
3066 wxFAIL_MSG(_T("TODO"));
3067 break;
3068
3069 case _T('%'): // a percent sign
3070 if ( *input++ != _T('%') )
3071 {
3072 // no match
3073 return (wxChar *)NULL;
3074 }
3075 break;
3076
3077 case 0: // the end of string
3078 wxFAIL_MSG(_T("unexpected format end"));
3079
3080 // fall through
3081
3082 default: // not a known format spec
3083 return (wxChar *)NULL;
3084 }
3085 }
3086
3087 // format matched, try to construct a date from what we have now
3088 Tm tmDef;
3089 if ( dateDef.IsValid() )
3090 {
3091 // take this date as default
3092 tmDef = dateDef.GetTm();
3093 }
3094 else if ( IsValid() )
3095 {
3096 // if this date is valid, don't change it
3097 tmDef = GetTm();
3098 }
3099 else
3100 {
3101 // no default and this date is invalid - fall back to Today()
3102 tmDef = Today().GetTm();
3103 }
3104
3105 Tm tm = tmDef;
3106
3107 // set the date
3108 if ( haveYear )
3109 {
3110 tm.year = year;
3111 }
3112
3113 // TODO we don't check here that the values are consistent, if both year
3114 // day and month/day were found, we just ignore the year day and we
3115 // also always ignore the week day
3116 if ( haveMon && haveDay )
3117 {
3118 if ( mday > GetNumOfDaysInMonth(tm.year, mon) )
3119 {
3120 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3121
3122 return (wxChar *)NULL;
3123 }
3124
3125 tm.mon = mon;
3126 tm.mday = mday;
3127 }
3128 else if ( haveYDay )
3129 {
3130 if ( yday > GetNumberOfDays(tm.year) )
3131 {
3132 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3133
3134 return (wxChar *)NULL;
3135 }
3136
3137 Tm tm2 = wxDateTime(1, Jan, tm.year).SetToYearDay(yday).GetTm();
3138
3139 tm.mon = tm2.mon;
3140 tm.mday = tm2.mday;
3141 }
3142
3143 // deal with AM/PM
3144 if ( haveHour && hourIsIn12hFormat && isPM )
3145 {
3146 // translate to 24hour format
3147 hour += 12;
3148 }
3149 //else: either already in 24h format or no translation needed
3150
3151 // set the time
3152 if ( haveHour )
3153 {
3154 tm.hour = hour;
3155 }
3156
3157 if ( haveMin )
3158 {
3159 tm.min = min;
3160 }
3161
3162 if ( haveSec )
3163 {
3164 tm.sec = sec;
3165 }
3166
3167 Set(tm);
3168
3169 return input;
3170 }
3171
3172 const wxChar *wxDateTime::ParseDateTime(const wxChar *date)
3173 {
3174 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3175
3176 // there is a public domain version of getdate.y, but it only works for
3177 // English...
3178 wxFAIL_MSG(_T("TODO"));
3179
3180 return (wxChar *)NULL;
3181 }
3182
3183 const wxChar *wxDateTime::ParseDate(const wxChar *date)
3184 {
3185 // this is a simplified version of ParseDateTime() which understands only
3186 // "today" (for wxDate compatibility) and digits only otherwise (and not
3187 // all esoteric constructions ParseDateTime() knows about)
3188
3189 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3190
3191 const wxChar *p = date;
3192 while ( wxIsspace(*p) )
3193 p++;
3194
3195 // some special cases
3196 static struct
3197 {
3198 const wxChar *str;
3199 int dayDiffFromToday;
3200 } literalDates[] =
3201 {
3202 { wxTRANSLATE("today"), 0 },
3203 { wxTRANSLATE("yesterday"), -1 },
3204 { wxTRANSLATE("tomorrow"), 1 },
3205 };
3206
3207 for ( size_t n = 0; n < WXSIZEOF(literalDates); n++ )
3208 {
3209 wxString date = wxGetTranslation(literalDates[n].str);
3210 size_t len = date.length();
3211 if ( wxStrlen(p) >= len && (wxString(p, len).CmpNoCase(date) == 0) )
3212 {
3213 // nothing can follow this, so stop here
3214 p += len;
3215
3216 int dayDiffFromToday = literalDates[n].dayDiffFromToday;
3217 *this = Today();
3218 if ( dayDiffFromToday )
3219 {
3220 *this += wxDateSpan::Days(dayDiffFromToday);
3221 }
3222
3223 return p;
3224 }
3225 }
3226
3227 // We try to guess what we have here: for each new (numeric) token, we
3228 // determine if it can be a month, day or a year. Of course, there is an
3229 // ambiguity as some numbers may be days as well as months, so we also
3230 // have the ability to back track.
3231
3232 // what do we have?
3233 bool haveDay = FALSE, // the months day?
3234 haveWDay = FALSE, // the day of week?
3235 haveMon = FALSE, // the month?
3236 haveYear = FALSE; // the year?
3237
3238 // and the value of the items we have (init them to get rid of warnings)
3239 WeekDay wday = Inv_WeekDay;
3240 wxDateTime_t day = 0;
3241 wxDateTime::Month mon = Inv_Month;
3242 int year = 0;
3243
3244 // tokenize the string
3245 size_t nPosCur = 0;
3246 static const wxChar *dateDelimiters = _T(".,/-\t\r\n ");
3247 wxStringTokenizer tok(p, dateDelimiters);
3248 while ( tok.HasMoreTokens() )
3249 {
3250 wxString token = tok.GetNextToken();
3251 if ( !token )
3252 continue;
3253
3254 // is it a number?
3255 unsigned long val;
3256 if ( token.ToULong(&val) )
3257 {
3258 // guess what this number is
3259
3260 bool isDay = FALSE,
3261 isMonth = FALSE,
3262 isYear = FALSE;
3263
3264 if ( !haveMon && val > 0 && val <= 12 )
3265 {
3266 // assume it is month
3267 isMonth = TRUE;
3268 }
3269 else // not the month
3270 {
3271 wxDateTime_t maxDays = haveMon
3272 ? GetNumOfDaysInMonth(haveYear ? year : Inv_Year, mon)
3273 : 31;
3274
3275 // can it be day?
3276 if ( (val == 0) || (val > (unsigned long)maxDays) ) // cast to shut up compiler warning in BCC
3277 {
3278 isYear = TRUE;
3279 }
3280 else
3281 {
3282 isDay = TRUE;
3283 }
3284 }
3285
3286 if ( isYear )
3287 {
3288 if ( haveYear )
3289 break;
3290
3291 haveYear = TRUE;
3292
3293 year = (wxDateTime_t)val;
3294 }
3295 else if ( isDay )
3296 {
3297 if ( haveDay )
3298 break;
3299
3300 haveDay = TRUE;
3301
3302 day = (wxDateTime_t)val;
3303 }
3304 else if ( isMonth )
3305 {
3306 haveMon = TRUE;
3307
3308 mon = (Month)(val - 1);
3309 }
3310 }
3311 else // not a number
3312 {
3313 // be careful not to overwrite the current mon value
3314 Month mon2 = GetMonthFromName(token, Name_Full | Name_Abbr);
3315 if ( mon2 != Inv_Month )
3316 {
3317 // it's a month
3318 if ( haveMon )
3319 {
3320 // but we already have a month - maybe we guessed wrong?
3321 if ( !haveDay )
3322 {
3323 // no need to check in month range as always < 12, but
3324 // the days are counted from 1 unlike the months
3325 day = (wxDateTime_t)mon + 1;
3326 haveDay = TRUE;
3327 }
3328 else
3329 {
3330 // could possible be the year (doesn't the year come
3331 // before the month in the japanese format?) (FIXME)
3332 break;
3333 }
3334 }
3335
3336 mon = mon2;
3337
3338 haveMon = TRUE;
3339 }
3340 else // not a valid month name
3341 {
3342 wday = GetWeekDayFromName(token, Name_Full | Name_Abbr);
3343 if ( wday != Inv_WeekDay )
3344 {
3345 // a week day
3346 if ( haveWDay )
3347 {
3348 break;
3349 }
3350
3351 haveWDay = TRUE;
3352 }
3353 else // not a valid weekday name
3354 {
3355 // try the ordinals
3356 static const wxChar *ordinals[] =
3357 {
3358 wxTRANSLATE("first"),
3359 wxTRANSLATE("second"),
3360 wxTRANSLATE("third"),
3361 wxTRANSLATE("fourth"),
3362 wxTRANSLATE("fifth"),
3363 wxTRANSLATE("sixth"),
3364 wxTRANSLATE("seventh"),
3365 wxTRANSLATE("eighth"),
3366 wxTRANSLATE("ninth"),
3367 wxTRANSLATE("tenth"),
3368 wxTRANSLATE("eleventh"),
3369 wxTRANSLATE("twelfth"),
3370 wxTRANSLATE("thirteenth"),
3371 wxTRANSLATE("fourteenth"),
3372 wxTRANSLATE("fifteenth"),
3373 wxTRANSLATE("sixteenth"),
3374 wxTRANSLATE("seventeenth"),
3375 wxTRANSLATE("eighteenth"),
3376 wxTRANSLATE("nineteenth"),
3377 wxTRANSLATE("twentieth"),
3378 // that's enough - otherwise we'd have problems with
3379 // composite (or not) ordinals
3380 };
3381
3382 size_t n;
3383 for ( n = 0; n < WXSIZEOF(ordinals); n++ )
3384 {
3385 if ( token.CmpNoCase(ordinals[n]) == 0 )
3386 {
3387 break;
3388 }
3389 }
3390
3391 if ( n == WXSIZEOF(ordinals) )
3392 {
3393 // stop here - something unknown
3394 break;
3395 }
3396
3397 // it's a day
3398 if ( haveDay )
3399 {
3400 // don't try anything here (as in case of numeric day
3401 // above) - the symbolic day spec should always
3402 // precede the month/year
3403 break;
3404 }
3405
3406 haveDay = TRUE;
3407
3408 day = (wxDateTime_t)(n + 1);
3409 }
3410 }
3411 }
3412
3413 nPosCur = tok.GetPosition();
3414 }
3415
3416 // either no more tokens or the scan was stopped by something we couldn't
3417 // parse - in any case, see if we can construct a date from what we have
3418 if ( !haveDay && !haveWDay )
3419 {
3420 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3421
3422 return (wxChar *)NULL;
3423 }
3424
3425 if ( haveWDay && (haveMon || haveYear || haveDay) &&
3426 !(haveDay && haveMon && haveYear) )
3427 {
3428 // without adjectives (which we don't support here) the week day only
3429 // makes sense completely separately or with the full date
3430 // specification (what would "Wed 1999" mean?)
3431 return (wxChar *)NULL;
3432 }
3433
3434 if ( !haveWDay && haveYear && !(haveDay && haveMon) )
3435 {
3436 // may be we have month and day instead of day and year?
3437 if ( haveDay && !haveMon )
3438 {
3439 if ( day <= 12 )
3440 {
3441 // exchange day and month
3442 mon = (wxDateTime::Month)(day - 1);
3443
3444 // we're in the current year then
3445 if ( (year > 0) &&
3446 (unsigned)year <= GetNumOfDaysInMonth(Inv_Year, mon) )
3447 {
3448 day = year;
3449
3450 haveMon = TRUE;
3451 haveYear = FALSE;
3452 }
3453 //else: no, can't exchange, leave haveMon == FALSE
3454 }
3455 }
3456
3457 if ( !haveMon )
3458 {
3459 // if we give the year, month and day must be given too
3460 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3461
3462 return (wxChar *)NULL;
3463 }
3464 }
3465
3466 if ( !haveMon )
3467 {
3468 mon = GetCurrentMonth();
3469 }
3470
3471 if ( !haveYear )
3472 {
3473 year = GetCurrentYear();
3474 }
3475
3476 if ( haveDay )
3477 {
3478 Set(day, mon, year);
3479
3480 if ( haveWDay )
3481 {
3482 // check that it is really the same
3483 if ( GetWeekDay() != wday )
3484 {
3485 // inconsistency detected
3486 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3487
3488 return (wxChar *)NULL;
3489 }
3490 }
3491 }
3492 else // haveWDay
3493 {
3494 *this = Today();
3495
3496 SetToWeekDayInSameWeek(wday);
3497 }
3498
3499 // return the pointer to the first unparsed char
3500 p += nPosCur;
3501 if ( nPosCur && wxStrchr(dateDelimiters, *(p - 1)) )
3502 {
3503 // if we couldn't parse the token after the delimiter, put back the
3504 // delimiter as well
3505 p--;
3506 }
3507
3508 return p;
3509 }
3510
3511 const wxChar *wxDateTime::ParseTime(const wxChar *time)
3512 {
3513 wxCHECK_MSG( time, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3514
3515 // first try some extra things
3516 static const struct
3517 {
3518 const wxChar *name;
3519 wxDateTime_t hour;
3520 } stdTimes[] =
3521 {
3522 { wxTRANSLATE("noon"), 12 },
3523 { wxTRANSLATE("midnight"), 00 },
3524 // anything else?
3525 };
3526
3527 for ( size_t n = 0; n < WXSIZEOF(stdTimes); n++ )
3528 {
3529 wxString timeString = wxGetTranslation(stdTimes[n].name);
3530 size_t len = timeString.length();
3531 if ( timeString.CmpNoCase(wxString(time, len)) == 0 )
3532 {
3533 Set(stdTimes[n].hour, 0, 0);
3534
3535 return time + len;
3536 }
3537 }
3538
3539 // try all time formats we may think about in the order from longest to
3540 // shortest
3541
3542 // 12hour with AM/PM?
3543 const wxChar *result = ParseFormat(time, _T("%I:%M:%S %p"));
3544
3545 if ( !result )
3546 {
3547 // normally, it's the same, but why not try it?
3548 result = ParseFormat(time, _T("%H:%M:%S"));
3549 }
3550
3551 if ( !result )
3552 {
3553 // 12hour with AM/PM but without seconds?
3554 result = ParseFormat(time, _T("%I:%M %p"));
3555 }
3556
3557 if ( !result )
3558 {
3559 // without seconds?
3560 result = ParseFormat(time, _T("%H:%M"));
3561 }
3562
3563 if ( !result )
3564 {
3565 // just the hour and AM/PM?
3566 result = ParseFormat(time, _T("%I %p"));
3567 }
3568
3569 if ( !result )
3570 {
3571 // just the hour?
3572 result = ParseFormat(time, _T("%H"));
3573 }
3574
3575 if ( !result )
3576 {
3577 // parse the standard format: normally it is one of the formats above
3578 // but it may be set to something completely different by the user
3579 result = ParseFormat(time, _T("%X"));
3580 }
3581
3582 // TODO: parse timezones
3583
3584 return result;
3585 }
3586
3587 // ----------------------------------------------------------------------------
3588 // Workdays and holidays support
3589 // ----------------------------------------------------------------------------
3590
3591 bool wxDateTime::IsWorkDay(Country WXUNUSED(country)) const
3592 {
3593 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3594 }
3595
3596 // ============================================================================
3597 // wxTimeSpan
3598 // ============================================================================
3599
3600 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3601 // it locally to the method as it provokes an internal compiler error in egcs
3602 // 2.91.60 when building with -O2
3603 enum TimeSpanPart
3604 {
3605 Part_Week,
3606 Part_Day,
3607 Part_Hour,
3608 Part_Min,
3609 Part_Sec,
3610 Part_MSec
3611 };
3612
3613 // not all strftime(3) format specifiers make sense here because, for example,
3614 // a time span doesn't have a year nor a timezone
3615 //
3616 // Here are the ones which are supported (all of them are supported by strftime
3617 // as well):
3618 // %H hour in 24 hour format
3619 // %M minute (00 - 59)
3620 // %S second (00 - 59)
3621 // %% percent sign
3622 //
3623 // Also, for MFC CTimeSpan compatibility, we support
3624 // %D number of days
3625 //
3626 // And, to be better than MFC :-), we also have
3627 // %E number of wEeks
3628 // %l milliseconds (000 - 999)
3629 wxString wxTimeSpan::Format(const wxChar *format) const
3630 {
3631 wxCHECK_MSG( format, _T(""), _T("NULL format in wxTimeSpan::Format") );
3632
3633 wxString str;
3634 str.Alloc(wxStrlen(format));
3635
3636 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3637 //
3638 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3639 // question is what should ts.Format("%S") do? The code here returns "3273"
3640 // in this case (i.e. the total number of seconds, not just seconds % 60)
3641 // because, for me, this call means "give me entire time interval in
3642 // seconds" and not "give me the seconds part of the time interval"
3643 //
3644 // If we agree that it should behave like this, it is clear that the
3645 // interpretation of each format specifier depends on the presence of the
3646 // other format specs in the string: if there was "%H" before "%M", we
3647 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3648
3649 // we remember the most important unit found so far
3650 TimeSpanPart partBiggest = Part_MSec;
3651
3652 for ( const wxChar *pch = format; *pch; pch++ )
3653 {
3654 wxChar ch = *pch;
3655
3656 if ( ch == _T('%') )
3657 {
3658 // the start of the format specification of the printf() below
3659 wxString fmtPrefix = _T('%');
3660
3661 // the number
3662 long n;
3663
3664 ch = *++pch; // get the format spec char
3665 switch ( ch )
3666 {
3667 default:
3668 wxFAIL_MSG( _T("invalid format character") );
3669 // fall through
3670
3671 case _T('%'):
3672 str += ch;
3673
3674 // skip the part below switch
3675 continue;
3676
3677 case _T('D'):
3678 n = GetDays();
3679 if ( partBiggest < Part_Day )
3680 {
3681 n %= DAYS_PER_WEEK;
3682 }
3683 else
3684 {
3685 partBiggest = Part_Day;
3686 }
3687 break;
3688
3689 case _T('E'):
3690 partBiggest = Part_Week;
3691 n = GetWeeks();
3692 break;
3693
3694 case _T('H'):
3695 n = GetHours();
3696 if ( partBiggest < Part_Hour )
3697 {
3698 n %= HOURS_PER_DAY;
3699 }
3700 else
3701 {
3702 partBiggest = Part_Hour;
3703 }
3704
3705 fmtPrefix += _T("02");
3706 break;
3707
3708 case _T('l'):
3709 n = GetMilliseconds().ToLong();
3710 if ( partBiggest < Part_MSec )
3711 {
3712 n %= 1000;
3713 }
3714 //else: no need to reset partBiggest to Part_MSec, it is
3715 // the least significant one anyhow
3716
3717 fmtPrefix += _T("03");
3718 break;
3719
3720 case _T('M'):
3721 n = GetMinutes();
3722 if ( partBiggest < Part_Min )
3723 {
3724 n %= MIN_PER_HOUR;
3725 }
3726 else
3727 {
3728 partBiggest = Part_Min;
3729 }
3730
3731 fmtPrefix += _T("02");
3732 break;
3733
3734 case _T('S'):
3735 n = GetSeconds().ToLong();
3736 if ( partBiggest < Part_Sec )
3737 {
3738 n %= SEC_PER_MIN;
3739 }
3740 else
3741 {
3742 partBiggest = Part_Sec;
3743 }
3744
3745 fmtPrefix += _T("02");
3746 break;
3747 }
3748
3749 str += wxString::Format(fmtPrefix + _T("ld"), n);
3750 }
3751 else
3752 {
3753 // normal character, just copy
3754 str += ch;
3755 }
3756 }
3757
3758 return str;
3759 }
3760
3761 // ============================================================================
3762 // wxDateTimeHolidayAuthority and related classes
3763 // ============================================================================
3764
3765 #include "wx/arrimpl.cpp"
3766
3767 WX_DEFINE_OBJARRAY(wxDateTimeArray);
3768
3769 static int wxCMPFUNC_CONV
3770 wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
3771 {
3772 wxDateTime dt1 = **first,
3773 dt2 = **second;
3774
3775 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
3776 }
3777
3778 // ----------------------------------------------------------------------------
3779 // wxDateTimeHolidayAuthority
3780 // ----------------------------------------------------------------------------
3781
3782 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
3783
3784 /* static */
3785 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
3786 {
3787 size_t count = ms_authorities.GetCount();
3788 for ( size_t n = 0; n < count; n++ )
3789 {
3790 if ( ms_authorities[n]->DoIsHoliday(dt) )
3791 {
3792 return TRUE;
3793 }
3794 }
3795
3796 return FALSE;
3797 }
3798
3799 /* static */
3800 size_t
3801 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
3802 const wxDateTime& dtEnd,
3803 wxDateTimeArray& holidays)
3804 {
3805 wxDateTimeArray hol;
3806
3807 holidays.Empty();
3808
3809 size_t count = ms_authorities.GetCount();
3810 for ( size_t nAuth = 0; nAuth < count; nAuth++ )
3811 {
3812 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
3813
3814 WX_APPEND_ARRAY(holidays, hol);
3815 }
3816
3817 holidays.Sort(wxDateTimeCompareFunc);
3818
3819 return holidays.GetCount();
3820 }
3821
3822 /* static */
3823 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3824 {
3825 WX_CLEAR_ARRAY(ms_authorities);
3826 }
3827
3828 /* static */
3829 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
3830 {
3831 ms_authorities.Add(auth);
3832 }
3833
3834 // ----------------------------------------------------------------------------
3835 // wxDateTimeWorkDays
3836 // ----------------------------------------------------------------------------
3837
3838 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
3839 {
3840 wxDateTime::WeekDay wd = dt.GetWeekDay();
3841
3842 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
3843 }
3844
3845 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
3846 const wxDateTime& dtEnd,
3847 wxDateTimeArray& holidays) const
3848 {
3849 if ( dtStart > dtEnd )
3850 {
3851 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3852
3853 return 0u;
3854 }
3855
3856 holidays.Empty();
3857
3858 // instead of checking all days, start with the first Sat after dtStart and
3859 // end with the last Sun before dtEnd
3860 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
3861 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
3862 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
3863 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
3864 dt;
3865
3866 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
3867 {
3868 holidays.Add(dt);
3869 }
3870
3871 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
3872 {
3873 holidays.Add(dt);
3874 }
3875
3876 return holidays.GetCount();
3877 }
3878
3879 #endif // wxUSE_DATETIME