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