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