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