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