]> git.saurik.com Git - wxWidgets.git/blob - src/common/datetime.cpp
document (and check for it with assert) that wxGetKeyState(WXK_[LMR]BUTTON) doesn...
[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 break;
3205
3206 case _T('S'): // second as a decimal number (00-61)
3207 if ( !GetNumericToken(width, input, &num) || (num > 61) )
3208 {
3209 // no match
3210 return (wxChar *)NULL;
3211 }
3212
3213 haveSec = true;
3214 sec = (wxDateTime_t)num;
3215 break;
3216
3217 case _T('T'): // time as %H:%M:%S
3218 {
3219 wxDateTime dt;
3220 input = dt.ParseFormat(input, _T("%H:%M:%S"));
3221 if ( !input )
3222 {
3223 // no match
3224 return (wxChar *)NULL;
3225 }
3226
3227 haveHour = haveMin = haveSec = true;
3228
3229 Tm tm = dt.GetTm();
3230 hour = tm.hour;
3231 min = tm.min;
3232 sec = tm.sec;
3233 }
3234 break;
3235
3236 case _T('w'): // weekday as a number (0-6), Sunday = 0
3237 if ( !GetNumericToken(width, input, &num) || (wday > 6) )
3238 {
3239 // no match
3240 return (wxChar *)NULL;
3241 }
3242
3243 haveWDay = true;
3244 wday = (WeekDay)num;
3245 break;
3246
3247 case _T('x'): // locale default date representation
3248 #ifdef HAVE_STRPTIME
3249 // try using strptime() -- it may fail even if the input is
3250 // correct but the date is out of range, so we will fall back
3251 // to our generic code anyhow
3252 {
3253 struct tm tm;
3254
3255 const wxChar *result = CallStrptime(input, "%x", &tm);
3256 if ( result )
3257 {
3258 input = result;
3259
3260 haveDay = haveMon = haveYear = true;
3261
3262 year = 1900 + tm.tm_year;
3263 mon = (Month)tm.tm_mon;
3264 mday = tm.tm_mday;
3265
3266 break;
3267 }
3268 }
3269 #endif // HAVE_STRPTIME
3270
3271 {
3272 wxDateTime dt;
3273
3274 wxString fmtDate, fmtDateAlt;
3275
3276 if ( IsWestEuropeanCountry(GetCountry()) ||
3277 GetCountry() == Russia )
3278 {
3279 fmtDate = _T("%d/%m/%y");
3280 fmtDateAlt = _T("%m/%d/%y");
3281 }
3282 else // assume USA
3283 {
3284 fmtDate = _T("%m/%d/%y");
3285 fmtDateAlt = _T("%d/%m/%y");
3286 }
3287
3288 #ifdef __WINDOWS__
3289 // The above doesn't work for all locales, try to query
3290 // Windows for the right way of formatting the date:
3291 GetLocaleDateFormat(&fmtDate);
3292 #endif
3293
3294 const wxChar *result = dt.ParseFormat(input, fmtDate);
3295
3296 if ( !result )
3297 {
3298 // ok, be nice and try another one
3299 result = dt.ParseFormat(input, fmtDateAlt);
3300 }
3301
3302 if ( !result )
3303 {
3304 // bad luck
3305 return (wxChar *)NULL;
3306 }
3307
3308 Tm tm = dt.GetTm();
3309
3310 haveDay = haveMon = haveYear = true;
3311
3312 year = tm.year;
3313 mon = tm.mon;
3314 mday = tm.mday;
3315
3316 input = result;
3317 }
3318
3319 break;
3320
3321 case _T('X'): // locale default time representation
3322 #ifdef HAVE_STRPTIME
3323 {
3324 // use strptime() to do it for us (FIXME !Unicode friendly)
3325 struct tm tm;
3326 input = CallStrptime(input, "%X", &tm);
3327 if ( !input )
3328 {
3329 return (wxChar *)NULL;
3330 }
3331
3332 haveHour = haveMin = haveSec = true;
3333
3334 hour = tm.tm_hour;
3335 min = tm.tm_min;
3336 sec = tm.tm_sec;
3337 }
3338 #else // !HAVE_STRPTIME
3339 // TODO under Win32 we can query the LOCALE_ITIME system
3340 // setting which says whether the default time format is
3341 // 24 or 12 hour
3342 {
3343 // try to parse what follows as "%H:%M:%S" and, if this
3344 // fails, as "%I:%M:%S %p" - this should catch the most
3345 // common cases
3346 wxDateTime dt;
3347
3348 const wxChar *result = dt.ParseFormat(input, _T("%T"));
3349 if ( !result )
3350 {
3351 result = dt.ParseFormat(input, _T("%r"));
3352 }
3353
3354 if ( !result )
3355 {
3356 // no match
3357 return (wxChar *)NULL;
3358 }
3359
3360 haveHour = haveMin = haveSec = true;
3361
3362 Tm tm = dt.GetTm();
3363 hour = tm.hour;
3364 min = tm.min;
3365 sec = tm.sec;
3366
3367 input = result;
3368 }
3369 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3370 break;
3371
3372 case _T('y'): // year without century (00-99)
3373 if ( !GetNumericToken(width, input, &num) || (num > 99) )
3374 {
3375 // no match
3376 return (wxChar *)NULL;
3377 }
3378
3379 haveYear = true;
3380
3381 // TODO should have an option for roll over date instead of
3382 // hard coding it here
3383 year = (num > 30 ? 1900 : 2000) + (wxDateTime_t)num;
3384 break;
3385
3386 case _T('Y'): // year with century
3387 if ( !GetNumericToken(width, input, &num) )
3388 {
3389 // no match
3390 return (wxChar *)NULL;
3391 }
3392
3393 haveYear = true;
3394 year = (wxDateTime_t)num;
3395 break;
3396
3397 case _T('Z'): // timezone name
3398 wxFAIL_MSG(_T("TODO"));
3399 break;
3400
3401 case _T('%'): // a percent sign
3402 if ( *input++ != _T('%') )
3403 {
3404 // no match
3405 return (wxChar *)NULL;
3406 }
3407 break;
3408
3409 case 0: // the end of string
3410 wxFAIL_MSG(_T("unexpected format end"));
3411
3412 // fall through
3413
3414 default: // not a known format spec
3415 return (wxChar *)NULL;
3416 }
3417 }
3418
3419 // format matched, try to construct a date from what we have now
3420 Tm tmDef;
3421 if ( dateDef.IsValid() )
3422 {
3423 // take this date as default
3424 tmDef = dateDef.GetTm();
3425 }
3426 else if ( IsValid() )
3427 {
3428 // if this date is valid, don't change it
3429 tmDef = GetTm();
3430 }
3431 else
3432 {
3433 // no default and this date is invalid - fall back to Today()
3434 tmDef = Today().GetTm();
3435 }
3436
3437 Tm tm = tmDef;
3438
3439 // set the date
3440 if ( haveYear )
3441 {
3442 tm.year = year;
3443 }
3444
3445 // TODO we don't check here that the values are consistent, if both year
3446 // day and month/day were found, we just ignore the year day and we
3447 // also always ignore the week day
3448 if ( haveMon && haveDay )
3449 {
3450 if ( mday > GetNumOfDaysInMonth(tm.year, mon) )
3451 {
3452 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3453
3454 return (wxChar *)NULL;
3455 }
3456
3457 tm.mon = mon;
3458 tm.mday = mday;
3459 }
3460 else if ( haveYDay )
3461 {
3462 if ( yday > GetNumberOfDays(tm.year) )
3463 {
3464 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3465
3466 return (wxChar *)NULL;
3467 }
3468
3469 Tm tm2 = wxDateTime(1, Jan, tm.year).SetToYearDay(yday).GetTm();
3470
3471 tm.mon = tm2.mon;
3472 tm.mday = tm2.mday;
3473 }
3474
3475 // deal with AM/PM
3476 if ( haveHour && hourIsIn12hFormat && isPM )
3477 {
3478 // translate to 24hour format
3479 hour += 12;
3480 }
3481 //else: either already in 24h format or no translation needed
3482
3483 // set the time
3484 if ( haveHour )
3485 {
3486 tm.hour = hour;
3487 }
3488
3489 if ( haveMin )
3490 {
3491 tm.min = min;
3492 }
3493
3494 if ( haveSec )
3495 {
3496 tm.sec = sec;
3497 }
3498
3499 Set(tm);
3500
3501 // finally check that the week day is consistent -- if we had it
3502 if ( haveWDay && GetWeekDay() != wday )
3503 {
3504 wxLogDebug(_T("inconsistsnet week day in wxDateTime::ParseFormat()"));
3505
3506 return NULL;
3507 }
3508
3509 return input;
3510 }
3511
3512 const wxChar *wxDateTime::ParseDateTime(const wxChar *date)
3513 {
3514 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3515
3516 // Set to current day and hour, so strings like '14:00' becomes today at
3517 // 14, not some other random date
3518 wxDateTime dtDate = wxDateTime::Today();
3519 wxDateTime dtTime = wxDateTime::Today();
3520
3521 const wxChar* pchTime;
3522
3523 // Try to parse the beginning of the string as a date
3524 const wxChar* pchDate = dtDate.ParseDate(date);
3525
3526 // We got a date in the beginning, see if there is a time specified after the date
3527 if ( pchDate )
3528 {
3529 // Skip spaces, as the ParseTime() function fails on spaces
3530 while ( wxIsspace(*pchDate) )
3531 pchDate++;
3532
3533 pchTime = dtTime.ParseTime(pchDate);
3534 }
3535 else // no date in the beginning
3536 {
3537 // check and see if we have a time followed by a date
3538 pchTime = dtTime.ParseTime(date);
3539 if ( pchTime )
3540 {
3541 while ( wxIsspace(*pchTime) )
3542 pchTime++;
3543
3544 pchDate = dtDate.ParseDate(pchTime);
3545 }
3546 }
3547
3548 // If we have a date specified, set our own data to the same date
3549 if ( !pchDate || !pchTime )
3550 return NULL;
3551
3552 Set(dtDate.GetDay(), dtDate.GetMonth(), dtDate.GetYear(),
3553 dtTime.GetHour(), dtTime.GetMinute(), dtTime.GetSecond(),
3554 dtTime.GetMillisecond());
3555
3556 // Return endpoint of scan
3557 return pchDate > pchTime ? pchDate : pchTime;
3558 }
3559
3560 const wxChar *wxDateTime::ParseDate(const wxChar *date)
3561 {
3562 // this is a simplified version of ParseDateTime() which understands only
3563 // "today" (for wxDate compatibility) and digits only otherwise (and not
3564 // all esoteric constructions ParseDateTime() knows about)
3565
3566 wxCHECK_MSG( date, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3567
3568 const wxChar *p = date;
3569 while ( wxIsspace(*p) )
3570 p++;
3571
3572 // some special cases
3573 static struct
3574 {
3575 const wxChar *str;
3576 int dayDiffFromToday;
3577 } literalDates[] =
3578 {
3579 { wxTRANSLATE("today"), 0 },
3580 { wxTRANSLATE("yesterday"), -1 },
3581 { wxTRANSLATE("tomorrow"), 1 },
3582 };
3583
3584 for ( size_t n = 0; n < WXSIZEOF(literalDates); n++ )
3585 {
3586 wxString date = wxGetTranslation(literalDates[n].str);
3587 size_t len = date.length();
3588 if ( wxStrlen(p) >= len )
3589 {
3590 wxString str(p, len);
3591 if ( str.CmpNoCase(date) == 0 )
3592 {
3593 // nothing can follow this, so stop here
3594 p += len;
3595
3596 int dayDiffFromToday = literalDates[n].dayDiffFromToday;
3597 *this = Today();
3598 if ( dayDiffFromToday )
3599 {
3600 *this += wxDateSpan::Days(dayDiffFromToday);
3601 }
3602
3603 return p;
3604 }
3605 }
3606 }
3607
3608 // We try to guess what we have here: for each new (numeric) token, we
3609 // determine if it can be a month, day or a year. Of course, there is an
3610 // ambiguity as some numbers may be days as well as months, so we also
3611 // have the ability to back track.
3612
3613 // what do we have?
3614 bool haveDay = false, // the months day?
3615 haveWDay = false, // the day of week?
3616 haveMon = false, // the month?
3617 haveYear = false; // the year?
3618
3619 // and the value of the items we have (init them to get rid of warnings)
3620 WeekDay wday = Inv_WeekDay;
3621 wxDateTime_t day = 0;
3622 wxDateTime::Month mon = Inv_Month;
3623 int year = 0;
3624
3625 // tokenize the string
3626 size_t nPosCur = 0;
3627 static const wxChar *dateDelimiters = _T(".,/-\t\r\n ");
3628 wxStringTokenizer tok(p, dateDelimiters);
3629 while ( tok.HasMoreTokens() )
3630 {
3631 wxString token = tok.GetNextToken();
3632 if ( !token )
3633 continue;
3634
3635 // is it a number?
3636 unsigned long val;
3637 if ( token.ToULong(&val) )
3638 {
3639 // guess what this number is
3640
3641 bool isDay = false,
3642 isMonth = false,
3643 isYear = false;
3644
3645 if ( !haveMon && val > 0 && val <= 12 )
3646 {
3647 // assume it is month
3648 isMonth = true;
3649 }
3650 else // not the month
3651 {
3652 if ( haveDay )
3653 {
3654 // this can only be the year
3655 isYear = true;
3656 }
3657 else // may be either day or year
3658 {
3659 wxDateTime_t max_days = (wxDateTime_t)(
3660 haveMon
3661 ? GetNumOfDaysInMonth(haveYear ? year : Inv_Year, mon)
3662 : 31
3663 );
3664
3665 // can it be day?
3666 if ( (val == 0) || (val > (unsigned long)max_days) )
3667 {
3668 // no
3669 isYear = true;
3670 }
3671 else // yes, suppose it's the day
3672 {
3673 isDay = true;
3674 }
3675 }
3676 }
3677
3678 if ( isYear )
3679 {
3680 if ( haveYear )
3681 break;
3682
3683 haveYear = true;
3684
3685 year = (wxDateTime_t)val;
3686 }
3687 else if ( isDay )
3688 {
3689 if ( haveDay )
3690 break;
3691
3692 haveDay = true;
3693
3694 day = (wxDateTime_t)val;
3695 }
3696 else if ( isMonth )
3697 {
3698 haveMon = true;
3699
3700 mon = (Month)(val - 1);
3701 }
3702 }
3703 else // not a number
3704 {
3705 // be careful not to overwrite the current mon value
3706 Month mon2 = GetMonthFromName(token, Name_Full | Name_Abbr);
3707 if ( mon2 != Inv_Month )
3708 {
3709 // it's a month
3710 if ( haveMon )
3711 {
3712 // but we already have a month - maybe we guessed wrong?
3713 if ( !haveDay )
3714 {
3715 // no need to check in month range as always < 12, but
3716 // the days are counted from 1 unlike the months
3717 day = (wxDateTime_t)(mon + 1);
3718 haveDay = true;
3719 }
3720 else
3721 {
3722 // could possible be the year (doesn't the year come
3723 // before the month in the japanese format?) (FIXME)
3724 break;
3725 }
3726 }
3727
3728 mon = mon2;
3729
3730 haveMon = true;
3731 }
3732 else // not a valid month name
3733 {
3734 wday = GetWeekDayFromName(token, Name_Full | Name_Abbr);
3735 if ( wday != Inv_WeekDay )
3736 {
3737 // a week day
3738 if ( haveWDay )
3739 {
3740 break;
3741 }
3742
3743 haveWDay = true;
3744 }
3745 else // not a valid weekday name
3746 {
3747 // try the ordinals
3748 static const wxChar *ordinals[] =
3749 {
3750 wxTRANSLATE("first"),
3751 wxTRANSLATE("second"),
3752 wxTRANSLATE("third"),
3753 wxTRANSLATE("fourth"),
3754 wxTRANSLATE("fifth"),
3755 wxTRANSLATE("sixth"),
3756 wxTRANSLATE("seventh"),
3757 wxTRANSLATE("eighth"),
3758 wxTRANSLATE("ninth"),
3759 wxTRANSLATE("tenth"),
3760 wxTRANSLATE("eleventh"),
3761 wxTRANSLATE("twelfth"),
3762 wxTRANSLATE("thirteenth"),
3763 wxTRANSLATE("fourteenth"),
3764 wxTRANSLATE("fifteenth"),
3765 wxTRANSLATE("sixteenth"),
3766 wxTRANSLATE("seventeenth"),
3767 wxTRANSLATE("eighteenth"),
3768 wxTRANSLATE("nineteenth"),
3769 wxTRANSLATE("twentieth"),
3770 // that's enough - otherwise we'd have problems with
3771 // composite (or not) ordinals
3772 };
3773
3774 size_t n;
3775 for ( n = 0; n < WXSIZEOF(ordinals); n++ )
3776 {
3777 if ( token.CmpNoCase(ordinals[n]) == 0 )
3778 {
3779 break;
3780 }
3781 }
3782
3783 if ( n == WXSIZEOF(ordinals) )
3784 {
3785 // stop here - something unknown
3786 break;
3787 }
3788
3789 // it's a day
3790 if ( haveDay )
3791 {
3792 // don't try anything here (as in case of numeric day
3793 // above) - the symbolic day spec should always
3794 // precede the month/year
3795 break;
3796 }
3797
3798 haveDay = true;
3799
3800 day = (wxDateTime_t)(n + 1);
3801 }
3802 }
3803 }
3804
3805 nPosCur = tok.GetPosition();
3806 }
3807
3808 // either no more tokens or the scan was stopped by something we couldn't
3809 // parse - in any case, see if we can construct a date from what we have
3810 if ( !haveDay && !haveWDay )
3811 {
3812 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3813
3814 return (wxChar *)NULL;
3815 }
3816
3817 if ( haveWDay && (haveMon || haveYear || haveDay) &&
3818 !(haveDay && haveMon && haveYear) )
3819 {
3820 // without adjectives (which we don't support here) the week day only
3821 // makes sense completely separately or with the full date
3822 // specification (what would "Wed 1999" mean?)
3823 return (wxChar *)NULL;
3824 }
3825
3826 if ( !haveWDay && haveYear && !(haveDay && haveMon) )
3827 {
3828 // may be we have month and day instead of day and year?
3829 if ( haveDay && !haveMon )
3830 {
3831 if ( day <= 12 )
3832 {
3833 // exchange day and month
3834 mon = (wxDateTime::Month)(day - 1);
3835
3836 // we're in the current year then
3837 if ( (year > 0) && (year <= (int)GetNumOfDaysInMonth(Inv_Year, mon)) )
3838 {
3839 day = (wxDateTime_t)year;
3840
3841 haveMon = true;
3842 haveYear = false;
3843 }
3844 //else: no, can't exchange, leave haveMon == false
3845 }
3846 }
3847
3848 if ( !haveMon )
3849 {
3850 // if we give the year, month and day must be given too
3851 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3852
3853 return (wxChar *)NULL;
3854 }
3855 }
3856
3857 if ( !haveMon )
3858 {
3859 mon = GetCurrentMonth();
3860 }
3861
3862 if ( !haveYear )
3863 {
3864 year = GetCurrentYear();
3865 }
3866
3867 if ( haveDay )
3868 {
3869 Set(day, mon, year);
3870
3871 if ( haveWDay )
3872 {
3873 // check that it is really the same
3874 if ( GetWeekDay() != wday )
3875 {
3876 // inconsistency detected
3877 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3878
3879 return (wxChar *)NULL;
3880 }
3881 }
3882 }
3883 else // haveWDay
3884 {
3885 *this = Today();
3886
3887 SetToWeekDayInSameWeek(wday);
3888 }
3889
3890 // return the pointer to the first unparsed char
3891 p += nPosCur;
3892 if ( nPosCur && wxStrchr(dateDelimiters, *(p - 1)) )
3893 {
3894 // if we couldn't parse the token after the delimiter, put back the
3895 // delimiter as well
3896 p--;
3897 }
3898
3899 return p;
3900 }
3901
3902 const wxChar *wxDateTime::ParseTime(const wxChar *time)
3903 {
3904 wxCHECK_MSG( time, (wxChar *)NULL, _T("NULL pointer in wxDateTime::Parse") );
3905
3906 // first try some extra things
3907 static const struct
3908 {
3909 const wxChar *name;
3910 wxDateTime_t hour;
3911 } stdTimes[] =
3912 {
3913 { wxTRANSLATE("noon"), 12 },
3914 { wxTRANSLATE("midnight"), 00 },
3915 // anything else?
3916 };
3917
3918 for ( size_t n = 0; n < WXSIZEOF(stdTimes); n++ )
3919 {
3920 wxString timeString = wxGetTranslation(stdTimes[n].name);
3921 size_t len = timeString.length();
3922 if ( timeString.CmpNoCase(wxString(time, len)) == 0 )
3923 {
3924 // casts required by DigitalMars
3925 Set(stdTimes[n].hour, wxDateTime_t(0), wxDateTime_t(0));
3926
3927 return time + len;
3928 }
3929 }
3930
3931 // try all time formats we may think about in the order from longest to
3932 // shortest
3933
3934 // 12hour with AM/PM?
3935 const wxChar *result = ParseFormat(time, _T("%I:%M:%S %p"));
3936
3937 if ( !result )
3938 {
3939 // normally, it's the same, but why not try it?
3940 result = ParseFormat(time, _T("%H:%M:%S"));
3941 }
3942
3943 if ( !result )
3944 {
3945 // 12hour with AM/PM but without seconds?
3946 result = ParseFormat(time, _T("%I:%M %p"));
3947 }
3948
3949 if ( !result )
3950 {
3951 // without seconds?
3952 result = ParseFormat(time, _T("%H:%M"));
3953 }
3954
3955 if ( !result )
3956 {
3957 // just the hour and AM/PM?
3958 result = ParseFormat(time, _T("%I %p"));
3959 }
3960
3961 if ( !result )
3962 {
3963 // just the hour?
3964 result = ParseFormat(time, _T("%H"));
3965 }
3966
3967 if ( !result )
3968 {
3969 // parse the standard format: normally it is one of the formats above
3970 // but it may be set to something completely different by the user
3971 result = ParseFormat(time, _T("%X"));
3972 }
3973
3974 // TODO: parse timezones
3975
3976 return result;
3977 }
3978
3979 // ----------------------------------------------------------------------------
3980 // Workdays and holidays support
3981 // ----------------------------------------------------------------------------
3982
3983 bool wxDateTime::IsWorkDay(Country WXUNUSED(country)) const
3984 {
3985 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3986 }
3987
3988 // ============================================================================
3989 // wxDateSpan
3990 // ============================================================================
3991
3992 wxDateSpan WXDLLIMPEXP_BASE operator*(int n, const wxDateSpan& ds)
3993 {
3994 wxDateSpan ds1(ds);
3995 return ds1.Multiply(n);
3996 }
3997
3998 // ============================================================================
3999 // wxTimeSpan
4000 // ============================================================================
4001
4002 wxTimeSpan WXDLLIMPEXP_BASE operator*(int n, const wxTimeSpan& ts)
4003 {
4004 return wxTimeSpan(ts).Multiply(n);
4005 }
4006
4007 // this enum is only used in wxTimeSpan::Format() below but we can't declare
4008 // it locally to the method as it provokes an internal compiler error in egcs
4009 // 2.91.60 when building with -O2
4010 enum TimeSpanPart
4011 {
4012 Part_Week,
4013 Part_Day,
4014 Part_Hour,
4015 Part_Min,
4016 Part_Sec,
4017 Part_MSec
4018 };
4019
4020 // not all strftime(3) format specifiers make sense here because, for example,
4021 // a time span doesn't have a year nor a timezone
4022 //
4023 // Here are the ones which are supported (all of them are supported by strftime
4024 // as well):
4025 // %H hour in 24 hour format
4026 // %M minute (00 - 59)
4027 // %S second (00 - 59)
4028 // %% percent sign
4029 //
4030 // Also, for MFC CTimeSpan compatibility, we support
4031 // %D number of days
4032 //
4033 // And, to be better than MFC :-), we also have
4034 // %E number of wEeks
4035 // %l milliseconds (000 - 999)
4036 wxString wxTimeSpan::Format(const wxChar *format) const
4037 {
4038 wxCHECK_MSG( format, wxEmptyString, _T("NULL format in wxTimeSpan::Format") );
4039
4040 wxString str;
4041 str.Alloc(wxStrlen(format));
4042
4043 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
4044 //
4045 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
4046 // question is what should ts.Format("%S") do? The code here returns "3273"
4047 // in this case (i.e. the total number of seconds, not just seconds % 60)
4048 // because, for me, this call means "give me entire time interval in
4049 // seconds" and not "give me the seconds part of the time interval"
4050 //
4051 // If we agree that it should behave like this, it is clear that the
4052 // interpretation of each format specifier depends on the presence of the
4053 // other format specs in the string: if there was "%H" before "%M", we
4054 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
4055
4056 // we remember the most important unit found so far
4057 TimeSpanPart partBiggest = Part_MSec;
4058
4059 for ( const wxChar *pch = format; *pch; pch++ )
4060 {
4061 wxChar ch = *pch;
4062
4063 if ( ch == _T('%') )
4064 {
4065 // the start of the format specification of the printf() below
4066 wxString fmtPrefix = _T('%');
4067
4068 // the number
4069 long n;
4070
4071 ch = *++pch; // get the format spec char
4072 switch ( ch )
4073 {
4074 default:
4075 wxFAIL_MSG( _T("invalid format character") );
4076 // fall through
4077
4078 case _T('%'):
4079 str += ch;
4080
4081 // skip the part below switch
4082 continue;
4083
4084 case _T('D'):
4085 n = GetDays();
4086 if ( partBiggest < Part_Day )
4087 {
4088 n %= DAYS_PER_WEEK;
4089 }
4090 else
4091 {
4092 partBiggest = Part_Day;
4093 }
4094 break;
4095
4096 case _T('E'):
4097 partBiggest = Part_Week;
4098 n = GetWeeks();
4099 break;
4100
4101 case _T('H'):
4102 n = GetHours();
4103 if ( partBiggest < Part_Hour )
4104 {
4105 n %= HOURS_PER_DAY;
4106 }
4107 else
4108 {
4109 partBiggest = Part_Hour;
4110 }
4111
4112 fmtPrefix += _T("02");
4113 break;
4114
4115 case _T('l'):
4116 n = GetMilliseconds().ToLong();
4117 if ( partBiggest < Part_MSec )
4118 {
4119 n %= 1000;
4120 }
4121 //else: no need to reset partBiggest to Part_MSec, it is
4122 // the least significant one anyhow
4123
4124 fmtPrefix += _T("03");
4125 break;
4126
4127 case _T('M'):
4128 n = GetMinutes();
4129 if ( partBiggest < Part_Min )
4130 {
4131 n %= MIN_PER_HOUR;
4132 }
4133 else
4134 {
4135 partBiggest = Part_Min;
4136 }
4137
4138 fmtPrefix += _T("02");
4139 break;
4140
4141 case _T('S'):
4142 n = GetSeconds().ToLong();
4143 if ( partBiggest < Part_Sec )
4144 {
4145 n %= SEC_PER_MIN;
4146 }
4147 else
4148 {
4149 partBiggest = Part_Sec;
4150 }
4151
4152 fmtPrefix += _T("02");
4153 break;
4154 }
4155
4156 str += wxString::Format(fmtPrefix + _T("ld"), n);
4157 }
4158 else
4159 {
4160 // normal character, just copy
4161 str += ch;
4162 }
4163 }
4164
4165 return str;
4166 }
4167
4168 // ============================================================================
4169 // wxDateTimeHolidayAuthority and related classes
4170 // ============================================================================
4171
4172 #include "wx/arrimpl.cpp"
4173
4174 WX_DEFINE_OBJARRAY(wxDateTimeArray);
4175
4176 static int wxCMPFUNC_CONV
4177 wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
4178 {
4179 wxDateTime dt1 = **first,
4180 dt2 = **second;
4181
4182 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
4183 }
4184
4185 // ----------------------------------------------------------------------------
4186 // wxDateTimeHolidayAuthority
4187 // ----------------------------------------------------------------------------
4188
4189 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
4190
4191 /* static */
4192 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
4193 {
4194 size_t count = ms_authorities.size();
4195 for ( size_t n = 0; n < count; n++ )
4196 {
4197 if ( ms_authorities[n]->DoIsHoliday(dt) )
4198 {
4199 return true;
4200 }
4201 }
4202
4203 return false;
4204 }
4205
4206 /* static */
4207 size_t
4208 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
4209 const wxDateTime& dtEnd,
4210 wxDateTimeArray& holidays)
4211 {
4212 wxDateTimeArray hol;
4213
4214 holidays.Clear();
4215
4216 size_t count = ms_authorities.size();
4217 for ( size_t nAuth = 0; nAuth < count; nAuth++ )
4218 {
4219 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
4220
4221 WX_APPEND_ARRAY(holidays, hol);
4222 }
4223
4224 holidays.Sort(wxDateTimeCompareFunc);
4225
4226 return holidays.size();
4227 }
4228
4229 /* static */
4230 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
4231 {
4232 WX_CLEAR_ARRAY(ms_authorities);
4233 }
4234
4235 /* static */
4236 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
4237 {
4238 ms_authorities.push_back(auth);
4239 }
4240
4241 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
4242 {
4243 // required here for Darwin
4244 }
4245
4246 // ----------------------------------------------------------------------------
4247 // wxDateTimeWorkDays
4248 // ----------------------------------------------------------------------------
4249
4250 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
4251 {
4252 wxDateTime::WeekDay wd = dt.GetWeekDay();
4253
4254 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
4255 }
4256
4257 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
4258 const wxDateTime& dtEnd,
4259 wxDateTimeArray& holidays) const
4260 {
4261 if ( dtStart > dtEnd )
4262 {
4263 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
4264
4265 return 0u;
4266 }
4267
4268 holidays.Empty();
4269
4270 // instead of checking all days, start with the first Sat after dtStart and
4271 // end with the last Sun before dtEnd
4272 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
4273 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
4274 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
4275 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
4276 dt;
4277
4278 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
4279 {
4280 holidays.Add(dt);
4281 }
4282
4283 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
4284 {
4285 holidays.Add(dt);
4286 }
4287
4288 return holidays.GetCount();
4289 }
4290
4291 // ============================================================================
4292 // other helper functions
4293 // ============================================================================
4294
4295 // ----------------------------------------------------------------------------
4296 // iteration helpers: can be used to write a for loop over enum variable like
4297 // this:
4298 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
4299 // ----------------------------------------------------------------------------
4300
4301 WXDLLIMPEXP_BASE void wxNextMonth(wxDateTime::Month& m)
4302 {
4303 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
4304
4305 // no wrapping or the for loop above would never end!
4306 m = (wxDateTime::Month)(m + 1);
4307 }
4308
4309 WXDLLIMPEXP_BASE void wxPrevMonth(wxDateTime::Month& m)
4310 {
4311 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
4312
4313 m = m == wxDateTime::Jan ? wxDateTime::Inv_Month
4314 : (wxDateTime::Month)(m - 1);
4315 }
4316
4317 WXDLLIMPEXP_BASE void wxNextWDay(wxDateTime::WeekDay& wd)
4318 {
4319 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
4320
4321 // no wrapping or the for loop above would never end!
4322 wd = (wxDateTime::WeekDay)(wd + 1);
4323 }
4324
4325 WXDLLIMPEXP_BASE void wxPrevWDay(wxDateTime::WeekDay& wd)
4326 {
4327 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
4328
4329 wd = wd == wxDateTime::Sun ? wxDateTime::Inv_WeekDay
4330 : (wxDateTime::WeekDay)(wd - 1);
4331 }
4332
4333 #endif // wxUSE_DATETIME