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