]> git.saurik.com Git - wxWidgets.git/blame - src/common/datetime.cpp
made definition of wxUSE_LOG_DEBUG dependent on wxDEBUG_LEVEL and added wxUSE_LOG_TRA...
[wxWidgets.git] / src / common / datetime.cpp
CommitLineData
1ef54dcf 1///////////////////////////////////////////////////////////////////////////////
96531a71 2// Name: src/common/datetime.cpp
0979c962 3// Purpose: implementation of time/date related classes
98919134 4// (for formatting&parsing see datetimefmt.cpp)
0979c962
VZ
5// Author: Vadim Zeitlin
6// Modified by:
7// Created: 11.05.99
8// RCS-ID: $Id$
1ef54dcf
VZ
9// Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10// parts of code taken from sndcal library by Scott E. Lee:
11//
12// Copyright 1993-1995, Scott E. Lee, all rights reserved.
13// Permission granted to use, copy, modify, distribute and sell
14// so long as the above copyright and this permission statement
15// are retained in all copies.
16//
65571936 17// Licence: wxWindows licence
1ef54dcf
VZ
18///////////////////////////////////////////////////////////////////////////////
19
20/*
21 * Implementation notes:
22 *
23 * 1. the time is stored as a 64bit integer containing the signed number of
299fcbfe
VZ
24 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
25 * expressed in GMT.
1ef54dcf
VZ
26 *
27 * 2. the range is thus something about 580 million years, but due to current
28 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 *
30 * 3. standard ANSI C functions are used to do time calculations whenever
31 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 *
33 * 4. otherwise, the calculations are done by converting the date to/from JDN
34 * first (the range limitation mentioned above comes from here: the
35 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
36 * or less)
37 *
299fcbfe
VZ
38 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
39 * this moment in local time and may be converted to the object
40 * corresponding to the same date/time in another time zone by using
41 * ToTimezone()
42 *
43 * 6. the conversions to the current (or any other) timezone are done when the
44 * internal time representation is converted to the broken-down one in
45 * wxDateTime::Tm.
1ef54dcf 46 */
0979c962
VZ
47
48// ============================================================================
49// declarations
50// ============================================================================
51
52// ----------------------------------------------------------------------------
53// headers
54// ----------------------------------------------------------------------------
55
0979c962
VZ
56// For compilers that support precompilation, includes "wx.h".
57#include "wx/wxprec.h"
58
59#ifdef __BORLANDC__
60 #pragma hdrstop
61#endif
62
1e6feb95
VZ
63#if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
64
0979c962 65#ifndef WX_PRECOMP
57bd4c60
WS
66 #ifdef __WXMSW__
67 #include "wx/msw/wrapwin.h"
68 #endif
0979c962 69 #include "wx/string.h"
0979c962 70 #include "wx/log.h"
88a7a4e1 71 #include "wx/intl.h"
bb90a3e6 72 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
02761f6c 73 #include "wx/module.h"
0bf751e7 74 #include "wx/crt.h"
0979c962
VZ
75#endif // WX_PRECOMP
76
fcc3d7cb 77#include "wx/thread.h"
cd0b1709 78#include "wx/tokenzr.h"
fcc3d7cb 79
ff0ea71c
GT
80#include <ctype.h>
81
64f9c100 82#ifdef __WINDOWS__
64f9c100 83 #include <winnls.h>
74b99d0f
WS
84 #ifndef __WXWINCE__
85 #include <locale.h>
86 #endif
64f9c100
VS
87#endif
88
0979c962
VZ
89#include "wx/datetime.h"
90
48fd6e9d
FM
91// ----------------------------------------------------------------------------
92// wxXTI
93// ----------------------------------------------------------------------------
bd4a25bc 94
cb73e600
SC
95#if wxUSE_EXTENDED_RTTI
96
97template<> void wxStringReadValue(const wxString &s , wxDateTime &data )
98{
1fcca711 99 data.ParseFormat(s,"%Y-%m-%d %H:%M:%S", NULL);
cb73e600
SC
100}
101
102template<> void wxStringWriteValue(wxString &s , const wxDateTime &data )
103{
c20d5805 104 s = data.Format("%Y-%m-%d %H:%M:%S");
cb73e600
SC
105}
106
8805dbab 107wxCUSTOM_TYPE_INFO(wxDateTime, wxToStringConverter<wxDateTime> , wxFromStringConverter<wxDateTime>)
cb73e600 108
c20d5805 109#endif // wxUSE_EXTENDED_RTTI
cb73e600 110
48fd6e9d 111
f0f951fa
VZ
112// ----------------------------------------------------------------------------
113// conditional compilation
114// ----------------------------------------------------------------------------
6de20863 115
31907d03
SC
116#if defined(__MWERKS__) && wxUSE_UNICODE
117 #include <wtime.h>
118#endif
119
0779cc9a 120#if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
6a27c749
WS
121 #if defined(__WXPALMOS__)
122 #define WX_GMTOFF_IN_TM
123 #elif 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
e09080ec 145 #elif defined(__WXWINCE__) && defined(__VISUALC8__)
44061d36 146 // _timezone is not present in dynamic run-time library
b667edae 147 #if 0
791b07a3
JS
148 // Solution (1): use the function equivalent of _timezone
149 static long wxGetTimeZone()
150 {
151 static long s_Timezone = MAXLONG; // invalid timezone
152 if (s_Timezone == MAXLONG)
153 {
154 int t;
155 _get_timezone(& t);
156 s_Timezone = (long) t;
157 }
158 return s_Timezone;
159 }
160 #define WX_TIMEZONE wxGetTimeZone()
b667edae 161 #elif 1
791b07a3 162 // Solution (2): using GetTimeZoneInformation
44061d36
JS
163 static long wxGetTimeZone()
164 {
165 static long timezone = MAXLONG; // invalid timezone
166 if (timezone == MAXLONG)
167 {
168 TIME_ZONE_INFORMATION tzi;
169 ::GetTimeZoneInformation(&tzi);
170 timezone = tzi.Bias;
171 }
172 return timezone;
173 }
174 #define WX_TIMEZONE wxGetTimeZone()
175 #else
791b07a3 176 // Old method using _timezone: this symbol doesn't exist in the dynamic run-time library (i.e. using /MD)
e09080ec 177 #define WX_TIMEZONE _timezone
44061d36 178 #endif
f0f951fa
VZ
179 #else // unknown platform - try timezone
180 #define WX_TIMEZONE timezone
181 #endif
0779cc9a 182#endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
c25a510b 183
e09080ec
VZ
184// NB: VC8 safe time functions could/should be used for wxMSW as well probably
185#if defined(__WXWINCE__) && defined(__VISUALC8__)
186
187struct tm *wxLocaltime_r(const time_t *t, struct tm* tm)
188{
189 __time64_t t64 = *t;
190 return _localtime64_s(tm, &t64) == 0 ? tm : NULL;
191}
192
193struct tm *wxGmtime_r(const time_t* t, struct tm* tm)
194{
195 __time64_t t64 = *t;
196 return _gmtime64_s(tm, &t64) == 0 ? tm : NULL;
197}
198
199#else // !wxWinCE with VC8
200
5b52a684 201#if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
cf44a61c
SN
202static wxMutex timeLock;
203#endif
204
205#ifndef HAVE_LOCALTIME_R
206struct tm *wxLocaltime_r(const time_t* ticks, struct tm* temp)
207{
208#if wxUSE_THREADS && !defined(__WINDOWS__)
209 // No need to waste time with a mutex on windows since it's using
210 // thread local storage for localtime anyway.
6f721331 211 wxMutexLocker locker(timeLock);
cf44a61c 212#endif
55809d13
VZ
213
214 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
215#ifdef __BORLANDC__
216 if ( !*ticks )
217 return NULL;
218#endif
219
220 const tm * const t = localtime(ticks);
221 if ( !t )
222 return NULL;
223
224 memcpy(temp, t, sizeof(struct tm));
cf44a61c
SN
225 return temp;
226}
e09080ec 227#endif // !HAVE_LOCALTIME_R
cf44a61c
SN
228
229#ifndef HAVE_GMTIME_R
230struct tm *wxGmtime_r(const time_t* ticks, struct tm* temp)
231{
232#if wxUSE_THREADS && !defined(__WINDOWS__)
233 // No need to waste time with a mutex on windows since it's
234 // using thread local storage for gmtime anyway.
6f721331 235 wxMutexLocker locker(timeLock);
cf44a61c 236#endif
55809d13
VZ
237
238#ifdef __BORLANDC__
239 if ( !*ticks )
240 return NULL;
241#endif
242
243 const tm * const t = gmtime(ticks);
244 if ( !t )
245 return NULL;
246
cf44a61c
SN
247 memcpy(temp, gmtime(ticks), sizeof(struct tm));
248 return temp;
249}
e09080ec
VZ
250#endif // !HAVE_GMTIME_R
251
252#endif // wxWinCE with VC8/other platforms
cf44a61c 253
384223b3
VZ
254// ----------------------------------------------------------------------------
255// macros
256// ----------------------------------------------------------------------------
257
258// debugging helper: just a convenient replacement of wxCHECK()
637b7e4f
VZ
259#define wxDATETIME_CHECK(expr, msg) \
260 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
384223b3 261
4f6aed9c
VZ
262// ----------------------------------------------------------------------------
263// private classes
264// ----------------------------------------------------------------------------
265
266class wxDateTimeHolidaysModule : public wxModule
267{
268public:
269 virtual bool OnInit()
270 {
271 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays);
272
68379eaf 273 return true;
4f6aed9c
VZ
274 }
275
276 virtual void OnExit()
277 {
278 wxDateTimeHolidayAuthority::ClearAllAuthorities();
df5168c4 279 wxDateTimeHolidayAuthority::ms_authorities.clear();
4f6aed9c
VZ
280 }
281
282private:
283 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule)
284};
285
286IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule, wxModule)
287
b76b015e
VZ
288// ----------------------------------------------------------------------------
289// constants
290// ----------------------------------------------------------------------------
291
e6ec579c 292// some trivial ones
fcc3d7cb
VZ
293static const int MONTHS_IN_YEAR = 12;
294
df05cdc5
VZ
295static const int SEC_PER_MIN = 60;
296
297static const int MIN_PER_HOUR = 60;
298
299static const int HOURS_PER_DAY = 24;
fcc3d7cb 300
e6ec579c
VZ
301static const long SECONDS_PER_DAY = 86400l;
302
df05cdc5
VZ
303static const int DAYS_PER_WEEK = 7;
304
e6ec579c
VZ
305static const long MILLISECONDS_PER_DAY = 86400000l;
306
307// this is the integral part of JDN of the midnight of Jan 1, 1970
308// (i.e. JDN(Jan 1, 1970) = 2440587.5)
cd0b1709 309static const long EPOCH_JDN = 2440587l;
b76b015e 310
4b6a582b
VZ
311// these values are only used in asserts so don't define them if asserts are
312// disabled to avoid warnings about unused static variables
313#if wxDEBUG_LEVEL
1ef54dcf
VZ
314// the date of JDN -0.5 (as we don't work with fractional parts, this is the
315// reference date for us) is Nov 24, 4714BC
316static const int JDN_0_YEAR = -4713;
317static const int JDN_0_MONTH = wxDateTime::Nov;
318static const int JDN_0_DAY = 24;
4b6a582b 319#endif // wxDEBUG_LEVEL
1ef54dcf
VZ
320
321// the constants used for JDN calculations
cd0b1709
VZ
322static const long JDN_OFFSET = 32046l;
323static const long DAYS_PER_5_MONTHS = 153l;
324static const long DAYS_PER_4_YEARS = 1461l;
325static const long DAYS_PER_400_YEARS = 146097l;
1ef54dcf 326
f0f951fa
VZ
327// this array contains the cumulated number of days in all previous months for
328// normal and leap years
329static const wxDateTime::wxDateTime_t gs_cumulatedDays[2][MONTHS_IN_YEAR] =
330{
331 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
332 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
333};
334
48fd6e9d
FM
335const long wxDateTime::TIME_T_FACTOR = 1000l;
336
fcc3d7cb 337// ----------------------------------------------------------------------------
2ef31e80
VZ
338// global data
339// ----------------------------------------------------------------------------
340
71ebd60b
VZ
341const char *wxDefaultDateTimeFormat = "%c";
342const char *wxDefaultTimeSpanFormat = "%H:%M:%S";
1aaf88d2 343
384223b3
VZ
344// in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
345// indicate an invalid wxDateTime object
56d0c5a6 346const wxDateTime wxDefaultDateTime;
2ef31e80
VZ
347
348wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
349
b76b015e
VZ
350// ----------------------------------------------------------------------------
351// private functions
352// ----------------------------------------------------------------------------
353
4b6a582b
VZ
354// debugger helper: this function can be called from a debugger to show what
355// the date really is
77fa3d82 356extern const char *wxDumpDate(const wxDateTime* dt)
4f6aed9c 357{
77fa3d82 358 static char buf[128];
4f6aed9c 359
77fa3d82 360 wxString fmt(dt->Format("%Y-%m-%d (%a) %H:%M:%S"));
b3483429
VZ
361 wxStrlcpy(buf,
362 (fmt + " (" + dt->GetValue().ToString() + " ticks)").ToAscii(),
77fa3d82 363 WXSIZEOF(buf));
4f6aed9c
VZ
364
365 return buf;
366}
4f6aed9c 367
fcc3d7cb 368// get the number of days in the given month of the given year
c4e08560 369static inline
fcc3d7cb
VZ
370wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
371{
e6ec579c
VZ
372 // the number of days in month in Julian/Gregorian calendar: the first line
373 // is for normal years, the second one is for the leap ones
374 static wxDateTime::wxDateTime_t daysInMonth[2][MONTHS_IN_YEAR] =
375 {
376 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
377 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
378 };
379
380 return daysInMonth[wxDateTime::IsLeapYear(year)][month];
fcc3d7cb
VZ
381}
382
c5432233
VZ
383// returns the time zone in the C sense, i.e. the difference UTC - local
384// (in seconds)
1ee2f9d9
FM
385// NOTE: not static because used by datetimefmt.cpp
386int GetTimeZone()
fcc3d7cb 387{
68379eaf
WS
388 // set to true when the timezone is set
389 static bool s_timezoneSet = false;
0779cc9a 390 static long gmtoffset = LONG_MAX; // invalid timezone
c5432233 391
a452689b 392 // ensure that the timezone variable is set by calling wxLocaltime_r
fcc3d7cb
VZ
393 if ( !s_timezoneSet )
394 {
a452689b
SN
395 // just call wxLocaltime_r() instead of figuring out whether this
396 // system supports tzset(), _tzset() or something else
c5432233 397 time_t t = 0;
3d561414 398 struct tm tm;
fcc3d7cb 399
3d561414 400 wxLocaltime_r(&t, &tm);
68379eaf 401 s_timezoneSet = true;
c5432233 402
44c930eb 403#ifdef WX_GMTOFF_IN_TM
c5432233
VZ
404 // note that GMT offset is the opposite of time zone and so to return
405 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
406 // cases we have to negate it
3d561414 407 gmtoffset = -tm.tm_gmtoff;
44c930eb
JG
408#else // !WX_GMTOFF_IN_TM
409 gmtoffset = WX_TIMEZONE;
410#endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
fcc3d7cb
VZ
411 }
412
0779cc9a 413 return (int)gmtoffset;
fcc3d7cb
VZ
414}
415
e6ec579c 416// return the integral part of the JDN for the midnight of the given date (to
1ef54dcf
VZ
417// get the real JDN you need to add 0.5, this is, in fact, JDN of the
418// noon of the previous day)
e6ec579c
VZ
419static long GetTruncatedJDN(wxDateTime::wxDateTime_t day,
420 wxDateTime::Month mon,
421 int year)
422{
1ef54dcf
VZ
423 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
424
425 // check the date validity
426 wxASSERT_MSG(
427 (year > JDN_0_YEAR) ||
428 ((year == JDN_0_YEAR) && (mon > JDN_0_MONTH)) ||
429 ((year == JDN_0_YEAR) && (mon == JDN_0_MONTH) && (day >= JDN_0_DAY)),
430 _T("date out of range - can't convert to JDN")
431 );
432
433 // make the year positive to avoid problems with negative numbers division
434 year += 4800;
435
436 // months are counted from March here
437 int month;
438 if ( mon >= wxDateTime::Mar )
e6ec579c 439 {
1ef54dcf 440 month = mon - 2;
e6ec579c 441 }
1ef54dcf 442 else
e6ec579c 443 {
1ef54dcf
VZ
444 month = mon + 10;
445 year--;
446 }
e6ec579c 447
1ef54dcf
VZ
448 // now we can simply add all the contributions together
449 return ((year / 100) * DAYS_PER_400_YEARS) / 4
450 + ((year % 100) * DAYS_PER_4_YEARS) / 4
451 + (month * DAYS_PER_5_MONTHS + 2) / 5
452 + day
453 - JDN_OFFSET;
e6ec579c
VZ
454}
455
bb7afa49
VZ
456#ifdef HAVE_STRFTIME
457
2423ef22 458// this function is a wrapper around strftime(3) adding error checking
1ee2f9d9
FM
459// NOTE: not static because used by datetimefmt.cpp
460wxString CallStrftime(const wxString& format, const tm* tm)
b76b015e 461{
68ee7c47 462 wxChar buf[4096];
594588aa
MW
463 // Create temp wxString here to work around mingw/cygwin bug 1046059
464 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
465 wxString s;
466
ba9bbf13 467 if ( !wxStrftime(buf, WXSIZEOF(buf), format, tm) )
b76b015e 468 {
adec277f 469 // if the format is valid, buffer must be too small?
b76b015e 470 wxFAIL_MSG(_T("strftime() failed"));
adec277f
VZ
471
472 buf[0] = '\0';
b76b015e
VZ
473 }
474
594588aa
MW
475 s = buf;
476 return s;
b76b015e 477}
bb7afa49
VZ
478
479#endif // HAVE_STRFTIME
b76b015e 480
2f02cb89
VZ
481// if year and/or month have invalid values, replace them with the current ones
482static void ReplaceDefaultYearMonthWithCurrent(int *year,
483 wxDateTime::Month *month)
484{
485 struct tm *tmNow = NULL;
a452689b 486 struct tm tmstruct;
2f02cb89
VZ
487
488 if ( *year == wxDateTime::Inv_Year )
489 {
a452689b 490 tmNow = wxDateTime::GetTmNow(&tmstruct);
2f02cb89
VZ
491
492 *year = 1900 + tmNow->tm_year;
493 }
494
495 if ( *month == wxDateTime::Inv_Month )
496 {
497 if ( !tmNow )
a452689b 498 tmNow = wxDateTime::GetTmNow(&tmstruct);
2f02cb89
VZ
499
500 *month = (wxDateTime::Month)tmNow->tm_mon;
501 }
502}
503
1ee2f9d9
FM
504// fill the struct tm with default values
505// NOTE: not static because used by datetimefmt.cpp
506void InitTm(struct tm& tm)
f0f951fa
VZ
507{
508 // struct tm may have etxra fields (undocumented and with unportable
509 // names) which, nevertheless, must be set to 0
510 memset(&tm, 0, sizeof(struct tm));
511
512 tm.tm_mday = 1; // mday 0 is invalid
513 tm.tm_year = 76; // any valid year
514 tm.tm_isdst = -1; // auto determine
515}
516
0979c962
VZ
517// ============================================================================
518// implementation of wxDateTime
519// ============================================================================
520
b76b015e
VZ
521// ----------------------------------------------------------------------------
522// struct Tm
523// ----------------------------------------------------------------------------
524
525wxDateTime::Tm::Tm()
526{
527 year = (wxDateTime_t)wxDateTime::Inv_Year;
528 mon = wxDateTime::Inv_Month;
529 mday = 0;
e6ec579c 530 hour = min = sec = msec = 0;
b76b015e
VZ
531 wday = wxDateTime::Inv_WeekDay;
532}
533
299fcbfe
VZ
534wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
535 : m_tz(tz)
b76b015e 536{
e6ec579c 537 msec = 0;
907173e5
WS
538 sec = (wxDateTime::wxDateTime_t)tm.tm_sec;
539 min = (wxDateTime::wxDateTime_t)tm.tm_min;
540 hour = (wxDateTime::wxDateTime_t)tm.tm_hour;
541 mday = (wxDateTime::wxDateTime_t)tm.tm_mday;
fcc3d7cb 542 mon = (wxDateTime::Month)tm.tm_mon;
b76b015e 543 year = 1900 + tm.tm_year;
bb8a8478
WS
544 wday = (wxDateTime::wxDateTime_t)tm.tm_wday;
545 yday = (wxDateTime::wxDateTime_t)tm.tm_yday;
b76b015e
VZ
546}
547
548bool wxDateTime::Tm::IsValid() const
549{
550 // we allow for the leap seconds, although we don't use them (yet)
fcc3d7cb 551 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
c5a1681b 552 (mday <= GetNumOfDaysInMonth(year, mon)) &&
e6ec579c 553 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
b76b015e
VZ
554}
555
556void wxDateTime::Tm::ComputeWeekDay()
557{
c5a1681b
VZ
558 // compute the week day from day/month/year: we use the dumbest algorithm
559 // possible: just compute our JDN and then use the (simple to derive)
560 // formula: weekday = (JDN + 1.5) % 7
5a572f6c 561 wday = (wxDateTime::wxDateTime_t)((GetTruncatedJDN(mday, mon, year) + 2) % 7);
b76b015e
VZ
562}
563
e6ec579c 564void wxDateTime::Tm::AddMonths(int monDiff)
fcc3d7cb
VZ
565{
566 // normalize the months field
567 while ( monDiff < -mon )
568 {
569 year--;
570
571 monDiff += MONTHS_IN_YEAR;
572 }
573
2ef31e80 574 while ( monDiff + mon >= MONTHS_IN_YEAR )
fcc3d7cb
VZ
575 {
576 year++;
239446b4
VZ
577
578 monDiff -= MONTHS_IN_YEAR;
fcc3d7cb
VZ
579 }
580
581 mon = (wxDateTime::Month)(mon + monDiff);
582
e6ec579c 583 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
4f6aed9c
VZ
584
585 // NB: we don't check here that the resulting date is valid, this function
586 // is private and the caller must check it if needed
fcc3d7cb
VZ
587}
588
e6ec579c 589void wxDateTime::Tm::AddDays(int dayDiff)
fcc3d7cb
VZ
590{
591 // normalize the days field
9d9b7755 592 while ( dayDiff + mday < 1 )
fcc3d7cb
VZ
593 {
594 AddMonths(-1);
595
9d9b7755 596 dayDiff += GetNumOfDaysInMonth(year, mon);
fcc3d7cb
VZ
597 }
598
907173e5 599 mday = (wxDateTime::wxDateTime_t)( mday + dayDiff );
fcc3d7cb
VZ
600 while ( mday > GetNumOfDaysInMonth(year, mon) )
601 {
602 mday -= GetNumOfDaysInMonth(year, mon);
603
604 AddMonths(1);
605 }
606
607 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
608 _T("logic error") );
609}
610
611// ----------------------------------------------------------------------------
612// class TimeZone
613// ----------------------------------------------------------------------------
614
615wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
616{
617 switch ( tz )
618 {
619 case wxDateTime::Local:
299fcbfe
VZ
620 // get the offset from C RTL: it returns the difference GMT-local
621 // while we want to have the offset _from_ GMT, hence the '-'
622 m_offset = -GetTimeZone();
fcc3d7cb
VZ
623 break;
624
625 case wxDateTime::GMT_12:
626 case wxDateTime::GMT_11:
627 case wxDateTime::GMT_10:
628 case wxDateTime::GMT_9:
629 case wxDateTime::GMT_8:
630 case wxDateTime::GMT_7:
631 case wxDateTime::GMT_6:
632 case wxDateTime::GMT_5:
633 case wxDateTime::GMT_4:
634 case wxDateTime::GMT_3:
635 case wxDateTime::GMT_2:
636 case wxDateTime::GMT_1:
299fcbfe 637 m_offset = -3600*(wxDateTime::GMT0 - tz);
fcc3d7cb
VZ
638 break;
639
640 case wxDateTime::GMT0:
641 case wxDateTime::GMT1:
642 case wxDateTime::GMT2:
643 case wxDateTime::GMT3:
644 case wxDateTime::GMT4:
645 case wxDateTime::GMT5:
646 case wxDateTime::GMT6:
647 case wxDateTime::GMT7:
648 case wxDateTime::GMT8:
649 case wxDateTime::GMT9:
650 case wxDateTime::GMT10:
651 case wxDateTime::GMT11:
652 case wxDateTime::GMT12:
34f90a1c 653 case wxDateTime::GMT13:
299fcbfe 654 m_offset = 3600*(tz - wxDateTime::GMT0);
fcc3d7cb
VZ
655 break;
656
657 case wxDateTime::A_CST:
658 // Central Standard Time in use in Australia = UTC + 9.5
d26adb9d 659 m_offset = 60l*(9*MIN_PER_HOUR + MIN_PER_HOUR/2);
fcc3d7cb
VZ
660 break;
661
662 default:
663 wxFAIL_MSG( _T("unknown time zone") );
664 }
665}
666
b76b015e
VZ
667// ----------------------------------------------------------------------------
668// static functions
669// ----------------------------------------------------------------------------
670
1ee2f9d9
FM
671/* static */
672struct tm *wxDateTime::GetTmNow(struct tm *tmstruct)
673{
674 time_t t = GetTimeNow();
675 return wxLocaltime_r(&t, tmstruct);
676}
677
b76b015e
VZ
678/* static */
679bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
680{
2f02cb89
VZ
681 if ( year == Inv_Year )
682 year = GetCurrentYear();
683
b76b015e
VZ
684 if ( cal == Gregorian )
685 {
686 // in Gregorian calendar leap years are those divisible by 4 except
687 // those divisible by 100 unless they're also divisible by 400
688 // (in some countries, like Russia and Greece, additional corrections
689 // exist, but they won't manifest themselves until 2700)
690 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
691 }
692 else if ( cal == Julian )
693 {
694 // in Julian calendar the rule is simpler
695 return year % 4 == 0;
696 }
697 else
698 {
699 wxFAIL_MSG(_T("unknown calendar"));
700
68379eaf 701 return false;
b76b015e
VZ
702 }
703}
704
fcc3d7cb
VZ
705/* static */
706int wxDateTime::GetCentury(int year)
707{
708 return year > 0 ? year / 100 : year / 100 - 1;
709}
710
b76b015e
VZ
711/* static */
712int wxDateTime::ConvertYearToBC(int year)
713{
714 // year 0 is BC 1
715 return year > 0 ? year : year - 1;
716}
717
718/* static */
719int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
720{
721 switch ( cal )
722 {
723 case Gregorian:
724 return Now().GetYear();
725
726 case Julian:
727 wxFAIL_MSG(_T("TODO"));
728 break;
729
730 default:
731 wxFAIL_MSG(_T("unsupported calendar"));
732 break;
733 }
734
735 return Inv_Year;
736}
737
738/* static */
739wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
740{
741 switch ( cal )
742 {
743 case Gregorian:
744 return Now().GetMonth();
b76b015e
VZ
745
746 case Julian:
747 wxFAIL_MSG(_T("TODO"));
748 break;
749
750 default:
751 wxFAIL_MSG(_T("unsupported calendar"));
752 break;
753 }
754
755 return Inv_Month;
756}
757
2f02cb89
VZ
758/* static */
759wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
760{
761 if ( year == Inv_Year )
762 {
763 // take the current year if none given
764 year = GetCurrentYear();
765 }
766
767 switch ( cal )
768 {
769 case Gregorian:
770 case Julian:
771 return IsLeapYear(year) ? 366 : 365;
2f02cb89
VZ
772
773 default:
774 wxFAIL_MSG(_T("unsupported calendar"));
775 break;
776 }
777
778 return 0;
779}
780
b76b015e
VZ
781/* static */
782wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
783 int year,
784 wxDateTime::Calendar cal)
785{
fcc3d7cb 786 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
b76b015e
VZ
787
788 if ( cal == Gregorian || cal == Julian )
789 {
790 if ( year == Inv_Year )
791 {
792 // take the current year if none given
793 year = GetCurrentYear();
794 }
795
fcc3d7cb 796 return GetNumOfDaysInMonth(year, month);
b76b015e
VZ
797 }
798 else
799 {
800 wxFAIL_MSG(_T("unsupported calendar"));
801
802 return 0;
803 }
804}
805
806/* static */
f0f951fa
VZ
807wxString wxDateTime::GetMonthName(wxDateTime::Month month,
808 wxDateTime::NameFlags flags)
b76b015e 809{
525d8583 810 wxCHECK_MSG( month != Inv_Month, wxEmptyString, _T("invalid month") );
bb7afa49 811#ifdef HAVE_STRFTIME
68ee7c47
VZ
812 // notice that we must set all the fields to avoid confusing libc (GNU one
813 // gets confused to a crash if we don't do this)
cd0b1709 814 tm tm;
f0f951fa 815 InitTm(tm);
cd0b1709 816 tm.tm_mon = month;
b76b015e 817
f0f951fa 818 return CallStrftime(flags == Name_Abbr ? _T("%b") : _T("%B"), &tm);
bb7afa49 819#else // !HAVE_STRFTIME
ba9bbf13
WS
820 wxString ret;
821 switch(month)
822 {
823 case Jan:
824 ret = (flags == Name_Abbr ? wxT("Jan"): wxT("January"));
825 break;
826 case Feb:
827 ret = (flags == Name_Abbr ? wxT("Feb"): wxT("Febuary"));
828 break;
829 case Mar:
830 ret = (flags == Name_Abbr ? wxT("Mar"): wxT("March"));
831 break;
832 case Apr:
833 ret = (flags == Name_Abbr ? wxT("Apr"): wxT("April"));
834 break;
835 case May:
836 ret = (flags == Name_Abbr ? wxT("May"): wxT("May"));
837 break;
838 case Jun:
839 ret = (flags == Name_Abbr ? wxT("Jun"): wxT("June"));
840 break;
841 case Jul:
842 ret = (flags == Name_Abbr ? wxT("Jul"): wxT("July"));
843 break;
844 case Aug:
845 ret = (flags == Name_Abbr ? wxT("Aug"): wxT("August"));
846 break;
847 case Sep:
848 ret = (flags == Name_Abbr ? wxT("Sep"): wxT("September"));
849 break;
850 case Oct:
851 ret = (flags == Name_Abbr ? wxT("Oct"): wxT("October"));
852 break;
853 case Nov:
854 ret = (flags == Name_Abbr ? wxT("Nov"): wxT("November"));
855 break;
856 case Dec:
857 ret = (flags == Name_Abbr ? wxT("Dec"): wxT("December"));
858 break;
859 }
860 return ret;
bb7afa49 861#endif // HAVE_STRFTIME/!HAVE_STRFTIME
b76b015e
VZ
862}
863
864/* static */
f0f951fa
VZ
865wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday,
866 wxDateTime::NameFlags flags)
b76b015e 867{
525d8583 868 wxCHECK_MSG( wday != Inv_WeekDay, wxEmptyString, _T("invalid weekday") );
bb7afa49 869#ifdef HAVE_STRFTIME
2c622d71
VZ
870 // take some arbitrary Sunday (but notice that the day should be such that
871 // after adding wday to it below we still have a valid date, e.g. don't
872 // take 28 here!)
f0f951fa
VZ
873 tm tm;
874 InitTm(tm);
2c622d71 875 tm.tm_mday = 21;
f0f951fa
VZ
876 tm.tm_mon = Nov;
877 tm.tm_year = 99;
b76b015e 878
1ef54dcf 879 // and offset it by the number of days needed to get the correct wday
b76b015e
VZ
880 tm.tm_mday += wday;
881
c5a1681b
VZ
882 // call mktime() to normalize it...
883 (void)mktime(&tm);
884
885 // ... and call strftime()
f0f951fa 886 return CallStrftime(flags == Name_Abbr ? _T("%a") : _T("%A"), &tm);
bb7afa49 887#else // !HAVE_STRFTIME
ba9bbf13
WS
888 wxString ret;
889 switch(wday)
890 {
891 case Sun:
892 ret = (flags == Name_Abbr ? wxT("Sun") : wxT("Sunday"));
893 break;
894 case Mon:
895 ret = (flags == Name_Abbr ? wxT("Mon") : wxT("Monday"));
896 break;
897 case Tue:
898 ret = (flags == Name_Abbr ? wxT("Tue") : wxT("Tuesday"));
899 break;
900 case Wed:
901 ret = (flags == Name_Abbr ? wxT("Wed") : wxT("Wednesday"));
902 break;
903 case Thu:
904 ret = (flags == Name_Abbr ? wxT("Thu") : wxT("Thursday"));
905 break;
906 case Fri:
907 ret = (flags == Name_Abbr ? wxT("Fri") : wxT("Friday"));
908 break;
909 case Sat:
910 ret = (flags == Name_Abbr ? wxT("Sat") : wxT("Saturday"));
911 break;
912 }
913 return ret;
bb7afa49 914#endif // HAVE_STRFTIME/!HAVE_STRFTIME
f0f951fa
VZ
915}
916
917/* static */
918void wxDateTime::GetAmPmStrings(wxString *am, wxString *pm)
919{
920 tm tm;
921 InitTm(tm);
653567bb 922 wxChar buffer[64];
0308fd61
JS
923 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
924 // and causes an assertion failed if the buffer is to small (which is good) - OR -
925 // if strftime does not return anything because the format string is invalid - OR -
926 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
927 // wxDateTime::ParseTime will try several different formats to parse the time.
928 // As a result, GetAmPmStrings might get called, even if the current locale
929 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
930 // assert, even though it is a perfectly legal use.
f0f951fa
VZ
931 if ( am )
932 {
10a2749b 933 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
0308fd61
JS
934 *am = wxString(buffer);
935 else
936 *am = wxString();
f0f951fa
VZ
937 }
938 if ( pm )
939 {
940 tm.tm_hour = 13;
10a2749b 941 if (wxStrftime(buffer, sizeof(buffer)/sizeof(wxChar), _T("%p"), &tm) > 0)
0308fd61
JS
942 *pm = wxString(buffer);
943 else
944 *pm = wxString();
f0f951fa 945 }
b76b015e
VZ
946}
947
54e660f8 948
239446b4
VZ
949// ----------------------------------------------------------------------------
950// Country stuff: date calculations depend on the country (DST, work days,
951// ...), so we need to know which rules to follow.
952// ----------------------------------------------------------------------------
953
954/* static */
955wxDateTime::Country wxDateTime::GetCountry()
956{
f0f951fa 957 // TODO use LOCALE_ICOUNTRY setting under Win32
77b88df2 958#ifndef __WXWINCE__
239446b4
VZ
959 if ( ms_country == Country_Unknown )
960 {
961 // try to guess from the time zone name
962 time_t t = time(NULL);
a452689b
SN
963 struct tm tmstruct;
964 struct tm *tm = wxLocaltime_r(&t, &tmstruct);
239446b4
VZ
965
966 wxString tz = CallStrftime(_T("%Z"), tm);
967 if ( tz == _T("WET") || tz == _T("WEST") )
968 {
969 ms_country = UK;
970 }
971 else if ( tz == _T("CET") || tz == _T("CEST") )
972 {
973 ms_country = Country_EEC;
974 }
975 else if ( tz == _T("MSK") || tz == _T("MSD") )
976 {
977 ms_country = Russia;
978 }
979 else if ( tz == _T("AST") || tz == _T("ADT") ||
980 tz == _T("EST") || tz == _T("EDT") ||
981 tz == _T("CST") || tz == _T("CDT") ||
982 tz == _T("MST") || tz == _T("MDT") ||
983 tz == _T("PST") || tz == _T("PDT") )
984 {
985 ms_country = USA;
986 }
987 else
988 {
989 // well, choose a default one
990 ms_country = USA;
991 }
992 }
bb7afa49 993#else // __WXWINCE__
77b88df2 994 ms_country = USA;
bb7afa49 995#endif // !__WXWINCE__/__WXWINCE__
239446b4
VZ
996
997 return ms_country;
998}
999
1000/* static */
1001void wxDateTime::SetCountry(wxDateTime::Country country)
1002{
1003 ms_country = country;
1004}
1005
1006/* static */
1007bool wxDateTime::IsWestEuropeanCountry(Country country)
1008{
1009 if ( country == Country_Default )
1010 {
1011 country = GetCountry();
1012 }
1013
1014 return (Country_WesternEurope_Start <= country) &&
1015 (country <= Country_WesternEurope_End);
1016}
1017
1018// ----------------------------------------------------------------------------
1019// DST calculations: we use 3 different rules for the West European countries,
1020// USA and for the rest of the world. This is undoubtedly false for many
1021// countries, but I lack the necessary info (and the time to gather it),
1022// please add the other rules here!
1023// ----------------------------------------------------------------------------
1024
1025/* static */
1026bool wxDateTime::IsDSTApplicable(int year, Country country)
1027{
1028 if ( year == Inv_Year )
1029 {
1030 // take the current year if none given
1031 year = GetCurrentYear();
1032 }
1033
1034 if ( country == Country_Default )
1035 {
1036 country = GetCountry();
1037 }
1038
1039 switch ( country )
1040 {
1041 case USA:
1042 case UK:
1043 // DST was first observed in the US and UK during WWI, reused
1044 // during WWII and used again since 1966
1045 return year >= 1966 ||
1046 (year >= 1942 && year <= 1945) ||
1047 (year == 1918 || year == 1919);
1048
1049 default:
1050 // assume that it started after WWII
1051 return year > 1950;
1052 }
1053}
1054
1055/* static */
1056wxDateTime wxDateTime::GetBeginDST(int year, Country country)
1057{
1058 if ( year == Inv_Year )
1059 {
1060 // take the current year if none given
1061 year = GetCurrentYear();
1062 }
1063
1064 if ( country == Country_Default )
1065 {
1066 country = GetCountry();
1067 }
1068
1069 if ( !IsDSTApplicable(year, country) )
1070 {
2ef31e80 1071 return wxInvalidDateTime;
239446b4
VZ
1072 }
1073
1074 wxDateTime dt;
1075
1076 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1077 {
1078 // DST begins at 1 a.m. GMT on the last Sunday of March
1079 if ( !dt.SetToLastWeekDay(Sun, Mar, year) )
1080 {
1081 // weird...
1082 wxFAIL_MSG( _T("no last Sunday in March?") );
1083 }
1084
1085 dt += wxTimeSpan::Hours(1);
239446b4
VZ
1086 }
1087 else switch ( country )
1088 {
1089 case USA:
1090 switch ( year )
1091 {
1092 case 1918:
1093 case 1919:
1094 // don't know for sure - assume it was in effect all year
1095
1096 case 1943:
1097 case 1944:
1098 case 1945:
1099 dt.Set(1, Jan, year);
1100 break;
1101
1102 case 1942:
1103 // DST was installed Feb 2, 1942 by the Congress
1104 dt.Set(2, Feb, year);
1105 break;
1106
1107 // Oil embargo changed the DST period in the US
1108 case 1974:
1109 dt.Set(6, Jan, 1974);
1110 break;
1111
1112 case 1975:
1113 dt.Set(23, Feb, 1975);
1114 break;
1115
1116 default:
1117 // before 1986, DST begun on the last Sunday of April, but
1118 // in 1986 Reagan changed it to begin at 2 a.m. of the
1119 // first Sunday in April
1120 if ( year < 1986 )
1121 {
1122 if ( !dt.SetToLastWeekDay(Sun, Apr, year) )
1123 {
1124 // weird...
1125 wxFAIL_MSG( _T("no first Sunday in April?") );
1126 }
1127 }
6b522db5
VZ
1128 else if ( year > 2006 )
1129 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1130 // Starting in 2007, daylight time begins in the United States on the
1131 // second Sunday in March and ends on the first Sunday in November
1132 {
1133 if ( !dt.SetToWeekDay(Sun, 2, Mar, year) )
1134 {
1135 // weird...
1136 wxFAIL_MSG( _T("no second Sunday in March?") );
1137 }
1138 }
239446b4
VZ
1139 else
1140 {
1141 if ( !dt.SetToWeekDay(Sun, 1, Apr, year) )
1142 {
1143 // weird...
1144 wxFAIL_MSG( _T("no first Sunday in April?") );
1145 }
1146 }
1147
1148 dt += wxTimeSpan::Hours(2);
1149
1150 // TODO what about timezone??
1151 }
1152
1153 break;
1154
1155 default:
1156 // assume Mar 30 as the start of the DST for the rest of the world
1157 // - totally bogus, of course
1158 dt.Set(30, Mar, year);
1159 }
1160
1161 return dt;
1162}
1163
1164/* static */
1165wxDateTime wxDateTime::GetEndDST(int year, Country country)
1166{
1167 if ( year == Inv_Year )
1168 {
1169 // take the current year if none given
1170 year = GetCurrentYear();
1171 }
1172
1173 if ( country == Country_Default )
1174 {
1175 country = GetCountry();
1176 }
1177
1178 if ( !IsDSTApplicable(year, country) )
1179 {
2ef31e80 1180 return wxInvalidDateTime;
239446b4
VZ
1181 }
1182
1183 wxDateTime dt;
1184
1185 if ( IsWestEuropeanCountry(country) || (country == Russia) )
1186 {
5f287370 1187 // DST ends at 1 a.m. GMT on the last Sunday of October
239446b4
VZ
1188 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1189 {
1190 // weirder and weirder...
1191 wxFAIL_MSG( _T("no last Sunday in October?") );
1192 }
1193
1194 dt += wxTimeSpan::Hours(1);
239446b4
VZ
1195 }
1196 else switch ( country )
1197 {
1198 case USA:
1199 switch ( year )
1200 {
1201 case 1918:
1202 case 1919:
1203 // don't know for sure - assume it was in effect all year
1204
1205 case 1943:
1206 case 1944:
1207 dt.Set(31, Dec, year);
1208 break;
1209
1210 case 1945:
1211 // the time was reset after the end of the WWII
1212 dt.Set(30, Sep, year);
1213 break;
1214
6b522db5
VZ
1215 default: // default for switch (year)
1216 if ( year > 2006 )
1217 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1218 // Starting in 2007, daylight time begins in the United States on the
1219 // second Sunday in March and ends on the first Sunday in November
1220 {
1221 if ( !dt.SetToWeekDay(Sun, 1, Nov, year) )
1222 {
1223 // weird...
1224 wxFAIL_MSG( _T("no first Sunday in November?") );
1225 }
1226 }
1227 else
1228 // pre-2007
1229 // DST ends at 2 a.m. on the last Sunday of October
239446b4 1230 {
6b522db5
VZ
1231 if ( !dt.SetToLastWeekDay(Sun, Oct, year) )
1232 {
1233 // weirder and weirder...
1234 wxFAIL_MSG( _T("no last Sunday in October?") );
1235 }
239446b4
VZ
1236 }
1237
1238 dt += wxTimeSpan::Hours(2);
1239
6b522db5 1240 // TODO: what about timezone??
239446b4
VZ
1241 }
1242 break;
1243
6b522db5 1244 default: // default for switch (country)
239446b4
VZ
1245 // assume October 26th as the end of the DST - totally bogus too
1246 dt.Set(26, Oct, year);
1247 }
1248
1249 return dt;
1250}
1251
0979c962
VZ
1252// ----------------------------------------------------------------------------
1253// constructors and assignment operators
1254// ----------------------------------------------------------------------------
1255
f6bcfd97
BP
1256// return the current time with ms precision
1257/* static */ wxDateTime wxDateTime::UNow()
1258{
1259 return wxDateTime(wxGetLocalTimeMillis());
1260}
1261
299fcbfe
VZ
1262// the values in the tm structure contain the local time
1263wxDateTime& wxDateTime::Set(const struct tm& tm)
0979c962 1264{
299fcbfe 1265 struct tm tm2(tm);
b76b015e 1266 time_t timet = mktime(&tm2);
1ef54dcf 1267
4afd7529 1268 if ( timet == (time_t)-1 )
0979c962 1269 {
4afd7529
VZ
1270 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1271 // less than timezone - try to make it work for this case
1272 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
1273 {
3d78a532
RD
1274 return Set((time_t)(
1275 GetTimeZone() +
1276 tm2.tm_hour * MIN_PER_HOUR * SEC_PER_MIN +
1277 tm2.tm_min * SEC_PER_MIN +
1278 tm2.tm_sec));
4afd7529
VZ
1279 }
1280
1281 wxFAIL_MSG( _T("mktime() failed") );
0979c962 1282
384223b3
VZ
1283 *this = wxInvalidDateTime;
1284
1285 return *this;
0979c962
VZ
1286 }
1287 else
1288 {
1289 return Set(timet);
1290 }
1291}
1292
1293wxDateTime& wxDateTime::Set(wxDateTime_t hour,
1294 wxDateTime_t minute,
1295 wxDateTime_t second,
1296 wxDateTime_t millisec)
1297{
1298 // we allow seconds to be 61 to account for the leap seconds, even if we
1299 // don't use them really
384223b3
VZ
1300 wxDATETIME_CHECK( hour < 24 &&
1301 second < 62 &&
1302 minute < 60 &&
1303 millisec < 1000,
1304 _T("Invalid time in wxDateTime::Set()") );
0979c962
VZ
1305
1306 // get the current date from system
a452689b
SN
1307 struct tm tmstruct;
1308 struct tm *tm = GetTmNow(&tmstruct);
299fcbfe 1309
a452689b 1310 wxDATETIME_CHECK( tm, _T("wxLocaltime_r() failed") );
0979c962 1311
456639ac
VZ
1312 // make a copy so it isn't clobbered by the call to mktime() below
1313 struct tm tm1(*tm);
1314
0979c962 1315 // adjust the time
456639ac
VZ
1316 tm1.tm_hour = hour;
1317 tm1.tm_min = minute;
1318 tm1.tm_sec = second;
0979c962 1319
9cc311d3 1320 // and the DST in case it changes on this date
456639ac 1321 struct tm tm2(tm1);
9cc311d3 1322 mktime(&tm2);
456639ac
VZ
1323 if ( tm2.tm_isdst != tm1.tm_isdst )
1324 tm1.tm_isdst = tm2.tm_isdst;
9cc311d3 1325
456639ac 1326 (void)Set(tm1);
0979c962
VZ
1327
1328 // and finally adjust milliseconds
1329 return SetMillisecond(millisec);
1330}
1331
1332wxDateTime& wxDateTime::Set(wxDateTime_t day,
1333 Month month,
1334 int year,
1335 wxDateTime_t hour,
1336 wxDateTime_t minute,
1337 wxDateTime_t second,
1338 wxDateTime_t millisec)
1339{
384223b3
VZ
1340 wxDATETIME_CHECK( hour < 24 &&
1341 second < 62 &&
1342 minute < 60 &&
1343 millisec < 1000,
1344 _T("Invalid time in wxDateTime::Set()") );
0979c962 1345
2f02cb89 1346 ReplaceDefaultYearMonthWithCurrent(&year, &month);
0979c962 1347
384223b3
VZ
1348 wxDATETIME_CHECK( (0 < day) && (day <= GetNumberOfDays(month, year)),
1349 _T("Invalid date in wxDateTime::Set()") );
0979c962
VZ
1350
1351 // the range of time_t type (inclusive)
1352 static const int yearMinInRange = 1970;
1353 static const int yearMaxInRange = 2037;
1354
1355 // test only the year instead of testing for the exact end of the Unix
1356 // time_t range - it doesn't bring anything to do more precise checks
2f02cb89 1357 if ( year >= yearMinInRange && year <= yearMaxInRange )
0979c962
VZ
1358 {
1359 // use the standard library version if the date is in range - this is
b76b015e 1360 // probably more efficient than our code
0979c962 1361 struct tm tm;
b76b015e 1362 tm.tm_year = year - 1900;
0979c962
VZ
1363 tm.tm_mon = month;
1364 tm.tm_mday = day;
1365 tm.tm_hour = hour;
1366 tm.tm_min = minute;
1367 tm.tm_sec = second;
299fcbfe 1368 tm.tm_isdst = -1; // mktime() will guess it
0979c962
VZ
1369
1370 (void)Set(tm);
1371
1372 // and finally adjust milliseconds
3d78a532
RD
1373 if (IsValid())
1374 SetMillisecond(millisec);
1375
1376 return *this;
0979c962
VZ
1377 }
1378 else
1379 {
1380 // do time calculations ourselves: we want to calculate the number of
fcc3d7cb 1381 // milliseconds between the given date and the epoch
e6ec579c
VZ
1382
1383 // get the JDN for the midnight of this day
1384 m_time = GetTruncatedJDN(day, month, year);
1385 m_time -= EPOCH_JDN;
1386 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
1387
299fcbfe
VZ
1388 // JDN corresponds to GMT, we take localtime
1389 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
b76b015e
VZ
1390 }
1391
1392 return *this;
1393}
1394
e6ec579c
VZ
1395wxDateTime& wxDateTime::Set(double jdn)
1396{
1ef54dcf
VZ
1397 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1398 // EPOCH_JDN + 0.5
1399 jdn -= EPOCH_JDN + 0.5;
1400
d26adb9d 1401 m_time.Assign(jdn*MILLISECONDS_PER_DAY);
cd0b1709 1402
d26adb9d 1403 // JDNs always are in UTC, so we don't need any adjustments for time zone
e6ec579c
VZ
1404
1405 return *this;
1406}
1407
9d9b7755
VZ
1408wxDateTime& wxDateTime::ResetTime()
1409{
1410 Tm tm = GetTm();
1411
1412 if ( tm.hour || tm.min || tm.sec || tm.msec )
1413 {
1414 tm.msec =
1415 tm.sec =
1416 tm.min =
1417 tm.hour = 0;
1418
1419 Set(tm);
1420 }
1421
1422 return *this;
1423}
1424
fb96cf85
VZ
1425wxDateTime wxDateTime::GetDateOnly() const
1426{
1427 Tm tm = GetTm();
1428 tm.msec =
1429 tm.sec =
1430 tm.min =
1431 tm.hour = 0;
1432 return wxDateTime(tm);
1433}
1434
2b5f62a0
VZ
1435// ----------------------------------------------------------------------------
1436// DOS Date and Time Format functions
1437// ----------------------------------------------------------------------------
1438// the dos date and time value is an unsigned 32 bit value in the format:
1439// YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1440//
1441// Y = year offset from 1980 (0-127)
1442// M = month (1-12)
1443// D = day of month (1-31)
1444// h = hour (0-23)
1445// m = minute (0-59)
1446// s = bisecond (0-29) each bisecond indicates two seconds
1447// ----------------------------------------------------------------------------
1448
1449wxDateTime& wxDateTime::SetFromDOS(unsigned long ddt)
1450{
1451 struct tm tm;
4739346e 1452 InitTm(tm);
2b5f62a0
VZ
1453
1454 long year = ddt & 0xFE000000;
1455 year >>= 25;
1456 year += 80;
1457 tm.tm_year = year;
1458
1459 long month = ddt & 0x1E00000;
1460 month >>= 21;
1461 month -= 1;
1462 tm.tm_mon = month;
1463
1464 long day = ddt & 0x1F0000;
1465 day >>= 16;
1466 tm.tm_mday = day;
1467
1468 long hour = ddt & 0xF800;
1469 hour >>= 11;
1470 tm.tm_hour = hour;
1471
1472 long minute = ddt & 0x7E0;
1473 minute >>= 5;
1474 tm.tm_min = minute;
1475
1476 long second = ddt & 0x1F;
1477 tm.tm_sec = second * 2;
1478
1479 return Set(mktime(&tm));
1480}
1481
1482unsigned long wxDateTime::GetAsDOS() const
1483{
1484 unsigned long ddt;
1485 time_t ticks = GetTicks();
a452689b
SN
1486 struct tm tmstruct;
1487 struct tm *tm = wxLocaltime_r(&ticks, &tmstruct);
1faa4ad2 1488 wxCHECK_MSG( tm, ULONG_MAX, _T("time can't be represented in DOS format") );
2b5f62a0
VZ
1489
1490 long year = tm->tm_year;
1491 year -= 80;
1492 year <<= 25;
1493
1494 long month = tm->tm_mon;
1495 month += 1;
1496 month <<= 21;
1497
1498 long day = tm->tm_mday;
1499 day <<= 16;
1500
1501 long hour = tm->tm_hour;
1502 hour <<= 11;
1503
1504 long minute = tm->tm_min;
1505 minute <<= 5;
1506
1507 long second = tm->tm_sec;
1508 second /= 2;
1509
1510 ddt = year | month | day | hour | minute | second;
1511 return ddt;
1512}
1513
b76b015e
VZ
1514// ----------------------------------------------------------------------------
1515// time_t <-> broken down time conversions
1516// ----------------------------------------------------------------------------
1517
299fcbfe 1518wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
b76b015e
VZ
1519{
1520 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1521
1522 time_t time = GetTicks();
1523 if ( time != (time_t)-1 )
1524 {
1525 // use C RTL functions
a452689b 1526 struct tm tmstruct;
299fcbfe
VZ
1527 tm *tm;
1528 if ( tz.GetOffset() == -GetTimeZone() )
1529 {
1530 // we are working with local time
a452689b 1531 tm = wxLocaltime_r(&time, &tmstruct);
c5a1681b
VZ
1532
1533 // should never happen
a452689b 1534 wxCHECK_MSG( tm, Tm(), _T("wxLocaltime_r() failed") );
299fcbfe
VZ
1535 }
1536 else
1537 {
13111b2a 1538 time += (time_t)tz.GetOffset();
33ac7e6f 1539#if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
13111b2a 1540 int time2 = (int) time;
9d9b7755 1541 if ( time2 >= 0 )
fb10f04c 1542#else
9d9b7755 1543 if ( time >= 0 )
fb10f04c 1544#endif
c5a1681b 1545 {
a452689b 1546 tm = wxGmtime_r(&time, &tmstruct);
b76b015e 1547
c5a1681b 1548 // should never happen
a452689b 1549 wxCHECK_MSG( tm, Tm(), _T("wxGmtime_r() failed") );
c5a1681b
VZ
1550 }
1551 else
1552 {
1553 tm = (struct tm *)NULL;
1554 }
1555 }
b76b015e 1556
c5a1681b
VZ
1557 if ( tm )
1558 {
f6bcfd97
BP
1559 // adjust the milliseconds
1560 Tm tm2(*tm, tz);
1561 long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong();
1562 tm2.msec = (wxDateTime_t)(timeOnly % 1000);
1563 return tm2;
c5a1681b
VZ
1564 }
1565 //else: use generic code below
b76b015e 1566 }
e6ec579c 1567
c5a1681b
VZ
1568 // remember the time and do the calculations with the date only - this
1569 // eliminates rounding errors of the floating point arithmetics
299fcbfe 1570
c5a1681b 1571 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
1ef54dcf 1572
c5a1681b 1573 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1ef54dcf 1574
c5a1681b
VZ
1575 // we want to always have positive time and timeMidnight to be really
1576 // the midnight before it
1577 if ( timeOnly < 0 )
1578 {
1579 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1580 }
e6ec579c 1581
c5a1681b 1582 timeMidnight -= timeOnly;
1ef54dcf 1583
c5a1681b
VZ
1584 // calculate the Gregorian date from JDN for the midnight of our date:
1585 // this will yield day, month (in 1..12 range) and year
1ef54dcf 1586
c5a1681b
VZ
1587 // actually, this is the JDN for the noon of the previous day
1588 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
1ef54dcf 1589
c5a1681b 1590 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1ef54dcf 1591
c5a1681b 1592 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
1ef54dcf 1593
c5a1681b 1594 // calculate the century
479cd5de
VZ
1595 long temp = (jdn + JDN_OFFSET) * 4 - 1;
1596 long century = temp / DAYS_PER_400_YEARS;
1ef54dcf 1597
c5a1681b
VZ
1598 // then the year and day of year (1 <= dayOfYear <= 366)
1599 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
479cd5de
VZ
1600 long year = (century * 100) + (temp / DAYS_PER_4_YEARS);
1601 long dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
1ef54dcf 1602
c5a1681b
VZ
1603 // and finally the month and day of the month
1604 temp = dayOfYear * 5 - 3;
479cd5de
VZ
1605 long month = temp / DAYS_PER_5_MONTHS;
1606 long day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
c5a1681b
VZ
1607
1608 // month is counted from March - convert to normal
1609 if ( month < 10 )
1610 {
1611 month += 3;
1612 }
1613 else
1614 {
1615 year += 1;
1616 month -= 9;
1617 }
1ef54dcf 1618
c5a1681b
VZ
1619 // year is offset by 4800
1620 year -= 4800;
1ef54dcf 1621
c5a1681b
VZ
1622 // check that the algorithm gave us something reasonable
1623 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
1624 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
e6ec579c 1625
c5a1681b
VZ
1626 // construct Tm from these values
1627 Tm tm;
1628 tm.year = (int)year;
1629 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1630 tm.mday = (wxDateTime_t)day;
479cd5de 1631 tm.msec = (wxDateTime_t)(timeOnly % 1000);
c5a1681b
VZ
1632 timeOnly -= tm.msec;
1633 timeOnly /= 1000; // now we have time in seconds
e6ec579c 1634
d26adb9d 1635 tm.sec = (wxDateTime_t)(timeOnly % SEC_PER_MIN);
c5a1681b 1636 timeOnly -= tm.sec;
d26adb9d 1637 timeOnly /= SEC_PER_MIN; // now we have time in minutes
e6ec579c 1638
d26adb9d 1639 tm.min = (wxDateTime_t)(timeOnly % MIN_PER_HOUR);
c5a1681b 1640 timeOnly -= tm.min;
e6ec579c 1641
d26adb9d 1642 tm.hour = (wxDateTime_t)(timeOnly / MIN_PER_HOUR);
b76b015e 1643
c5a1681b 1644 return tm;
b76b015e
VZ
1645}
1646
1647wxDateTime& wxDateTime::SetYear(int year)
1648{
1649 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1650
1651 Tm tm(GetTm());
1652 tm.year = year;
1653 Set(tm);
1654
1655 return *this;
1656}
1657
1658wxDateTime& wxDateTime::SetMonth(Month month)
1659{
1660 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1661
1662 Tm tm(GetTm());
1663 tm.mon = month;
1664 Set(tm);
1665
1666 return *this;
1667}
1668
1669wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
1670{
1671 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1672
1673 Tm tm(GetTm());
1674 tm.mday = mday;
1675 Set(tm);
1676
1677 return *this;
1678}
1679
1680wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
1681{
1682 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1683
1684 Tm tm(GetTm());
1685 tm.hour = hour;
1686 Set(tm);
1687
1688 return *this;
1689}
1690
1691wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
1692{
1693 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1694
1695 Tm tm(GetTm());
1696 tm.min = min;
1697 Set(tm);
1698
1699 return *this;
1700}
1701
1702wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
1703{
1704 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1705
1706 Tm tm(GetTm());
1707 tm.sec = sec;
1708 Set(tm);
0979c962
VZ
1709
1710 return *this;
1711}
b76b015e
VZ
1712
1713wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
1714{
1715 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1716
1717 // we don't need to use GetTm() for this one
1718 m_time -= m_time % 1000l;
1719 m_time += millisecond;
1720
1721 return *this;
1722}
1723
1724// ----------------------------------------------------------------------------
1725// wxDateTime arithmetics
1726// ----------------------------------------------------------------------------
1727
1728wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
1729{
1730 Tm tm(GetTm());
1731
1732 tm.year += diff.GetYears();
fcc3d7cb 1733 tm.AddMonths(diff.GetMonths());
4f6aed9c
VZ
1734
1735 // check that the resulting date is valid
1736 if ( tm.mday > GetNumOfDaysInMonth(tm.year, tm.mon) )
1737 {
1738 // We suppose that when adding one month to Jan 31 we want to get Feb
1739 // 28 (or 29), i.e. adding a month to the last day of the month should
1740 // give the last day of the next month which is quite logical.
1741 //
1742 // Unfortunately, there is no logic way to understand what should
1743 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1744 // We make it Feb 28 (last day too), but it is highly questionable.
1745 tm.mday = GetNumOfDaysInMonth(tm.year, tm.mon);
1746 }
1747
fcc3d7cb 1748 tm.AddDays(diff.GetTotalDays());
b76b015e
VZ
1749
1750 Set(tm);
1751
9d9b7755
VZ
1752 wxASSERT_MSG( IsSameTime(tm),
1753 _T("Add(wxDateSpan) shouldn't modify time") );
1754
b76b015e
VZ
1755 return *this;
1756}
1757
2f02cb89
VZ
1758// ----------------------------------------------------------------------------
1759// Weekday and monthday stuff
1760// ----------------------------------------------------------------------------
1761
4c27e2fa
VZ
1762// convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1763static inline int ConvertWeekDayToMondayBase(int wd)
1764{
1765 return wd == wxDateTime::Sun ? 6 : wd - 1;
1766}
1767
1768/* static */
1769wxDateTime
1770wxDateTime::SetToWeekOfYear(int year, wxDateTime_t numWeek, WeekDay wd)
4f6aed9c 1771{
2b5f62a0
VZ
1772 wxASSERT_MSG( numWeek > 0,
1773 _T("invalid week number: weeks are counted from 1") );
1774
4c27e2fa
VZ
1775 // Jan 4 always lies in the 1st week of the year
1776 wxDateTime dt(4, Jan, year);
1777 dt.SetToWeekDayInSameWeek(wd);
1778 dt += wxDateSpan::Weeks(numWeek - 1);
1779
1780 return dt;
1781}
4f6aed9c 1782
ca3e85cf 1783#if WXWIN_COMPATIBILITY_2_6
4c27e2fa
VZ
1784// use a separate function to avoid warnings about using deprecated
1785// SetToTheWeek in GetWeek below
1786static wxDateTime
1787SetToTheWeek(int year,
1788 wxDateTime::wxDateTime_t numWeek,
1789 wxDateTime::WeekDay weekday,
1790 wxDateTime::WeekFlags flags)
1791{
4f6aed9c 1792 // Jan 4 always lies in the 1st week of the year
4c27e2fa
VZ
1793 wxDateTime dt(4, wxDateTime::Jan, year);
1794 dt.SetToWeekDayInSameWeek(weekday, flags);
1795 dt += wxDateSpan::Weeks(numWeek - 1);
4f6aed9c 1796
4c27e2fa
VZ
1797 return dt;
1798}
1799
1800bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek,
1801 WeekDay weekday,
1802 WeekFlags flags)
1803{
1804 int year = GetYear();
1805 *this = ::SetToTheWeek(year, numWeek, weekday, flags);
4f6aed9c
VZ
1806 if ( GetYear() != year )
1807 {
1808 // oops... numWeek was too big
68379eaf 1809 return false;
4f6aed9c
VZ
1810 }
1811
68379eaf 1812 return true;
4f6aed9c
VZ
1813}
1814
4c27e2fa
VZ
1815wxDateTime wxDateTime::GetWeek(wxDateTime_t numWeek,
1816 WeekDay weekday,
1817 WeekFlags flags) const
1818{
1819 return ::SetToTheWeek(GetYear(), numWeek, weekday, flags);
1820}
ca3e85cf 1821#endif // WXWIN_COMPATIBILITY_2_6
4c27e2fa 1822
2f02cb89
VZ
1823wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
1824 int year)
1825{
1826 // take the current month/year if none specified
1a8557b1
VZ
1827 if ( year == Inv_Year )
1828 year = GetYear();
1829 if ( month == Inv_Month )
1830 month = GetMonth();
2f02cb89 1831
fcc3d7cb 1832 return Set(GetNumOfDaysInMonth(year, month), month, year);
2f02cb89
VZ
1833}
1834
2b5f62a0 1835wxDateTime& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday, WeekFlags flags)
cd0b1709 1836{
384223b3 1837 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
cd0b1709 1838
af80bc92
VZ
1839 int wdayDst = weekday,
1840 wdayThis = GetWeekDay();
1841 if ( wdayDst == wdayThis )
cd0b1709
VZ
1842 {
1843 // nothing to do
1844 return *this;
1845 }
2b5f62a0
VZ
1846
1847 if ( flags == Default_First )
1848 {
1849 flags = GetCountry() == USA ? Sunday_First : Monday_First;
1850 }
1851
1852 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1853 // is the first day in the week, but breaks down for Monday_First case so
1854 // we adjust the week days in this case
af80bc92 1855 if ( flags == Monday_First )
2b5f62a0
VZ
1856 {
1857 if ( wdayThis == Sun )
1858 wdayThis += 7;
af80bc92
VZ
1859 if ( wdayDst == Sun )
1860 wdayDst += 7;
2b5f62a0
VZ
1861 }
1862 //else: Sunday_First, nothing to do
1863
1864 // go forward or back in time to the day we want
af80bc92 1865 if ( wdayDst < wdayThis )
cd0b1709 1866 {
af80bc92 1867 return Subtract(wxDateSpan::Days(wdayThis - wdayDst));
cd0b1709
VZ
1868 }
1869 else // weekday > wdayThis
1870 {
af80bc92 1871 return Add(wxDateSpan::Days(wdayDst - wdayThis));
cd0b1709
VZ
1872 }
1873}
1874
1875wxDateTime& wxDateTime::SetToNextWeekDay(WeekDay weekday)
1876{
384223b3 1877 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
cd0b1709
VZ
1878
1879 int diff;
1880 WeekDay wdayThis = GetWeekDay();
1881 if ( weekday == wdayThis )
1882 {
1883 // nothing to do
1884 return *this;
1885 }
1886 else if ( weekday < wdayThis )
1887 {
1888 // need to advance a week
1889 diff = 7 - (wdayThis - weekday);
1890 }
1891 else // weekday > wdayThis
1892 {
1893 diff = weekday - wdayThis;
1894 }
1895
4f6aed9c 1896 return Add(wxDateSpan::Days(diff));
cd0b1709
VZ
1897}
1898
1899wxDateTime& wxDateTime::SetToPrevWeekDay(WeekDay weekday)
1900{
384223b3 1901 wxDATETIME_CHECK( weekday != Inv_WeekDay, _T("invalid weekday") );
cd0b1709
VZ
1902
1903 int diff;
1904 WeekDay wdayThis = GetWeekDay();
1905 if ( weekday == wdayThis )
1906 {
1907 // nothing to do
1908 return *this;
1909 }
1910 else if ( weekday > wdayThis )
1911 {
1912 // need to go to previous week
1913 diff = 7 - (weekday - wdayThis);
1914 }
1915 else // weekday < wdayThis
1916 {
1917 diff = wdayThis - weekday;
1918 }
1919
f6bcfd97 1920 return Subtract(wxDateSpan::Days(diff));
cd0b1709
VZ
1921}
1922
2f02cb89
VZ
1923bool wxDateTime::SetToWeekDay(WeekDay weekday,
1924 int n,
1925 Month month,
1926 int year)
1927{
68379eaf 1928 wxCHECK_MSG( weekday != Inv_WeekDay, false, _T("invalid weekday") );
2f02cb89 1929
68379eaf 1930 // we don't check explicitly that -5 <= n <= 5 because we will return false
2f02cb89
VZ
1931 // anyhow in such case - but may be should still give an assert for it?
1932
1933 // take the current month/year if none specified
1934 ReplaceDefaultYearMonthWithCurrent(&year, &month);
1935
1936 wxDateTime dt;
1937
1938 // TODO this probably could be optimised somehow...
1939
1940 if ( n > 0 )
1941 {
1942 // get the first day of the month
1943 dt.Set(1, month, year);
1944
1945 // get its wday
1946 WeekDay wdayFirst = dt.GetWeekDay();
1947
1948 // go to the first weekday of the month
1949 int diff = weekday - wdayFirst;
1950 if ( diff < 0 )
1951 diff += 7;
1952
1953 // add advance n-1 weeks more
1954 diff += 7*(n - 1);
1955
239446b4 1956 dt += wxDateSpan::Days(diff);
2f02cb89 1957 }
239446b4 1958 else // count from the end of the month
2f02cb89
VZ
1959 {
1960 // get the last day of the month
1961 dt.SetToLastMonthDay(month, year);
1962
1963 // get its wday
1964 WeekDay wdayLast = dt.GetWeekDay();
1965
1966 // go to the last weekday of the month
1967 int diff = wdayLast - weekday;
1968 if ( diff < 0 )
1969 diff += 7;
1970
1971 // and rewind n-1 weeks from there
239446b4 1972 diff += 7*(-n - 1);
2f02cb89
VZ
1973
1974 dt -= wxDateSpan::Days(diff);
1975 }
1976
1977 // check that it is still in the same month
1978 if ( dt.GetMonth() == month )
1979 {
1980 *this = dt;
1981
68379eaf 1982 return true;
2f02cb89
VZ
1983 }
1984 else
1985 {
1986 // no such day in this month
68379eaf 1987 return false;
2f02cb89
VZ
1988 }
1989}
1990
1c5d27e2
VZ
1991static inline
1992wxDateTime::wxDateTime_t GetDayOfYearFromTm(const wxDateTime::Tm& tm)
1993{
907173e5 1994 return (wxDateTime::wxDateTime_t)(gs_cumulatedDays[wxDateTime::IsLeapYear(tm.year)][tm.mon] + tm.mday);
1c5d27e2
VZ
1995}
1996
239446b4
VZ
1997wxDateTime::wxDateTime_t wxDateTime::GetDayOfYear(const TimeZone& tz) const
1998{
1c5d27e2
VZ
1999 return GetDayOfYearFromTm(GetTm(tz));
2000}
239446b4 2001
1c5d27e2
VZ
2002wxDateTime::wxDateTime_t
2003wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags, const TimeZone& tz) const
239446b4 2004{
9d9b7755
VZ
2005 if ( flags == Default_First )
2006 {
2007 flags = GetCountry() == USA ? Sunday_First : Monday_First;
2008 }
239446b4 2009
1c5d27e2
VZ
2010 Tm tm(GetTm(tz));
2011 wxDateTime_t nDayInYear = GetDayOfYearFromTm(tm);
239446b4 2012
1c5d27e2
VZ
2013 int wdTarget = GetWeekDay(tz);
2014 int wdYearStart = wxDateTime(1, Jan, GetYear()).GetWeekDay();
2015 int week;
9d9b7755
VZ
2016 if ( flags == Sunday_First )
2017 {
1c5d27e2
VZ
2018 // FIXME: First week is not calculated correctly.
2019 week = (nDayInYear - wdTarget + 7) / 7;
2020 if ( wdYearStart == Wed || wdYearStart == Thu )
2021 week++;
9d9b7755 2022 }
1c5d27e2 2023 else // week starts with monday
9d9b7755 2024 {
1c5d27e2
VZ
2025 // adjust the weekdays to non-US style.
2026 wdYearStart = ConvertWeekDayToMondayBase(wdYearStart);
2027 wdTarget = ConvertWeekDayToMondayBase(wdTarget);
239446b4 2028
1c5d27e2
VZ
2029 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2030 //
2031 // Week 01 of a year is per definition the first week that has the
2032 // Thursday in this year, which is equivalent to the week that
2033 // contains the fourth day of January. In other words, the first
2034 // week of a new year is the week that has the majority of its
2035 // days in the new year. Week 01 might also contain days from the
2036 // previous year and the week before week 01 of a year is the last
2037 // week (52 or 53) of the previous year even if it contains days
2038 // from the new year. A week starts with Monday (day 1) and ends
2039 // with Sunday (day 7).
2040 //
2041
2042 // if Jan 1 is Thursday or less, it is in the first week of this year
2043 if ( wdYearStart < 4 )
2044 {
2045 // count the number of entire weeks between Jan 1 and this date
2046 week = (nDayInYear + wdYearStart + 6 - wdTarget)/7;
2047
2048 // be careful to check for overflow in the next year
2049 if ( week == 53 && tm.mday - wdTarget > 28 )
2050 week = 1;
2051 }
2052 else // Jan 1 is in the last week of the previous year
2053 {
2054 // check if we happen to be at the last week of previous year:
2055 if ( tm.mon == Jan && tm.mday < 8 - wdYearStart )
2056 week = wxDateTime(31, Dec, GetYear()-1).GetWeekOfYear();
2057 else
2058 week = (nDayInYear + wdYearStart - 1 - wdTarget)/7;
2059 }
239446b4
VZ
2060 }
2061
907173e5 2062 return (wxDateTime::wxDateTime_t)week;
68ee7c47
VZ
2063}
2064
9d9b7755
VZ
2065wxDateTime::wxDateTime_t wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags,
2066 const TimeZone& tz) const
68ee7c47 2067{
9d9b7755
VZ
2068 Tm tm = GetTm(tz);
2069 wxDateTime dtMonthStart = wxDateTime(1, tm.mon, tm.year);
6dc6fda6 2070 int nWeek = GetWeekOfYear(flags) - dtMonthStart.GetWeekOfYear(flags) + 1;
9d9b7755 2071 if ( nWeek < 0 )
68ee7c47 2072 {
9d9b7755
VZ
2073 // this may happen for January when Jan, 1 is the last week of the
2074 // previous year
2075 nWeek += IsLeapYear(tm.year - 1) ? 53 : 52;
68ee7c47 2076 }
68ee7c47 2077
6dc6fda6 2078 return (wxDateTime::wxDateTime_t)nWeek;
239446b4
VZ
2079}
2080
f0f951fa
VZ
2081wxDateTime& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday)
2082{
2083 int year = GetYear();
384223b3
VZ
2084 wxDATETIME_CHECK( (0 < yday) && (yday <= GetNumberOfDays(year)),
2085 _T("invalid year day") );
f0f951fa
VZ
2086
2087 bool isLeap = IsLeapYear(year);
2088 for ( Month mon = Jan; mon < Inv_Month; wxNextMonth(mon) )
2089 {
2090 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2091 // don't need it neither - because of the CHECK above we know that
2092 // yday lies in December then
f49d731f 2093 if ( (mon == Dec) || (yday <= gs_cumulatedDays[isLeap][mon + 1]) )
f0f951fa 2094 {
42841dfc 2095 Set((wxDateTime::wxDateTime_t)(yday - gs_cumulatedDays[isLeap][mon]), mon, year);
f0f951fa
VZ
2096
2097 break;
2098 }
2099 }
2100
2101 return *this;
2102}
2103
e6ec579c
VZ
2104// ----------------------------------------------------------------------------
2105// Julian day number conversion and related stuff
2106// ----------------------------------------------------------------------------
2107
2108double wxDateTime::GetJulianDayNumber() const
2109{
d26adb9d 2110 return m_time.ToDouble() / MILLISECONDS_PER_DAY + EPOCH_JDN + 0.5;
e6ec579c
VZ
2111}
2112
2113double wxDateTime::GetRataDie() const
2114{
2115 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2116 return GetJulianDayNumber() - 1721119.5 - 306;
2117}
2118
fcc3d7cb 2119// ----------------------------------------------------------------------------
299fcbfe 2120// timezone and DST stuff
fcc3d7cb
VZ
2121// ----------------------------------------------------------------------------
2122
299fcbfe 2123int wxDateTime::IsDST(wxDateTime::Country country) const
fcc3d7cb 2124{
299fcbfe
VZ
2125 wxCHECK_MSG( country == Country_Default, -1,
2126 _T("country support not implemented") );
2127
2128 // use the C RTL for the dates in the standard range
2129 time_t timet = GetTicks();
2130 if ( timet != (time_t)-1 )
2131 {
a452689b
SN
2132 struct tm tmstruct;
2133 tm *tm = wxLocaltime_r(&timet, &tmstruct);
299fcbfe 2134
a452689b 2135 wxCHECK_MSG( tm, -1, _T("wxLocaltime_r() failed") );
299fcbfe
VZ
2136
2137 return tm->tm_isdst;
2138 }
2139 else
2140 {
239446b4
VZ
2141 int year = GetYear();
2142
2143 if ( !IsDSTApplicable(year, country) )
2144 {
2145 // no DST time in this year in this country
2146 return -1;
2147 }
299fcbfe 2148
239446b4 2149 return IsBetween(GetBeginDST(year, country), GetEndDST(year, country));
299fcbfe 2150 }
fcc3d7cb
VZ
2151}
2152
41acf5c0 2153wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz, bool noDST)
fcc3d7cb 2154{
479cd5de 2155 long secDiff = GetTimeZone() + tz.GetOffset();
fcc3d7cb 2156
41acf5c0
VZ
2157 // we need to know whether DST is or not in effect for this date unless
2158 // the test disabled by the caller
2159 if ( !noDST && (IsDST() == 1) )
299fcbfe
VZ
2160 {
2161 // FIXME we assume that the DST is always shifted by 1 hour
2162 secDiff -= 3600;
2163 }
2164
d26adb9d
VZ
2165 return Add(wxTimeSpan::Seconds(secDiff));
2166}
2167
2168wxDateTime& wxDateTime::MakeFromTimezone(const TimeZone& tz, bool noDST)
2169{
2170 long secDiff = GetTimeZone() + tz.GetOffset();
2171
2172 // we need to know whether DST is or not in effect for this date unless
2173 // the test disabled by the caller
2174 if ( !noDST && (IsDST() == 1) )
2175 {
2176 // FIXME we assume that the DST is always shifted by 1 hour
2177 secDiff -= 3600;
2178 }
2179
f6bcfd97 2180 return Subtract(wxTimeSpan::Seconds(secDiff));
fcc3d7cb
VZ
2181}
2182
4f6aed9c
VZ
2183// ============================================================================
2184// wxDateTimeHolidayAuthority and related classes
2185// ============================================================================
2186
2187#include "wx/arrimpl.cpp"
2188
4115960d 2189WX_DEFINE_OBJARRAY(wxDateTimeArray)
4f6aed9c
VZ
2190
2191static int wxCMPFUNC_CONV
2192wxDateTimeCompareFunc(wxDateTime **first, wxDateTime **second)
2193{
2194 wxDateTime dt1 = **first,
2195 dt2 = **second;
2196
2197 return dt1 == dt2 ? 0 : dt1 < dt2 ? -1 : +1;
2198}
2199
2200// ----------------------------------------------------------------------------
2201// wxDateTimeHolidayAuthority
2202// ----------------------------------------------------------------------------
2203
2204wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority::ms_authorities;
2205
2206/* static */
2207bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime& dt)
2208{
df5168c4 2209 size_t count = ms_authorities.size();
4f6aed9c
VZ
2210 for ( size_t n = 0; n < count; n++ )
2211 {
2212 if ( ms_authorities[n]->DoIsHoliday(dt) )
2213 {
68379eaf 2214 return true;
4f6aed9c
VZ
2215 }
2216 }
2217
68379eaf 2218 return false;
4f6aed9c
VZ
2219}
2220
2221/* static */
2222size_t
2223wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime& dtStart,
2224 const wxDateTime& dtEnd,
2225 wxDateTimeArray& holidays)
2226{
2227 wxDateTimeArray hol;
2228
df5168c4 2229 holidays.Clear();
4f6aed9c 2230
7a7bd38a
VZ
2231 const size_t countAuth = ms_authorities.size();
2232 for ( size_t nAuth = 0; nAuth < countAuth; nAuth++ )
4f6aed9c 2233 {
6dc6fda6 2234 ms_authorities[nAuth]->DoGetHolidaysInRange(dtStart, dtEnd, hol);
4f6aed9c
VZ
2235
2236 WX_APPEND_ARRAY(holidays, hol);
2237 }
2238
2239 holidays.Sort(wxDateTimeCompareFunc);
2240
df5168c4 2241 return holidays.size();
4f6aed9c
VZ
2242}
2243
2244/* static */
2245void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2246{
2247 WX_CLEAR_ARRAY(ms_authorities);
2248}
2249
2250/* static */
2251void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority *auth)
2252{
df5168c4 2253 ms_authorities.push_back(auth);
4f6aed9c
VZ
2254}
2255
5e233068
WS
2256wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2257{
2258 // required here for Darwin
2259}
2260
4f6aed9c
VZ
2261// ----------------------------------------------------------------------------
2262// wxDateTimeWorkDays
2263// ----------------------------------------------------------------------------
2264
2265bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime& dt) const
2266{
2267 wxDateTime::WeekDay wd = dt.GetWeekDay();
2268
2269 return (wd == wxDateTime::Sun) || (wd == wxDateTime::Sat);
2270}
2271
2272size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime& dtStart,
2273 const wxDateTime& dtEnd,
2274 wxDateTimeArray& holidays) const
2275{
2276 if ( dtStart > dtEnd )
2277 {
2278 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
2279
2280 return 0u;
2281 }
2282
2283 holidays.Empty();
2284
2285 // instead of checking all days, start with the first Sat after dtStart and
2286 // end with the last Sun before dtEnd
2287 wxDateTime dtSatFirst = dtStart.GetNextWeekDay(wxDateTime::Sat),
2288 dtSatLast = dtEnd.GetPrevWeekDay(wxDateTime::Sat),
2289 dtSunFirst = dtStart.GetNextWeekDay(wxDateTime::Sun),
2290 dtSunLast = dtEnd.GetPrevWeekDay(wxDateTime::Sun),
2291 dt;
2292
2293 for ( dt = dtSatFirst; dt <= dtSatLast; dt += wxDateSpan::Week() )
2294 {
2295 holidays.Add(dt);
2296 }
2297
2298 for ( dt = dtSunFirst; dt <= dtSunLast; dt += wxDateSpan::Week() )
2299 {
2300 holidays.Add(dt);
2301 }
2302
2303 return holidays.GetCount();
2304}
3e0b743f 2305
26364344
WS
2306// ============================================================================
2307// other helper functions
2308// ============================================================================
2309
2310// ----------------------------------------------------------------------------
2311// iteration helpers: can be used to write a for loop over enum variable like
2312// this:
2313// for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2314// ----------------------------------------------------------------------------
2315
2316WXDLLIMPEXP_BASE void wxNextMonth(wxDateTime::Month& m)
2317{
2318 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2319
2320 // no wrapping or the for loop above would never end!
2321 m = (wxDateTime::Month)(m + 1);
2322}
2323
2324WXDLLIMPEXP_BASE void wxPrevMonth(wxDateTime::Month& m)
2325{
2326 wxASSERT_MSG( m < wxDateTime::Inv_Month, _T("invalid month") );
2327
2328 m = m == wxDateTime::Jan ? wxDateTime::Inv_Month
2329 : (wxDateTime::Month)(m - 1);
2330}
2331
2332WXDLLIMPEXP_BASE void wxNextWDay(wxDateTime::WeekDay& wd)
2333{
2334 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2335
2336 // no wrapping or the for loop above would never end!
2337 wd = (wxDateTime::WeekDay)(wd + 1);
2338}
2339
2340WXDLLIMPEXP_BASE void wxPrevWDay(wxDateTime::WeekDay& wd)
2341{
2342 wxASSERT_MSG( wd < wxDateTime::Inv_WeekDay, _T("invalid week day") );
2343
2344 wd = wd == wxDateTime::Sun ? wxDateTime::Inv_WeekDay
2345 : (wxDateTime::WeekDay)(wd - 1);
2346}
2347
154014d6
VZ
2348#ifdef __WXMSW__
2349
2350wxDateTime& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME& st)
2351{
2352 return Set(st.wDay,
5c33522f 2353 static_cast<wxDateTime::Month>(wxDateTime::Jan + st.wMonth - 1),
154014d6
VZ
2354 st.wYear,
2355 0, 0, 0);
2356}
2357
2358void wxDateTime::GetAsMSWSysTime(SYSTEMTIME* st) const
2359{
2360 const wxDateTime::Tm tm(GetTm());
2361
2362 st->wYear = (WXWORD)tm.year;
2363 st->wMonth = (WXWORD)(tm.mon - wxDateTime::Jan + 1);
2364 st->wDay = tm.mday;
2365
2366 st->wDayOfWeek =
2367 st->wHour =
2368 st->wMinute =
2369 st->wSecond =
2370 st->wMilliseconds = 0;
2371}
2372#endif // __WXMSW__
2373
1e6feb95 2374#endif // wxUSE_DATETIME