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