1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/datetime.cpp
3 // Purpose: implementation of time/date related classes
4 // (for formatting&parsing see datetimefmt.cpp)
5 // Author: Vadim Zeitlin
9 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // parts of code taken from sndcal library by Scott E. Lee:
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.
17 // Licence: wxWindows licence
18 ///////////////////////////////////////////////////////////////////////////////
21 * Implementation notes:
23 * 1. the time is stored as a 64bit integer containing the signed number of
24 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
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
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
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
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
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
48 // ============================================================================
50 // ============================================================================
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // For compilers that support precompilation, includes "wx.h".
57 #include "wx/wxprec.h"
63 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
67 #include "wx/msw/wrapwin.h"
69 #include "wx/string.h"
72 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
73 #include "wx/module.h"
77 #include "wx/thread.h"
78 #include "wx/tokenzr.h"
89 #include "wx/datetime.h"
91 const long wxDateTime
::TIME_T_FACTOR
= 1000l;
93 #if wxUSE_EXTENDED_RTTI
95 template<> void wxStringReadValue(const wxString
&s
, wxDateTime
&data
)
97 data
.ParseFormat(s
,"%Y-%m-%d %H:%M:%S", NULL
);
100 template<> void wxStringWriteValue(wxString
&s
, const wxDateTime
&data
)
102 s
= data
.Format("%Y-%m-%d %H:%M:%S");
105 wxCUSTOM_TYPE_INFO(wxDateTime
, wxToStringConverter
<wxDateTime
> , wxFromStringConverter
<wxDateTime
>)
107 #endif // wxUSE_EXTENDED_RTTI
110 // ----------------------------------------------------------------------------
111 // conditional compilation
112 // ----------------------------------------------------------------------------
114 #if defined(HAVE_STRPTIME) && defined(__GLIBC__) && \
115 ((__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
116 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
117 // crash (instead of just failing):
119 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
120 // strptime(buf, "%x", &tm);
124 #endif // broken strptime()
126 #if defined(HAVE_STRPTIME) && defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
127 // configure detects strptime as linkable because it's in the OS X
128 // System library but MSL headers don't declare it.
130 // char *strptime(const char *, const char *, struct tm *);
131 // However, we DON'T want to just provide it here because we would
132 // crash and/or overwrite data when strptime from OS X tries
133 // to fill in MW's struct tm which is two fields shorter (no TZ stuff)
134 // So for now let's just say we don't have strptime
138 #if defined(__MWERKS__) && wxUSE_UNICODE
142 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
143 #if defined(__WXPALMOS__)
144 #define WX_GMTOFF_IN_TM
145 #elif defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
146 #define WX_TIMEZONE _timezone
147 #elif defined(__MWERKS__)
148 long wxmw_timezone
= 28800;
149 #define WX_TIMEZONE wxmw_timezone
150 #elif defined(__DJGPP__) || defined(__WINE__)
151 #include <sys/timeb.h>
153 static long wxGetTimeZone()
155 static long timezone
= MAXLONG
; // invalid timezone
156 if (timezone
== MAXLONG
)
160 timezone
= tb
.timezone
;
164 #define WX_TIMEZONE wxGetTimeZone()
165 #elif defined(__DARWIN__)
166 #define WX_GMTOFF_IN_TM
167 #elif defined(__WXWINCE__) && defined(__VISUALC8__)
168 // _timezone is not present in dynamic run-time library
170 // Solution (1): use the function equivalent of _timezone
171 static long wxGetTimeZone()
173 static long s_Timezone
= MAXLONG
; // invalid timezone
174 if (s_Timezone
== MAXLONG
)
178 s_Timezone
= (long) t
;
182 #define WX_TIMEZONE wxGetTimeZone()
184 // Solution (2): using GetTimeZoneInformation
185 static long wxGetTimeZone()
187 static long timezone
= MAXLONG
; // invalid timezone
188 if (timezone
== MAXLONG
)
190 TIME_ZONE_INFORMATION tzi
;
191 ::GetTimeZoneInformation(&tzi
);
196 #define WX_TIMEZONE wxGetTimeZone()
198 // Old method using _timezone: this symbol doesn't exist in the dynamic run-time library (i.e. using /MD)
199 #define WX_TIMEZONE _timezone
201 #else // unknown platform - try timezone
202 #define WX_TIMEZONE timezone
204 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
206 // everyone has strftime except Win CE unless VC8 is used
207 #if !defined(__WXWINCE__) || defined(__VISUALC8__)
208 #define HAVE_STRFTIME
211 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
212 #if defined(__WXWINCE__) && defined(__VISUALC8__)
214 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
217 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
220 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
223 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
226 #else // !wxWinCE with VC8
228 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
229 static wxMutex timeLock
;
232 #ifndef HAVE_LOCALTIME_R
233 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
235 #if wxUSE_THREADS && !defined(__WINDOWS__)
236 // No need to waste time with a mutex on windows since it's using
237 // thread local storage for localtime anyway.
238 wxMutexLocker
locker(timeLock
);
241 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
247 const tm
* const t
= localtime(ticks
);
251 memcpy(temp
, t
, sizeof(struct tm
));
254 #endif // !HAVE_LOCALTIME_R
256 #ifndef HAVE_GMTIME_R
257 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
259 #if wxUSE_THREADS && !defined(__WINDOWS__)
260 // No need to waste time with a mutex on windows since it's
261 // using thread local storage for gmtime anyway.
262 wxMutexLocker
locker(timeLock
);
270 const tm
* const t
= gmtime(ticks
);
274 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
277 #endif // !HAVE_GMTIME_R
279 #endif // wxWinCE with VC8/other platforms
281 // ----------------------------------------------------------------------------
283 // ----------------------------------------------------------------------------
285 // debugging helper: just a convenient replacement of wxCHECK()
286 #define wxDATETIME_CHECK(expr, msg) \
287 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 class wxDateTimeHolidaysModule
: public wxModule
296 virtual bool OnInit()
298 wxDateTimeHolidayAuthority
::AddAuthority(new wxDateTimeWorkDays
);
303 virtual void OnExit()
305 wxDateTimeHolidayAuthority
::ClearAllAuthorities();
306 wxDateTimeHolidayAuthority
::ms_authorities
.clear();
310 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
313 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
315 // ----------------------------------------------------------------------------
317 // ----------------------------------------------------------------------------
320 static const int MONTHS_IN_YEAR
= 12;
322 static const int SEC_PER_MIN
= 60;
324 static const int MIN_PER_HOUR
= 60;
326 static const int HOURS_PER_DAY
= 24;
328 static const long SECONDS_PER_DAY
= 86400l;
330 static const int DAYS_PER_WEEK
= 7;
332 static const long MILLISECONDS_PER_DAY
= 86400000l;
334 // this is the integral part of JDN of the midnight of Jan 1, 1970
335 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
336 static const long EPOCH_JDN
= 2440587l;
338 // used only in asserts
340 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
341 // reference date for us) is Nov 24, 4714BC
342 static const int JDN_0_YEAR
= -4713;
343 static const int JDN_0_MONTH
= wxDateTime
::Nov
;
344 static const int JDN_0_DAY
= 24;
345 #endif // __WXDEBUG__
347 // the constants used for JDN calculations
348 static const long JDN_OFFSET
= 32046l;
349 static const long DAYS_PER_5_MONTHS
= 153l;
350 static const long DAYS_PER_4_YEARS
= 1461l;
351 static const long DAYS_PER_400_YEARS
= 146097l;
353 // this array contains the cumulated number of days in all previous months for
354 // normal and leap years
355 static const wxDateTime
::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
357 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
358 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
361 // ----------------------------------------------------------------------------
363 // ----------------------------------------------------------------------------
365 const char *wxDefaultDateTimeFormat
= "%c";
366 const char *wxDefaultTimeSpanFormat
= "%H:%M:%S";
368 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
369 // indicate an invalid wxDateTime object
370 const wxDateTime wxDefaultDateTime
;
372 wxDateTime
::Country wxDateTime
::ms_country
= wxDateTime
::Country_Unknown
;
374 // ----------------------------------------------------------------------------
376 // ----------------------------------------------------------------------------
378 // debugger helper: shows what the date really is
380 extern const char *wxDumpDate(const wxDateTime
* dt
)
382 static char buf
[128];
384 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
386 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
393 // get the number of days in the given month of the given year
395 wxDateTime
::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime
::Month month
)
397 // the number of days in month in Julian/Gregorian calendar: the first line
398 // is for normal years, the second one is for the leap ones
399 static wxDateTime
::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
401 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
402 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
405 return daysInMonth
[wxDateTime
::IsLeapYear(year
)][month
];
408 // returns the time zone in the C sense, i.e. the difference UTC - local
410 static int GetTimeZone()
412 // set to true when the timezone is set
413 static bool s_timezoneSet
= false;
414 static long gmtoffset
= LONG_MAX
; // invalid timezone
416 // ensure that the timezone variable is set by calling wxLocaltime_r
417 if ( !s_timezoneSet
)
419 // just call wxLocaltime_r() instead of figuring out whether this
420 // system supports tzset(), _tzset() or something else
424 wxLocaltime_r(&t
, &tm
);
425 s_timezoneSet
= true;
427 #ifdef WX_GMTOFF_IN_TM
428 // note that GMT offset is the opposite of time zone and so to return
429 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
430 // cases we have to negate it
431 gmtoffset
= -tm
.tm_gmtoff
;
432 #else // !WX_GMTOFF_IN_TM
433 gmtoffset
= WX_TIMEZONE
;
434 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
437 return (int)gmtoffset
;
440 // return the integral part of the JDN for the midnight of the given date (to
441 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
442 // noon of the previous day)
443 static long GetTruncatedJDN(wxDateTime
::wxDateTime_t day
,
444 wxDateTime
::Month mon
,
447 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
449 // check the date validity
451 (year
> JDN_0_YEAR
) ||
452 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
453 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
454 _T("date out of range - can't convert to JDN")
457 // make the year positive to avoid problems with negative numbers division
460 // months are counted from March here
462 if ( mon
>= wxDateTime
::Mar
)
472 // now we can simply add all the contributions together
473 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
474 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
475 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
482 // this function is a wrapper around strftime(3) adding error checking
483 static wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
486 // Create temp wxString here to work around mingw/cygwin bug 1046059
487 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
490 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
492 // if the format is valid, buffer must be too small?
493 wxFAIL_MSG(_T("strftime() failed"));
502 #endif // HAVE_STRFTIME
504 // if year and/or month have invalid values, replace them with the current ones
505 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
506 wxDateTime
::Month
*month
)
508 struct tm
*tmNow
= NULL
;
511 if ( *year
== wxDateTime
::Inv_Year
)
513 tmNow
= wxDateTime
::GetTmNow(&tmstruct
);
515 *year
= 1900 + tmNow
->tm_year
;
518 if ( *month
== wxDateTime
::Inv_Month
)
521 tmNow
= wxDateTime
::GetTmNow(&tmstruct
);
523 *month
= (wxDateTime
::Month
)tmNow
->tm_mon
;
527 // fll the struct tm with default values
528 static void InitTm(struct tm
& tm
)
530 // struct tm may have etxra fields (undocumented and with unportable
531 // names) which, nevertheless, must be set to 0
532 memset(&tm
, 0, sizeof(struct tm
));
534 tm
.tm_mday
= 1; // mday 0 is invalid
535 tm
.tm_year
= 76; // any valid year
536 tm
.tm_isdst
= -1; // auto determine
539 // ============================================================================
540 // implementation of wxDateTime
541 // ============================================================================
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
549 year
= (wxDateTime_t
)wxDateTime
::Inv_Year
;
550 mon
= wxDateTime
::Inv_Month
;
552 hour
= min
= sec
= msec
= 0;
553 wday
= wxDateTime
::Inv_WeekDay
;
556 wxDateTime
::Tm
::Tm(const struct tm
& tm
, const TimeZone
& tz
)
560 sec
= (wxDateTime
::wxDateTime_t
)tm
.tm_sec
;
561 min
= (wxDateTime
::wxDateTime_t
)tm
.tm_min
;
562 hour
= (wxDateTime
::wxDateTime_t
)tm
.tm_hour
;
563 mday
= (wxDateTime
::wxDateTime_t
)tm
.tm_mday
;
564 mon
= (wxDateTime
::Month
)tm
.tm_mon
;
565 year
= 1900 + tm
.tm_year
;
566 wday
= (wxDateTime
::wxDateTime_t
)tm
.tm_wday
;
567 yday
= (wxDateTime
::wxDateTime_t
)tm
.tm_yday
;
570 bool wxDateTime
::Tm
::IsValid() const
572 // we allow for the leap seconds, although we don't use them (yet)
573 return (year
!= wxDateTime
::Inv_Year
) && (mon
!= wxDateTime
::Inv_Month
) &&
574 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
575 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
578 void wxDateTime
::Tm
::ComputeWeekDay()
580 // compute the week day from day/month/year: we use the dumbest algorithm
581 // possible: just compute our JDN and then use the (simple to derive)
582 // formula: weekday = (JDN + 1.5) % 7
583 wday
= (wxDateTime
::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
586 void wxDateTime
::Tm
::AddMonths(int monDiff
)
588 // normalize the months field
589 while ( monDiff
< -mon
)
593 monDiff
+= MONTHS_IN_YEAR
;
596 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
600 monDiff
-= MONTHS_IN_YEAR
;
603 mon
= (wxDateTime
::Month
)(mon
+ monDiff
);
605 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
607 // NB: we don't check here that the resulting date is valid, this function
608 // is private and the caller must check it if needed
611 void wxDateTime
::Tm
::AddDays(int dayDiff
)
613 // normalize the days field
614 while ( dayDiff
+ mday
< 1 )
618 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
621 mday
= (wxDateTime
::wxDateTime_t
)( mday
+ dayDiff
);
622 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
624 mday
-= GetNumOfDaysInMonth(year
, mon
);
629 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
633 // ----------------------------------------------------------------------------
635 // ----------------------------------------------------------------------------
637 wxDateTime
::TimeZone
::TimeZone(wxDateTime
::TZ tz
)
641 case wxDateTime
::Local
:
642 // get the offset from C RTL: it returns the difference GMT-local
643 // while we want to have the offset _from_ GMT, hence the '-'
644 m_offset
= -GetTimeZone();
647 case wxDateTime
::GMT_12
:
648 case wxDateTime
::GMT_11
:
649 case wxDateTime
::GMT_10
:
650 case wxDateTime
::GMT_9
:
651 case wxDateTime
::GMT_8
:
652 case wxDateTime
::GMT_7
:
653 case wxDateTime
::GMT_6
:
654 case wxDateTime
::GMT_5
:
655 case wxDateTime
::GMT_4
:
656 case wxDateTime
::GMT_3
:
657 case wxDateTime
::GMT_2
:
658 case wxDateTime
::GMT_1
:
659 m_offset
= -3600*(wxDateTime
::GMT0
- tz
);
662 case wxDateTime
::GMT0
:
663 case wxDateTime
::GMT1
:
664 case wxDateTime
::GMT2
:
665 case wxDateTime
::GMT3
:
666 case wxDateTime
::GMT4
:
667 case wxDateTime
::GMT5
:
668 case wxDateTime
::GMT6
:
669 case wxDateTime
::GMT7
:
670 case wxDateTime
::GMT8
:
671 case wxDateTime
::GMT9
:
672 case wxDateTime
::GMT10
:
673 case wxDateTime
::GMT11
:
674 case wxDateTime
::GMT12
:
675 case wxDateTime
::GMT13
:
676 m_offset
= 3600*(tz
- wxDateTime
::GMT0
);
679 case wxDateTime
::A_CST
:
680 // Central Standard Time in use in Australia = UTC + 9.5
681 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
685 wxFAIL_MSG( _T("unknown time zone") );
689 // ----------------------------------------------------------------------------
691 // ----------------------------------------------------------------------------
694 bool wxDateTime
::IsLeapYear(int year
, wxDateTime
::Calendar cal
)
696 if ( year
== Inv_Year
)
697 year
= GetCurrentYear();
699 if ( cal
== Gregorian
)
701 // in Gregorian calendar leap years are those divisible by 4 except
702 // those divisible by 100 unless they're also divisible by 400
703 // (in some countries, like Russia and Greece, additional corrections
704 // exist, but they won't manifest themselves until 2700)
705 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
707 else if ( cal
== Julian
)
709 // in Julian calendar the rule is simpler
710 return year
% 4 == 0;
714 wxFAIL_MSG(_T("unknown calendar"));
721 int wxDateTime
::GetCentury(int year
)
723 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
727 int wxDateTime
::ConvertYearToBC(int year
)
730 return year
> 0 ? year
: year
- 1;
734 int wxDateTime
::GetCurrentYear(wxDateTime
::Calendar cal
)
739 return Now().GetYear();
742 wxFAIL_MSG(_T("TODO"));
746 wxFAIL_MSG(_T("unsupported calendar"));
754 wxDateTime
::Month wxDateTime
::GetCurrentMonth(wxDateTime
::Calendar cal
)
759 return Now().GetMonth();
762 wxFAIL_MSG(_T("TODO"));
766 wxFAIL_MSG(_T("unsupported calendar"));
774 wxDateTime
::wxDateTime_t wxDateTime
::GetNumberOfDays(int year
, Calendar cal
)
776 if ( year
== Inv_Year
)
778 // take the current year if none given
779 year
= GetCurrentYear();
786 return IsLeapYear(year
) ?
366 : 365;
789 wxFAIL_MSG(_T("unsupported calendar"));
797 wxDateTime
::wxDateTime_t wxDateTime
::GetNumberOfDays(wxDateTime
::Month month
,
799 wxDateTime
::Calendar cal
)
801 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
803 if ( cal
== Gregorian
|| cal
== Julian
)
805 if ( year
== Inv_Year
)
807 // take the current year if none given
808 year
= GetCurrentYear();
811 return GetNumOfDaysInMonth(year
, month
);
815 wxFAIL_MSG(_T("unsupported calendar"));
822 wxString wxDateTime
::GetMonthName(wxDateTime
::Month month
,
823 wxDateTime
::NameFlags flags
)
825 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, _T("invalid month") );
827 // notice that we must set all the fields to avoid confusing libc (GNU one
828 // gets confused to a crash if we don't do this)
833 return CallStrftime(flags
== Name_Abbr ?
_T("%b") : _T("%B"), &tm
);
834 #else // !HAVE_STRFTIME
839 ret
= (flags
== Name_Abbr ?
wxT("Jan"): wxT("January"));
842 ret
= (flags
== Name_Abbr ?
wxT("Feb"): wxT("Febuary"));
845 ret
= (flags
== Name_Abbr ?
wxT("Mar"): wxT("March"));
848 ret
= (flags
== Name_Abbr ?
wxT("Apr"): wxT("April"));
851 ret
= (flags
== Name_Abbr ?
wxT("May"): wxT("May"));
854 ret
= (flags
== Name_Abbr ?
wxT("Jun"): wxT("June"));
857 ret
= (flags
== Name_Abbr ?
wxT("Jul"): wxT("July"));
860 ret
= (flags
== Name_Abbr ?
wxT("Aug"): wxT("August"));
863 ret
= (flags
== Name_Abbr ?
wxT("Sep"): wxT("September"));
866 ret
= (flags
== Name_Abbr ?
wxT("Oct"): wxT("October"));
869 ret
= (flags
== Name_Abbr ?
wxT("Nov"): wxT("November"));
872 ret
= (flags
== Name_Abbr ?
wxT("Dec"): wxT("December"));
876 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
880 wxString wxDateTime
::GetWeekDayName(wxDateTime
::WeekDay wday
,
881 wxDateTime
::NameFlags flags
)
883 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, _T("invalid weekday") );
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
894 // and offset it by the number of days needed to get the correct wday
897 // call mktime() to normalize it...
900 // ... and call strftime()
901 return CallStrftime(flags
== Name_Abbr ?
_T("%a") : _T("%A"), &tm
);
902 #else // !HAVE_STRFTIME
907 ret
= (flags
== Name_Abbr ?
wxT("Sun") : wxT("Sunday"));
910 ret
= (flags
== Name_Abbr ?
wxT("Mon") : wxT("Monday"));
913 ret
= (flags
== Name_Abbr ?
wxT("Tue") : wxT("Tuesday"));
916 ret
= (flags
== Name_Abbr ?
wxT("Wed") : wxT("Wednesday"));
919 ret
= (flags
== Name_Abbr ?
wxT("Thu") : wxT("Thursday"));
922 ret
= (flags
== Name_Abbr ?
wxT("Fri") : wxT("Friday"));
925 ret
= (flags
== Name_Abbr ?
wxT("Sat") : wxT("Saturday"));
929 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
933 void wxDateTime
::GetAmPmStrings(wxString
*am
, wxString
*pm
)
938 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
939 // and causes an assertion failed if the buffer is to small (which is good) - OR -
940 // if strftime does not return anything because the format string is invalid - OR -
941 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
942 // wxDateTime::ParseTime will try several different formats to parse the time.
943 // As a result, GetAmPmStrings might get called, even if the current locale
944 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
945 // assert, even though it is a perfectly legal use.
948 if (wxStrftime(buffer
, sizeof(buffer
)/sizeof(wxChar
), _T("%p"), &tm
) > 0)
949 *am
= wxString(buffer
);
956 if (wxStrftime(buffer
, sizeof(buffer
)/sizeof(wxChar
), _T("%p"), &tm
) > 0)
957 *pm
= wxString(buffer
);
964 // ----------------------------------------------------------------------------
965 // Country stuff: date calculations depend on the country (DST, work days,
966 // ...), so we need to know which rules to follow.
967 // ----------------------------------------------------------------------------
970 wxDateTime
::Country wxDateTime
::GetCountry()
972 // TODO use LOCALE_ICOUNTRY setting under Win32
974 if ( ms_country
== Country_Unknown
)
976 // try to guess from the time zone name
977 time_t t
= time(NULL
);
979 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
981 wxString tz
= CallStrftime(_T("%Z"), tm
);
982 if ( tz
== _T("WET") || tz
== _T("WEST") )
986 else if ( tz
== _T("CET") || tz
== _T("CEST") )
988 ms_country
= Country_EEC
;
990 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
994 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
995 tz
== _T("EST") || tz
== _T("EDT") ||
996 tz
== _T("CST") || tz
== _T("CDT") ||
997 tz
== _T("MST") || tz
== _T("MDT") ||
998 tz
== _T("PST") || tz
== _T("PDT") )
1004 // well, choose a default one
1008 #else // __WXWINCE__
1010 #endif // !__WXWINCE__/__WXWINCE__
1016 void wxDateTime
::SetCountry(wxDateTime
::Country country
)
1018 ms_country
= country
;
1022 bool wxDateTime
::IsWestEuropeanCountry(Country country
)
1024 if ( country
== Country_Default
)
1026 country
= GetCountry();
1029 return (Country_WesternEurope_Start
<= country
) &&
1030 (country
<= Country_WesternEurope_End
);
1033 // ----------------------------------------------------------------------------
1034 // DST calculations: we use 3 different rules for the West European countries,
1035 // USA and for the rest of the world. This is undoubtedly false for many
1036 // countries, but I lack the necessary info (and the time to gather it),
1037 // please add the other rules here!
1038 // ----------------------------------------------------------------------------
1041 bool wxDateTime
::IsDSTApplicable(int year
, Country country
)
1043 if ( year
== Inv_Year
)
1045 // take the current year if none given
1046 year
= GetCurrentYear();
1049 if ( country
== Country_Default
)
1051 country
= GetCountry();
1058 // DST was first observed in the US and UK during WWI, reused
1059 // during WWII and used again since 1966
1060 return year
>= 1966 ||
1061 (year
>= 1942 && year
<= 1945) ||
1062 (year
== 1918 || year
== 1919);
1065 // assume that it started after WWII
1071 wxDateTime wxDateTime
::GetBeginDST(int year
, Country country
)
1073 if ( year
== Inv_Year
)
1075 // take the current year if none given
1076 year
= GetCurrentYear();
1079 if ( country
== Country_Default
)
1081 country
= GetCountry();
1084 if ( !IsDSTApplicable(year
, country
) )
1086 return wxInvalidDateTime
;
1091 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1093 // DST begins at 1 a.m. GMT on the last Sunday of March
1094 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1097 wxFAIL_MSG( _T("no last Sunday in March?") );
1100 dt
+= wxTimeSpan
::Hours(1);
1102 else switch ( country
)
1109 // don't know for sure - assume it was in effect all year
1114 dt
.Set(1, Jan
, year
);
1118 // DST was installed Feb 2, 1942 by the Congress
1119 dt
.Set(2, Feb
, year
);
1122 // Oil embargo changed the DST period in the US
1124 dt
.Set(6, Jan
, 1974);
1128 dt
.Set(23, Feb
, 1975);
1132 // before 1986, DST begun on the last Sunday of April, but
1133 // in 1986 Reagan changed it to begin at 2 a.m. of the
1134 // first Sunday in April
1137 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1140 wxFAIL_MSG( _T("no first Sunday in April?") );
1143 else if ( year
> 2006 )
1144 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1145 // Starting in 2007, daylight time begins in the United States on the
1146 // second Sunday in March and ends on the first Sunday in November
1148 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1151 wxFAIL_MSG( _T("no second Sunday in March?") );
1156 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1159 wxFAIL_MSG( _T("no first Sunday in April?") );
1163 dt
+= wxTimeSpan
::Hours(2);
1165 // TODO what about timezone??
1171 // assume Mar 30 as the start of the DST for the rest of the world
1172 // - totally bogus, of course
1173 dt
.Set(30, Mar
, year
);
1180 wxDateTime wxDateTime
::GetEndDST(int year
, Country country
)
1182 if ( year
== Inv_Year
)
1184 // take the current year if none given
1185 year
= GetCurrentYear();
1188 if ( country
== Country_Default
)
1190 country
= GetCountry();
1193 if ( !IsDSTApplicable(year
, country
) )
1195 return wxInvalidDateTime
;
1200 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1202 // DST ends at 1 a.m. GMT on the last Sunday of October
1203 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1205 // weirder and weirder...
1206 wxFAIL_MSG( _T("no last Sunday in October?") );
1209 dt
+= wxTimeSpan
::Hours(1);
1211 else switch ( country
)
1218 // don't know for sure - assume it was in effect all year
1222 dt
.Set(31, Dec
, year
);
1226 // the time was reset after the end of the WWII
1227 dt
.Set(30, Sep
, year
);
1230 default: // default for switch (year)
1232 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1233 // Starting in 2007, daylight time begins in the United States on the
1234 // second Sunday in March and ends on the first Sunday in November
1236 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1239 wxFAIL_MSG( _T("no first Sunday in November?") );
1244 // DST ends at 2 a.m. on the last Sunday of October
1246 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1248 // weirder and weirder...
1249 wxFAIL_MSG( _T("no last Sunday in October?") );
1253 dt
+= wxTimeSpan
::Hours(2);
1255 // TODO: what about timezone??
1259 default: // default for switch (country)
1260 // assume October 26th as the end of the DST - totally bogus too
1261 dt
.Set(26, Oct
, year
);
1267 // ----------------------------------------------------------------------------
1268 // constructors and assignment operators
1269 // ----------------------------------------------------------------------------
1271 // return the current time with ms precision
1272 /* static */ wxDateTime wxDateTime
::UNow()
1274 return wxDateTime(wxGetLocalTimeMillis());
1277 // the values in the tm structure contain the local time
1278 wxDateTime
& wxDateTime
::Set(const struct tm
& tm
)
1281 time_t timet
= mktime(&tm2
);
1283 if ( timet
== (time_t)-1 )
1285 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1286 // less than timezone - try to make it work for this case
1287 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1289 return Set((time_t)(
1291 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1292 tm2
.tm_min
* SEC_PER_MIN
+
1296 wxFAIL_MSG( _T("mktime() failed") );
1298 *this = wxInvalidDateTime
;
1308 wxDateTime
& wxDateTime
::Set(wxDateTime_t hour
,
1309 wxDateTime_t minute
,
1310 wxDateTime_t second
,
1311 wxDateTime_t millisec
)
1313 // we allow seconds to be 61 to account for the leap seconds, even if we
1314 // don't use them really
1315 wxDATETIME_CHECK( hour
< 24 &&
1319 _T("Invalid time in wxDateTime::Set()") );
1321 // get the current date from system
1323 struct tm
*tm
= GetTmNow(&tmstruct
);
1325 wxDATETIME_CHECK( tm
, _T("wxLocaltime_r() failed") );
1327 // make a copy so it isn't clobbered by the call to mktime() below
1332 tm1
.tm_min
= minute
;
1333 tm1
.tm_sec
= second
;
1335 // and the DST in case it changes on this date
1338 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1339 tm1
.tm_isdst
= tm2
.tm_isdst
;
1343 // and finally adjust milliseconds
1344 return SetMillisecond(millisec
);
1347 wxDateTime
& wxDateTime
::Set(wxDateTime_t day
,
1351 wxDateTime_t minute
,
1352 wxDateTime_t second
,
1353 wxDateTime_t millisec
)
1355 wxDATETIME_CHECK( hour
< 24 &&
1359 _T("Invalid time in wxDateTime::Set()") );
1361 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1363 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1364 _T("Invalid date in wxDateTime::Set()") );
1366 // the range of time_t type (inclusive)
1367 static const int yearMinInRange
= 1970;
1368 static const int yearMaxInRange
= 2037;
1370 // test only the year instead of testing for the exact end of the Unix
1371 // time_t range - it doesn't bring anything to do more precise checks
1372 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1374 // use the standard library version if the date is in range - this is
1375 // probably more efficient than our code
1377 tm
.tm_year
= year
- 1900;
1383 tm
.tm_isdst
= -1; // mktime() will guess it
1387 // and finally adjust milliseconds
1389 SetMillisecond(millisec
);
1395 // do time calculations ourselves: we want to calculate the number of
1396 // milliseconds between the given date and the epoch
1398 // get the JDN for the midnight of this day
1399 m_time
= GetTruncatedJDN(day
, month
, year
);
1400 m_time
-= EPOCH_JDN
;
1401 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1403 // JDN corresponds to GMT, we take localtime
1404 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1410 wxDateTime
& wxDateTime
::Set(double jdn
)
1412 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1414 jdn
-= EPOCH_JDN
+ 0.5;
1416 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1418 // JDNs always are in UTC, so we don't need any adjustments for time zone
1423 wxDateTime
& wxDateTime
::ResetTime()
1427 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1440 wxDateTime wxDateTime
::GetDateOnly() const
1447 return wxDateTime(tm
);
1450 // ----------------------------------------------------------------------------
1451 // DOS Date and Time Format functions
1452 // ----------------------------------------------------------------------------
1453 // the dos date and time value is an unsigned 32 bit value in the format:
1454 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1456 // Y = year offset from 1980 (0-127)
1458 // D = day of month (1-31)
1460 // m = minute (0-59)
1461 // s = bisecond (0-29) each bisecond indicates two seconds
1462 // ----------------------------------------------------------------------------
1464 wxDateTime
& wxDateTime
::SetFromDOS(unsigned long ddt
)
1469 long year
= ddt
& 0xFE000000;
1474 long month
= ddt
& 0x1E00000;
1479 long day
= ddt
& 0x1F0000;
1483 long hour
= ddt
& 0xF800;
1487 long minute
= ddt
& 0x7E0;
1491 long second
= ddt
& 0x1F;
1492 tm
.tm_sec
= second
* 2;
1494 return Set(mktime(&tm
));
1497 unsigned long wxDateTime
::GetAsDOS() const
1500 time_t ticks
= GetTicks();
1502 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1503 wxCHECK_MSG( tm
, ULONG_MAX
, _T("time can't be represented in DOS format") );
1505 long year
= tm
->tm_year
;
1509 long month
= tm
->tm_mon
;
1513 long day
= tm
->tm_mday
;
1516 long hour
= tm
->tm_hour
;
1519 long minute
= tm
->tm_min
;
1522 long second
= tm
->tm_sec
;
1525 ddt
= year
| month
| day
| hour
| minute
| second
;
1529 // ----------------------------------------------------------------------------
1530 // time_t <-> broken down time conversions
1531 // ----------------------------------------------------------------------------
1533 wxDateTime
::Tm wxDateTime
::GetTm(const TimeZone
& tz
) const
1535 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1537 time_t time
= GetTicks();
1538 if ( time
!= (time_t)-1 )
1540 // use C RTL functions
1543 if ( tz
.GetOffset() == -GetTimeZone() )
1545 // we are working with local time
1546 tm
= wxLocaltime_r(&time
, &tmstruct
);
1548 // should never happen
1549 wxCHECK_MSG( tm
, Tm(), _T("wxLocaltime_r() failed") );
1553 time
+= (time_t)tz
.GetOffset();
1554 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1555 int time2
= (int) time
;
1561 tm
= wxGmtime_r(&time
, &tmstruct
);
1563 // should never happen
1564 wxCHECK_MSG( tm
, Tm(), _T("wxGmtime_r() failed") );
1568 tm
= (struct tm
*)NULL
;
1574 // adjust the milliseconds
1576 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1577 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1580 //else: use generic code below
1583 // remember the time and do the calculations with the date only - this
1584 // eliminates rounding errors of the floating point arithmetics
1586 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1588 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1590 // we want to always have positive time and timeMidnight to be really
1591 // the midnight before it
1594 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1597 timeMidnight
-= timeOnly
;
1599 // calculate the Gregorian date from JDN for the midnight of our date:
1600 // this will yield day, month (in 1..12 range) and year
1602 // actually, this is the JDN for the noon of the previous day
1603 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1605 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1607 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1609 // calculate the century
1610 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1611 long century
= temp
/ DAYS_PER_400_YEARS
;
1613 // then the year and day of year (1 <= dayOfYear <= 366)
1614 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1615 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1616 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1618 // and finally the month and day of the month
1619 temp
= dayOfYear
* 5 - 3;
1620 long month
= temp
/ DAYS_PER_5_MONTHS
;
1621 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1623 // month is counted from March - convert to normal
1634 // year is offset by 4800
1637 // check that the algorithm gave us something reasonable
1638 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1639 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1641 // construct Tm from these values
1643 tm
.year
= (int)year
;
1644 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1645 tm
.mday
= (wxDateTime_t
)day
;
1646 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1647 timeOnly
-= tm
.msec
;
1648 timeOnly
/= 1000; // now we have time in seconds
1650 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1652 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1654 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1657 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1662 wxDateTime
& wxDateTime
::SetYear(int year
)
1664 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1673 wxDateTime
& wxDateTime
::SetMonth(Month month
)
1675 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1684 wxDateTime
& wxDateTime
::SetDay(wxDateTime_t mday
)
1686 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1695 wxDateTime
& wxDateTime
::SetHour(wxDateTime_t hour
)
1697 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1706 wxDateTime
& wxDateTime
::SetMinute(wxDateTime_t min
)
1708 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1717 wxDateTime
& wxDateTime
::SetSecond(wxDateTime_t sec
)
1719 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1728 wxDateTime
& wxDateTime
::SetMillisecond(wxDateTime_t millisecond
)
1730 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1732 // we don't need to use GetTm() for this one
1733 m_time
-= m_time
% 1000l;
1734 m_time
+= millisecond
;
1739 // ----------------------------------------------------------------------------
1740 // wxDateTime arithmetics
1741 // ----------------------------------------------------------------------------
1743 wxDateTime
& wxDateTime
::Add(const wxDateSpan
& diff
)
1747 tm
.year
+= diff
.GetYears();
1748 tm
.AddMonths(diff
.GetMonths());
1750 // check that the resulting date is valid
1751 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1753 // We suppose that when adding one month to Jan 31 we want to get Feb
1754 // 28 (or 29), i.e. adding a month to the last day of the month should
1755 // give the last day of the next month which is quite logical.
1757 // Unfortunately, there is no logic way to understand what should
1758 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1759 // We make it Feb 28 (last day too), but it is highly questionable.
1760 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1763 tm
.AddDays(diff
.GetTotalDays());
1767 wxASSERT_MSG( IsSameTime(tm
),
1768 _T("Add(wxDateSpan) shouldn't modify time") );
1773 // ----------------------------------------------------------------------------
1774 // Weekday and monthday stuff
1775 // ----------------------------------------------------------------------------
1777 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1778 static inline int ConvertWeekDayToMondayBase(int wd
)
1780 return wd
== wxDateTime
::Sun ?
6 : wd
- 1;
1785 wxDateTime
::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1787 wxASSERT_MSG( numWeek
> 0,
1788 _T("invalid week number: weeks are counted from 1") );
1790 // Jan 4 always lies in the 1st week of the year
1791 wxDateTime
dt(4, Jan
, year
);
1792 dt
.SetToWeekDayInSameWeek(wd
);
1793 dt
+= wxDateSpan
::Weeks(numWeek
- 1);
1798 #if WXWIN_COMPATIBILITY_2_6
1799 // use a separate function to avoid warnings about using deprecated
1800 // SetToTheWeek in GetWeek below
1802 SetToTheWeek(int year
,
1803 wxDateTime
::wxDateTime_t numWeek
,
1804 wxDateTime
::WeekDay weekday
,
1805 wxDateTime
::WeekFlags flags
)
1807 // Jan 4 always lies in the 1st week of the year
1808 wxDateTime
dt(4, wxDateTime
::Jan
, year
);
1809 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1810 dt
+= wxDateSpan
::Weeks(numWeek
- 1);
1815 bool wxDateTime
::SetToTheWeek(wxDateTime_t numWeek
,
1819 int year
= GetYear();
1820 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1821 if ( GetYear() != year
)
1823 // oops... numWeek was too big
1830 wxDateTime wxDateTime
::GetWeek(wxDateTime_t numWeek
,
1832 WeekFlags flags
) const
1834 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1836 #endif // WXWIN_COMPATIBILITY_2_6
1838 wxDateTime
& wxDateTime
::SetToLastMonthDay(Month month
,
1841 // take the current month/year if none specified
1842 if ( year
== Inv_Year
)
1844 if ( month
== Inv_Month
)
1847 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1850 wxDateTime
& wxDateTime
::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1852 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1854 int wdayDst
= weekday
,
1855 wdayThis
= GetWeekDay();
1856 if ( wdayDst
== wdayThis
)
1862 if ( flags
== Default_First
)
1864 flags
= GetCountry() == USA ? Sunday_First
: Monday_First
;
1867 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1868 // is the first day in the week, but breaks down for Monday_First case so
1869 // we adjust the week days in this case
1870 if ( flags
== Monday_First
)
1872 if ( wdayThis
== Sun
)
1874 if ( wdayDst
== Sun
)
1877 //else: Sunday_First, nothing to do
1879 // go forward or back in time to the day we want
1880 if ( wdayDst
< wdayThis
)
1882 return Subtract(wxDateSpan
::Days(wdayThis
- wdayDst
));
1884 else // weekday > wdayThis
1886 return Add(wxDateSpan
::Days(wdayDst
- wdayThis
));
1890 wxDateTime
& wxDateTime
::SetToNextWeekDay(WeekDay weekday
)
1892 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1895 WeekDay wdayThis
= GetWeekDay();
1896 if ( weekday
== wdayThis
)
1901 else if ( weekday
< wdayThis
)
1903 // need to advance a week
1904 diff
= 7 - (wdayThis
- weekday
);
1906 else // weekday > wdayThis
1908 diff
= weekday
- wdayThis
;
1911 return Add(wxDateSpan
::Days(diff
));
1914 wxDateTime
& wxDateTime
::SetToPrevWeekDay(WeekDay weekday
)
1916 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1919 WeekDay wdayThis
= GetWeekDay();
1920 if ( weekday
== wdayThis
)
1925 else if ( weekday
> wdayThis
)
1927 // need to go to previous week
1928 diff
= 7 - (weekday
- wdayThis
);
1930 else // weekday < wdayThis
1932 diff
= wdayThis
- weekday
;
1935 return Subtract(wxDateSpan
::Days(diff
));
1938 bool wxDateTime
::SetToWeekDay(WeekDay weekday
,
1943 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, _T("invalid weekday") );
1945 // we don't check explicitly that -5 <= n <= 5 because we will return false
1946 // anyhow in such case - but may be should still give an assert for it?
1948 // take the current month/year if none specified
1949 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1953 // TODO this probably could be optimised somehow...
1957 // get the first day of the month
1958 dt
.Set(1, month
, year
);
1961 WeekDay wdayFirst
= dt
.GetWeekDay();
1963 // go to the first weekday of the month
1964 int diff
= weekday
- wdayFirst
;
1968 // add advance n-1 weeks more
1971 dt
+= wxDateSpan
::Days(diff
);
1973 else // count from the end of the month
1975 // get the last day of the month
1976 dt
.SetToLastMonthDay(month
, year
);
1979 WeekDay wdayLast
= dt
.GetWeekDay();
1981 // go to the last weekday of the month
1982 int diff
= wdayLast
- weekday
;
1986 // and rewind n-1 weeks from there
1989 dt
-= wxDateSpan
::Days(diff
);
1992 // check that it is still in the same month
1993 if ( dt
.GetMonth() == month
)
2001 // no such day in this month
2007 wxDateTime
::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime
::Tm
& tm
)
2009 return (wxDateTime
::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime
::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
2012 wxDateTime
::wxDateTime_t wxDateTime
::GetDayOfYear(const TimeZone
& tz
) const
2014 return GetDayOfYearFromTm(GetTm(tz
));
2017 wxDateTime
::wxDateTime_t
2018 wxDateTime
::GetWeekOfYear(wxDateTime
::WeekFlags flags
, const TimeZone
& tz
) const
2020 if ( flags
== Default_First
)
2022 flags
= GetCountry() == USA ? Sunday_First
: Monday_First
;
2026 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
2028 int wdTarget
= GetWeekDay(tz
);
2029 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
2031 if ( flags
== Sunday_First
)
2033 // FIXME: First week is not calculated correctly.
2034 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2035 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2038 else // week starts with monday
2040 // adjust the weekdays to non-US style.
2041 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2042 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2044 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2046 // Week 01 of a year is per definition the first week that has the
2047 // Thursday in this year, which is equivalent to the week that
2048 // contains the fourth day of January. In other words, the first
2049 // week of a new year is the week that has the majority of its
2050 // days in the new year. Week 01 might also contain days from the
2051 // previous year and the week before week 01 of a year is the last
2052 // week (52 or 53) of the previous year even if it contains days
2053 // from the new year. A week starts with Monday (day 1) and ends
2054 // with Sunday (day 7).
2057 // if Jan 1 is Thursday or less, it is in the first week of this year
2058 if ( wdYearStart
< 4 )
2060 // count the number of entire weeks between Jan 1 and this date
2061 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2063 // be careful to check for overflow in the next year
2064 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2067 else // Jan 1 is in the last week of the previous year
2069 // check if we happen to be at the last week of previous year:
2070 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2071 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2073 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2077 return (wxDateTime
::wxDateTime_t
)week
;
2080 wxDateTime
::wxDateTime_t wxDateTime
::GetWeekOfMonth(wxDateTime
::WeekFlags flags
,
2081 const TimeZone
& tz
) const
2084 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
2085 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
2088 // this may happen for January when Jan, 1 is the last week of the
2090 nWeek
+= IsLeapYear(tm
.year
- 1) ?
53 : 52;
2093 return (wxDateTime
::wxDateTime_t
)nWeek
;
2096 wxDateTime
& wxDateTime
::SetToYearDay(wxDateTime
::wxDateTime_t yday
)
2098 int year
= GetYear();
2099 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2100 _T("invalid year day") );
2102 bool isLeap
= IsLeapYear(year
);
2103 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2105 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2106 // don't need it neither - because of the CHECK above we know that
2107 // yday lies in December then
2108 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2110 Set((wxDateTime
::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2119 // ----------------------------------------------------------------------------
2120 // Julian day number conversion and related stuff
2121 // ----------------------------------------------------------------------------
2123 double wxDateTime
::GetJulianDayNumber() const
2125 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2128 double wxDateTime
::GetRataDie() const
2130 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2131 return GetJulianDayNumber() - 1721119.5 - 306;
2134 // ----------------------------------------------------------------------------
2135 // timezone and DST stuff
2136 // ----------------------------------------------------------------------------
2138 int wxDateTime
::IsDST(wxDateTime
::Country country
) const
2140 wxCHECK_MSG( country
== Country_Default
, -1,
2141 _T("country support not implemented") );
2143 // use the C RTL for the dates in the standard range
2144 time_t timet
= GetTicks();
2145 if ( timet
!= (time_t)-1 )
2148 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2150 wxCHECK_MSG( tm
, -1, _T("wxLocaltime_r() failed") );
2152 return tm
->tm_isdst
;
2156 int year
= GetYear();
2158 if ( !IsDSTApplicable(year
, country
) )
2160 // no DST time in this year in this country
2164 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2168 wxDateTime
& wxDateTime
::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2170 long secDiff
= GetTimeZone() + tz
.GetOffset();
2172 // we need to know whether DST is or not in effect for this date unless
2173 // the test disabled by the caller
2174 if ( !noDST
&& (IsDST() == 1) )
2176 // FIXME we assume that the DST is always shifted by 1 hour
2180 return Add(wxTimeSpan
::Seconds(secDiff
));
2183 wxDateTime
& wxDateTime
::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2185 long secDiff
= GetTimeZone() + tz
.GetOffset();
2187 // we need to know whether DST is or not in effect for this date unless
2188 // the test disabled by the caller
2189 if ( !noDST
&& (IsDST() == 1) )
2191 // FIXME we assume that the DST is always shifted by 1 hour
2195 return Subtract(wxTimeSpan
::Seconds(secDiff
));
2198 // ============================================================================
2199 // wxDateTimeHolidayAuthority and related classes
2200 // ============================================================================
2202 #include "wx/arrimpl.cpp"
2204 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2206 static int wxCMPFUNC_CONV
2207 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2209 wxDateTime dt1
= **first
,
2212 return dt1
== dt2 ?
0 : dt1
< dt2 ?
-1 : +1;
2215 // ----------------------------------------------------------------------------
2216 // wxDateTimeHolidayAuthority
2217 // ----------------------------------------------------------------------------
2219 wxHolidayAuthoritiesArray wxDateTimeHolidayAuthority
::ms_authorities
;
2222 bool wxDateTimeHolidayAuthority
::IsHoliday(const wxDateTime
& dt
)
2224 size_t count
= ms_authorities
.size();
2225 for ( size_t n
= 0; n
< count
; n
++ )
2227 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2238 wxDateTimeHolidayAuthority
::GetHolidaysInRange(const wxDateTime
& dtStart
,
2239 const wxDateTime
& dtEnd
,
2240 wxDateTimeArray
& holidays
)
2242 wxDateTimeArray hol
;
2246 const size_t countAuth
= ms_authorities
.size();
2247 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2249 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2251 WX_APPEND_ARRAY(holidays
, hol
);
2254 holidays
.Sort(wxDateTimeCompareFunc
);
2256 return holidays
.size();
2260 void wxDateTimeHolidayAuthority
::ClearAllAuthorities()
2262 WX_CLEAR_ARRAY(ms_authorities
);
2266 void wxDateTimeHolidayAuthority
::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2268 ms_authorities
.push_back(auth
);
2271 wxDateTimeHolidayAuthority
::~wxDateTimeHolidayAuthority()
2273 // required here for Darwin
2276 // ----------------------------------------------------------------------------
2277 // wxDateTimeWorkDays
2278 // ----------------------------------------------------------------------------
2280 bool wxDateTimeWorkDays
::DoIsHoliday(const wxDateTime
& dt
) const
2282 wxDateTime
::WeekDay wd
= dt
.GetWeekDay();
2284 return (wd
== wxDateTime
::Sun
) || (wd
== wxDateTime
::Sat
);
2287 size_t wxDateTimeWorkDays
::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2288 const wxDateTime
& dtEnd
,
2289 wxDateTimeArray
& holidays
) const
2291 if ( dtStart
> dtEnd
)
2293 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
2300 // instead of checking all days, start with the first Sat after dtStart and
2301 // end with the last Sun before dtEnd
2302 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime
::Sat
),
2303 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime
::Sat
),
2304 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime
::Sun
),
2305 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime
::Sun
),
2308 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan
::Week() )
2313 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan
::Week() )
2318 return holidays
.GetCount();
2321 // ============================================================================
2322 // other helper functions
2323 // ============================================================================
2325 // ----------------------------------------------------------------------------
2326 // iteration helpers: can be used to write a for loop over enum variable like
2328 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2329 // ----------------------------------------------------------------------------
2331 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime
::Month
& m
)
2333 wxASSERT_MSG( m
< wxDateTime
::Inv_Month
, _T("invalid month") );
2335 // no wrapping or the for loop above would never end!
2336 m
= (wxDateTime
::Month
)(m
+ 1);
2339 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime
::Month
& m
)
2341 wxASSERT_MSG( m
< wxDateTime
::Inv_Month
, _T("invalid month") );
2343 m
= m
== wxDateTime
::Jan ? wxDateTime
::Inv_Month
2344 : (wxDateTime
::Month
)(m
- 1);
2347 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime
::WeekDay
& wd
)
2349 wxASSERT_MSG( wd
< wxDateTime
::Inv_WeekDay
, _T("invalid week day") );
2351 // no wrapping or the for loop above would never end!
2352 wd
= (wxDateTime
::WeekDay
)(wd
+ 1);
2355 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime
::WeekDay
& wd
)
2357 wxASSERT_MSG( wd
< wxDateTime
::Inv_WeekDay
, _T("invalid week day") );
2359 wd
= wd
== wxDateTime
::Sun ? wxDateTime
::Inv_WeekDay
2360 : (wxDateTime
::WeekDay
)(wd
- 1);
2365 wxDateTime
& wxDateTime
::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2368 static_cast<wxDateTime
::Month
>(wxDateTime
::Jan
+ st
.wMonth
- 1),
2373 void wxDateTime
::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2375 const wxDateTime
::Tm
tm(GetTm());
2377 st
->wYear
= (WXWORD
)tm
.year
;
2378 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime
::Jan
+ 1);
2385 st
->wMilliseconds
= 0;
2389 #endif // wxUSE_DATETIME