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