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