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