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