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 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 #if wxUSE_EXTENDED_RTTI
97 template<> void wxStringReadValue(const wxString
&s
, wxDateTime
&data
)
99 data
.ParseFormat(s
,"%Y-%m-%d %H:%M:%S", NULL
);
102 template<> void wxStringWriteValue(wxString
&s
, const wxDateTime
&data
)
104 s
= data
.Format("%Y-%m-%d %H:%M:%S");
107 wxCUSTOM_TYPE_INFO(wxDateTime
, wxToStringConverter
<wxDateTime
> , wxFromStringConverter
<wxDateTime
>)
109 #endif // wxUSE_EXTENDED_RTTI
112 // ----------------------------------------------------------------------------
113 // conditional compilation
114 // ----------------------------------------------------------------------------
116 #if defined(__MWERKS__) && wxUSE_UNICODE
120 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
121 #if defined(__WXPALMOS__)
122 #define WX_GMTOFF_IN_TM
123 #elif defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
124 #define WX_TIMEZONE _timezone
125 #elif defined(__MWERKS__)
126 long wxmw_timezone
= 28800;
127 #define WX_TIMEZONE wxmw_timezone
128 #elif defined(__DJGPP__) || defined(__WINE__)
129 #include <sys/timeb.h>
131 static long wxGetTimeZone()
137 #define WX_TIMEZONE wxGetTimeZone()
138 #elif defined(__DARWIN__)
139 #define WX_GMTOFF_IN_TM
140 #elif wxCHECK_VISUALC_VERSION(8)
141 // While _timezone is still present in (some versions of) VC CRT, it's
142 // deprecated and _get_timezone() should be used instead.
143 static long wxGetTimeZone()
145 // The type of _get_timezone() parameter seems to have changed
146 // between VC8 and VC9.
155 #define WX_TIMEZONE wxGetTimeZone()
156 #else // unknown platform - try timezone
157 #define WX_TIMEZONE timezone
159 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
161 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
162 #if defined(__WXWINCE__) && defined(__VISUALC8__)
164 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
167 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
170 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
173 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
176 #else // !wxWinCE with VC8
178 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
179 static wxMutex timeLock
;
182 #ifndef HAVE_LOCALTIME_R
183 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
185 #if wxUSE_THREADS && !defined(__WINDOWS__)
186 // No need to waste time with a mutex on windows since it's using
187 // thread local storage for localtime anyway.
188 wxMutexLocker
locker(timeLock
);
191 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
197 const tm
* const t
= localtime(ticks
);
201 memcpy(temp
, t
, sizeof(struct tm
));
204 #endif // !HAVE_LOCALTIME_R
206 #ifndef HAVE_GMTIME_R
207 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
209 #if wxUSE_THREADS && !defined(__WINDOWS__)
210 // No need to waste time with a mutex on windows since it's
211 // using thread local storage for gmtime anyway.
212 wxMutexLocker
locker(timeLock
);
220 const tm
* const t
= gmtime(ticks
);
224 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
227 #endif // !HAVE_GMTIME_R
229 #endif // wxWinCE with VC8/other platforms
231 // ----------------------------------------------------------------------------
233 // ----------------------------------------------------------------------------
235 // debugging helper: just a convenient replacement of wxCHECK()
236 #define wxDATETIME_CHECK(expr, msg) \
237 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
239 // ----------------------------------------------------------------------------
241 // ----------------------------------------------------------------------------
243 class wxDateTimeHolidaysModule
: public wxModule
246 virtual bool OnInit()
248 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
253 virtual void OnExit()
255 wxDateTimeHolidayAuthority::ClearAllAuthorities();
256 wxDateTimeHolidayAuthority::ms_authorities
.clear();
260 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
263 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
265 // ----------------------------------------------------------------------------
267 // ----------------------------------------------------------------------------
270 static const int MONTHS_IN_YEAR
= 12;
272 static const int SEC_PER_MIN
= 60;
274 static const int MIN_PER_HOUR
= 60;
276 static const long SECONDS_PER_DAY
= 86400l;
278 static const int DAYS_PER_WEEK
= 7;
280 static const long MILLISECONDS_PER_DAY
= 86400000l;
282 // this is the integral part of JDN of the midnight of Jan 1, 1970
283 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
284 static const long EPOCH_JDN
= 2440587l;
286 // these values are only used in asserts so don't define them if asserts are
287 // disabled to avoid warnings about unused static variables
289 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
290 // reference date for us) is Nov 24, 4714BC
291 static const int JDN_0_YEAR
= -4713;
292 static const int JDN_0_MONTH
= wxDateTime::Nov
;
293 static const int JDN_0_DAY
= 24;
294 #endif // wxDEBUG_LEVEL
296 // the constants used for JDN calculations
297 static const long JDN_OFFSET
= 32046l;
298 static const long DAYS_PER_5_MONTHS
= 153l;
299 static const long DAYS_PER_4_YEARS
= 1461l;
300 static const long DAYS_PER_400_YEARS
= 146097l;
302 // this array contains the cumulated number of days in all previous months for
303 // normal and leap years
304 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
306 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
307 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
310 const long wxDateTime::TIME_T_FACTOR
= 1000l;
312 // ----------------------------------------------------------------------------
314 // ----------------------------------------------------------------------------
316 const char wxDefaultDateTimeFormat
[] = "%c";
317 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
319 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
320 // indicate an invalid wxDateTime object
321 const wxDateTime wxDefaultDateTime
;
323 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
325 // ----------------------------------------------------------------------------
327 // ----------------------------------------------------------------------------
329 // debugger helper: this function can be called from a debugger to show what
330 // the date really is
331 extern const char *wxDumpDate(const wxDateTime
* dt
)
333 static char buf
[128];
335 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
337 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
343 // get the number of days in the given month of the given year
345 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
347 // the number of days in month in Julian/Gregorian calendar: the first line
348 // is for normal years, the second one is for the leap ones
349 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
351 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
352 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
355 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
358 // returns the time zone in the C sense, i.e. the difference UTC - local
360 // NOTE: not static because used by datetimefmt.cpp
363 #ifdef WX_GMTOFF_IN_TM
364 // set to true when the timezone is set
365 static bool s_timezoneSet
= false;
366 static long gmtoffset
= LONG_MAX
; // invalid timezone
368 // ensure that the timezone variable is set by calling wxLocaltime_r
369 if ( !s_timezoneSet
)
371 // just call wxLocaltime_r() instead of figuring out whether this
372 // system supports tzset(), _tzset() or something else
376 wxLocaltime_r(&t
, &tm
);
377 s_timezoneSet
= true;
379 // note that GMT offset is the opposite of time zone and so to return
380 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
381 // cases we have to negate it
382 gmtoffset
= -tm
.tm_gmtoff
;
384 return (int)gmtoffset
;
385 #else // !WX_GMTOFF_IN_TM
387 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
390 // return the integral part of the JDN for the midnight of the given date (to
391 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
392 // noon of the previous day)
393 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
394 wxDateTime::Month mon
,
397 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
399 // check the date validity
401 (year
> JDN_0_YEAR
) ||
402 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
403 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
404 wxT("date out of range - can't convert to JDN")
407 // make the year positive to avoid problems with negative numbers division
410 // months are counted from March here
412 if ( mon
>= wxDateTime::Mar
)
422 // now we can simply add all the contributions together
423 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
424 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
425 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
430 #ifdef wxHAS_STRFTIME
432 // this function is a wrapper around strftime(3) adding error checking
433 // NOTE: not static because used by datetimefmt.cpp
434 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
437 // Create temp wxString here to work around mingw/cygwin bug 1046059
438 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
441 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
443 // if the format is valid, buffer must be too small?
444 wxFAIL_MSG(wxT("strftime() failed"));
453 #endif // wxHAS_STRFTIME
455 // if year and/or month have invalid values, replace them with the current ones
456 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
457 wxDateTime::Month
*month
)
459 struct tm
*tmNow
= NULL
;
462 if ( *year
== wxDateTime::Inv_Year
)
464 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
466 *year
= 1900 + tmNow
->tm_year
;
469 if ( *month
== wxDateTime::Inv_Month
)
472 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
474 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
478 // fill the struct tm with default values
479 // NOTE: not static because used by datetimefmt.cpp
480 void InitTm(struct tm
& tm
)
482 // struct tm may have etxra fields (undocumented and with unportable
483 // names) which, nevertheless, must be set to 0
484 memset(&tm
, 0, sizeof(struct tm
));
486 tm
.tm_mday
= 1; // mday 0 is invalid
487 tm
.tm_year
= 76; // any valid year
488 tm
.tm_isdst
= -1; // auto determine
491 // ============================================================================
492 // implementation of wxDateTime
493 // ============================================================================
495 // ----------------------------------------------------------------------------
497 // ----------------------------------------------------------------------------
501 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
502 mon
= wxDateTime::Inv_Month
;
509 wday
= wxDateTime::Inv_WeekDay
;
512 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
516 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
517 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
518 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
519 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
520 mon
= (wxDateTime::Month
)tm
.tm_mon
;
521 year
= 1900 + tm
.tm_year
;
522 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
523 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
526 bool wxDateTime::Tm::IsValid() const
528 // we allow for the leap seconds, although we don't use them (yet)
529 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
530 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
531 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
534 void wxDateTime::Tm::ComputeWeekDay()
536 // compute the week day from day/month/year: we use the dumbest algorithm
537 // possible: just compute our JDN and then use the (simple to derive)
538 // formula: weekday = (JDN + 1.5) % 7
539 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
542 void wxDateTime::Tm::AddMonths(int monDiff
)
544 // normalize the months field
545 while ( monDiff
< -mon
)
549 monDiff
+= MONTHS_IN_YEAR
;
552 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
556 monDiff
-= MONTHS_IN_YEAR
;
559 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
561 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
563 // NB: we don't check here that the resulting date is valid, this function
564 // is private and the caller must check it if needed
567 void wxDateTime::Tm::AddDays(int dayDiff
)
569 // normalize the days field
570 while ( dayDiff
+ mday
< 1 )
574 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
577 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
578 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
580 mday
-= GetNumOfDaysInMonth(year
, mon
);
585 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
586 wxT("logic error") );
589 // ----------------------------------------------------------------------------
591 // ----------------------------------------------------------------------------
593 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
597 case wxDateTime::Local
:
598 // get the offset from C RTL: it returns the difference GMT-local
599 // while we want to have the offset _from_ GMT, hence the '-'
600 m_offset
= -GetTimeZone();
603 case wxDateTime::GMT_12
:
604 case wxDateTime::GMT_11
:
605 case wxDateTime::GMT_10
:
606 case wxDateTime::GMT_9
:
607 case wxDateTime::GMT_8
:
608 case wxDateTime::GMT_7
:
609 case wxDateTime::GMT_6
:
610 case wxDateTime::GMT_5
:
611 case wxDateTime::GMT_4
:
612 case wxDateTime::GMT_3
:
613 case wxDateTime::GMT_2
:
614 case wxDateTime::GMT_1
:
615 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
618 case wxDateTime::GMT0
:
619 case wxDateTime::GMT1
:
620 case wxDateTime::GMT2
:
621 case wxDateTime::GMT3
:
622 case wxDateTime::GMT4
:
623 case wxDateTime::GMT5
:
624 case wxDateTime::GMT6
:
625 case wxDateTime::GMT7
:
626 case wxDateTime::GMT8
:
627 case wxDateTime::GMT9
:
628 case wxDateTime::GMT10
:
629 case wxDateTime::GMT11
:
630 case wxDateTime::GMT12
:
631 case wxDateTime::GMT13
:
632 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
635 case wxDateTime::A_CST
:
636 // Central Standard Time in use in Australia = UTC + 9.5
637 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
641 wxFAIL_MSG( wxT("unknown time zone") );
645 // ----------------------------------------------------------------------------
647 // ----------------------------------------------------------------------------
650 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
652 time_t t
= GetTimeNow();
653 return wxLocaltime_r(&t
, tmstruct
);
657 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
659 if ( year
== Inv_Year
)
660 year
= GetCurrentYear();
662 if ( cal
== Gregorian
)
664 // in Gregorian calendar leap years are those divisible by 4 except
665 // those divisible by 100 unless they're also divisible by 400
666 // (in some countries, like Russia and Greece, additional corrections
667 // exist, but they won't manifest themselves until 2700)
668 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
670 else if ( cal
== Julian
)
672 // in Julian calendar the rule is simpler
673 return year
% 4 == 0;
677 wxFAIL_MSG(wxT("unknown calendar"));
684 int wxDateTime::GetCentury(int year
)
686 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
690 int wxDateTime::ConvertYearToBC(int year
)
693 return year
> 0 ? year
: year
- 1;
697 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
702 return Now().GetYear();
705 wxFAIL_MSG(wxT("TODO"));
709 wxFAIL_MSG(wxT("unsupported calendar"));
717 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
722 return Now().GetMonth();
725 wxFAIL_MSG(wxT("TODO"));
729 wxFAIL_MSG(wxT("unsupported calendar"));
737 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
739 if ( year
== Inv_Year
)
741 // take the current year if none given
742 year
= GetCurrentYear();
749 return IsLeapYear(year
) ? 366 : 365;
752 wxFAIL_MSG(wxT("unsupported calendar"));
760 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
762 wxDateTime::Calendar cal
)
764 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
766 if ( cal
== Gregorian
|| cal
== Julian
)
768 if ( year
== Inv_Year
)
770 // take the current year if none given
771 year
= GetCurrentYear();
774 return GetNumOfDaysInMonth(year
, month
);
778 wxFAIL_MSG(wxT("unsupported calendar"));
787 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
788 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
789 // asserts in this case)
791 // the return value of this function is used as an index into 2D array
792 // containing full names in its first row and abbreviated ones in the 2nd one
793 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
797 case wxDateTime::Name_Full
:
800 case wxDateTime::Name_Abbr
:
804 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
810 } // anonymous namespace
813 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
815 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
817 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
819 { "January", "February", "March", "April", "May", "June",
820 "July", "August", "September", "October", "November", "December" },
821 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
822 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
825 const int idx
= NameArrayIndexFromFlag(flags
);
829 return monthNames
[idx
][month
];
833 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
834 wxDateTime::NameFlags flags
)
836 #ifdef wxHAS_STRFTIME
837 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
839 // notice that we must set all the fields to avoid confusing libc (GNU one
840 // gets confused to a crash if we don't do this)
845 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
846 #else // !wxHAS_STRFTIME
847 return GetEnglishMonthName(month
, flags
);
848 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
852 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
854 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
856 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
858 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
860 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
863 const int idx
= NameArrayIndexFromFlag(flags
);
867 return weekdayNames
[idx
][wday
];
871 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
872 wxDateTime::NameFlags flags
)
874 #ifdef wxHAS_STRFTIME
875 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
877 // take some arbitrary Sunday (but notice that the day should be such that
878 // after adding wday to it below we still have a valid date, e.g. don't
886 // and offset it by the number of days needed to get the correct wday
889 // call mktime() to normalize it...
892 // ... and call strftime()
893 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
894 #else // !wxHAS_STRFTIME
895 return GetEnglishWeekDayName(wday
, flags
);
896 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
900 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
905 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
906 // and causes an assertion failed if the buffer is to small (which is good) - OR -
907 // if strftime does not return anything because the format string is invalid - OR -
908 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
909 // wxDateTime::ParseTime will try several different formats to parse the time.
910 // As a result, GetAmPmStrings might get called, even if the current locale
911 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
912 // assert, even though it is a perfectly legal use.
915 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
916 *am
= wxString(buffer
);
923 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
924 *pm
= wxString(buffer
);
931 // ----------------------------------------------------------------------------
932 // Country stuff: date calculations depend on the country (DST, work days,
933 // ...), so we need to know which rules to follow.
934 // ----------------------------------------------------------------------------
937 wxDateTime::Country
wxDateTime::GetCountry()
939 // TODO use LOCALE_ICOUNTRY setting under Win32
941 if ( ms_country
== Country_Unknown
)
943 // try to guess from the time zone name
944 time_t t
= time(NULL
);
946 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
948 wxString tz
= CallStrftime(wxT("%Z"), tm
);
949 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
953 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
955 ms_country
= Country_EEC
;
957 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
961 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
962 tz
== wxT("EST") || tz
== wxT("EDT") ||
963 tz
== wxT("CST") || tz
== wxT("CDT") ||
964 tz
== wxT("MST") || tz
== wxT("MDT") ||
965 tz
== wxT("PST") || tz
== wxT("PDT") )
971 // well, choose a default one
977 #endif // !__WXWINCE__/__WXWINCE__
983 void wxDateTime::SetCountry(wxDateTime::Country country
)
985 ms_country
= country
;
989 bool wxDateTime::IsWestEuropeanCountry(Country country
)
991 if ( country
== Country_Default
)
993 country
= GetCountry();
996 return (Country_WesternEurope_Start
<= country
) &&
997 (country
<= Country_WesternEurope_End
);
1000 // ----------------------------------------------------------------------------
1001 // DST calculations: we use 3 different rules for the West European countries,
1002 // USA and for the rest of the world. This is undoubtedly false for many
1003 // countries, but I lack the necessary info (and the time to gather it),
1004 // please add the other rules here!
1005 // ----------------------------------------------------------------------------
1008 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1010 if ( year
== Inv_Year
)
1012 // take the current year if none given
1013 year
= GetCurrentYear();
1016 if ( country
== Country_Default
)
1018 country
= GetCountry();
1025 // DST was first observed in the US and UK during WWI, reused
1026 // during WWII and used again since 1966
1027 return year
>= 1966 ||
1028 (year
>= 1942 && year
<= 1945) ||
1029 (year
== 1918 || year
== 1919);
1032 // assume that it started after WWII
1038 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1040 if ( year
== Inv_Year
)
1042 // take the current year if none given
1043 year
= GetCurrentYear();
1046 if ( country
== Country_Default
)
1048 country
= GetCountry();
1051 if ( !IsDSTApplicable(year
, country
) )
1053 return wxInvalidDateTime
;
1058 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1060 // DST begins at 1 a.m. GMT on the last Sunday of March
1061 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1064 wxFAIL_MSG( wxT("no last Sunday in March?") );
1067 dt
+= wxTimeSpan::Hours(1);
1069 else switch ( country
)
1076 // don't know for sure - assume it was in effect all year
1081 dt
.Set(1, Jan
, year
);
1085 // DST was installed Feb 2, 1942 by the Congress
1086 dt
.Set(2, Feb
, year
);
1089 // Oil embargo changed the DST period in the US
1091 dt
.Set(6, Jan
, 1974);
1095 dt
.Set(23, Feb
, 1975);
1099 // before 1986, DST begun on the last Sunday of April, but
1100 // in 1986 Reagan changed it to begin at 2 a.m. of the
1101 // first Sunday in April
1104 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1107 wxFAIL_MSG( wxT("no first Sunday in April?") );
1110 else if ( year
> 2006 )
1111 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1112 // Starting in 2007, daylight time begins in the United States on the
1113 // second Sunday in March and ends on the first Sunday in November
1115 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1118 wxFAIL_MSG( wxT("no second Sunday in March?") );
1123 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1126 wxFAIL_MSG( wxT("no first Sunday in April?") );
1130 dt
+= wxTimeSpan::Hours(2);
1132 // TODO what about timezone??
1138 // assume Mar 30 as the start of the DST for the rest of the world
1139 // - totally bogus, of course
1140 dt
.Set(30, Mar
, year
);
1147 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1149 if ( year
== Inv_Year
)
1151 // take the current year if none given
1152 year
= GetCurrentYear();
1155 if ( country
== Country_Default
)
1157 country
= GetCountry();
1160 if ( !IsDSTApplicable(year
, country
) )
1162 return wxInvalidDateTime
;
1167 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1169 // DST ends at 1 a.m. GMT on the last Sunday of October
1170 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1172 // weirder and weirder...
1173 wxFAIL_MSG( wxT("no last Sunday in October?") );
1176 dt
+= wxTimeSpan::Hours(1);
1178 else switch ( country
)
1185 // don't know for sure - assume it was in effect all year
1189 dt
.Set(31, Dec
, year
);
1193 // the time was reset after the end of the WWII
1194 dt
.Set(30, Sep
, year
);
1197 default: // default for switch (year)
1199 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1200 // Starting in 2007, daylight time begins in the United States on the
1201 // second Sunday in March and ends on the first Sunday in November
1203 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1206 wxFAIL_MSG( wxT("no first Sunday in November?") );
1211 // DST ends at 2 a.m. on the last Sunday of October
1213 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1215 // weirder and weirder...
1216 wxFAIL_MSG( wxT("no last Sunday in October?") );
1220 dt
+= wxTimeSpan::Hours(2);
1222 // TODO: what about timezone??
1226 default: // default for switch (country)
1227 // assume October 26th as the end of the DST - totally bogus too
1228 dt
.Set(26, Oct
, year
);
1234 // ----------------------------------------------------------------------------
1235 // constructors and assignment operators
1236 // ----------------------------------------------------------------------------
1238 // return the current time with ms precision
1239 /* static */ wxDateTime
wxDateTime::UNow()
1241 return wxDateTime(wxGetLocalTimeMillis());
1244 // the values in the tm structure contain the local time
1245 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1248 time_t timet
= mktime(&tm2
);
1250 if ( timet
== (time_t)-1 )
1252 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1253 // less than timezone - try to make it work for this case
1254 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1256 return Set((time_t)(
1258 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1259 tm2
.tm_min
* SEC_PER_MIN
+
1263 wxFAIL_MSG( wxT("mktime() failed") );
1265 *this = wxInvalidDateTime
;
1275 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1276 wxDateTime_t minute
,
1277 wxDateTime_t second
,
1278 wxDateTime_t millisec
)
1280 // we allow seconds to be 61 to account for the leap seconds, even if we
1281 // don't use them really
1282 wxDATETIME_CHECK( hour
< 24 &&
1286 wxT("Invalid time in wxDateTime::Set()") );
1288 // get the current date from system
1290 struct tm
*tm
= GetTmNow(&tmstruct
);
1292 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1294 // make a copy so it isn't clobbered by the call to mktime() below
1299 tm1
.tm_min
= minute
;
1300 tm1
.tm_sec
= second
;
1302 // and the DST in case it changes on this date
1305 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1306 tm1
.tm_isdst
= tm2
.tm_isdst
;
1310 // and finally adjust milliseconds
1311 return SetMillisecond(millisec
);
1314 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1318 wxDateTime_t minute
,
1319 wxDateTime_t second
,
1320 wxDateTime_t millisec
)
1322 wxDATETIME_CHECK( hour
< 24 &&
1326 wxT("Invalid time in wxDateTime::Set()") );
1328 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1330 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1331 wxT("Invalid date in wxDateTime::Set()") );
1333 // the range of time_t type (inclusive)
1334 static const int yearMinInRange
= 1970;
1335 static const int yearMaxInRange
= 2037;
1337 // test only the year instead of testing for the exact end of the Unix
1338 // time_t range - it doesn't bring anything to do more precise checks
1339 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1341 // use the standard library version if the date is in range - this is
1342 // probably more efficient than our code
1344 tm
.tm_year
= year
- 1900;
1350 tm
.tm_isdst
= -1; // mktime() will guess it
1354 // and finally adjust milliseconds
1356 SetMillisecond(millisec
);
1362 // do time calculations ourselves: we want to calculate the number of
1363 // milliseconds between the given date and the epoch
1365 // get the JDN for the midnight of this day
1366 m_time
= GetTruncatedJDN(day
, month
, year
);
1367 m_time
-= EPOCH_JDN
;
1368 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1370 // JDN corresponds to GMT, we take localtime
1371 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1377 wxDateTime
& wxDateTime::Set(double jdn
)
1379 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1381 jdn
-= EPOCH_JDN
+ 0.5;
1383 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1385 // JDNs always are in UTC, so we don't need any adjustments for time zone
1390 wxDateTime
& wxDateTime::ResetTime()
1394 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1407 wxDateTime
wxDateTime::GetDateOnly() const
1414 return wxDateTime(tm
);
1417 // ----------------------------------------------------------------------------
1418 // DOS Date and Time Format functions
1419 // ----------------------------------------------------------------------------
1420 // the dos date and time value is an unsigned 32 bit value in the format:
1421 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1423 // Y = year offset from 1980 (0-127)
1425 // D = day of month (1-31)
1427 // m = minute (0-59)
1428 // s = bisecond (0-29) each bisecond indicates two seconds
1429 // ----------------------------------------------------------------------------
1431 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1436 long year
= ddt
& 0xFE000000;
1441 long month
= ddt
& 0x1E00000;
1446 long day
= ddt
& 0x1F0000;
1450 long hour
= ddt
& 0xF800;
1454 long minute
= ddt
& 0x7E0;
1458 long second
= ddt
& 0x1F;
1459 tm
.tm_sec
= second
* 2;
1461 return Set(mktime(&tm
));
1464 unsigned long wxDateTime::GetAsDOS() const
1467 time_t ticks
= GetTicks();
1469 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1470 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1472 long year
= tm
->tm_year
;
1476 long month
= tm
->tm_mon
;
1480 long day
= tm
->tm_mday
;
1483 long hour
= tm
->tm_hour
;
1486 long minute
= tm
->tm_min
;
1489 long second
= tm
->tm_sec
;
1492 ddt
= year
| month
| day
| hour
| minute
| second
;
1496 // ----------------------------------------------------------------------------
1497 // time_t <-> broken down time conversions
1498 // ----------------------------------------------------------------------------
1500 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1502 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1504 time_t time
= GetTicks();
1505 if ( time
!= (time_t)-1 )
1507 // use C RTL functions
1510 if ( tz
.GetOffset() == -GetTimeZone() )
1512 // we are working with local time
1513 tm
= wxLocaltime_r(&time
, &tmstruct
);
1515 // should never happen
1516 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1520 time
+= (time_t)tz
.GetOffset();
1521 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1522 int time2
= (int) time
;
1528 tm
= wxGmtime_r(&time
, &tmstruct
);
1530 // should never happen
1531 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1535 tm
= (struct tm
*)NULL
;
1541 // adjust the milliseconds
1543 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1544 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1547 //else: use generic code below
1550 // remember the time and do the calculations with the date only - this
1551 // eliminates rounding errors of the floating point arithmetics
1553 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1555 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1557 // we want to always have positive time and timeMidnight to be really
1558 // the midnight before it
1561 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1564 timeMidnight
-= timeOnly
;
1566 // calculate the Gregorian date from JDN for the midnight of our date:
1567 // this will yield day, month (in 1..12 range) and year
1569 // actually, this is the JDN for the noon of the previous day
1570 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1572 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1574 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1576 // calculate the century
1577 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1578 long century
= temp
/ DAYS_PER_400_YEARS
;
1580 // then the year and day of year (1 <= dayOfYear <= 366)
1581 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1582 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1583 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1585 // and finally the month and day of the month
1586 temp
= dayOfYear
* 5 - 3;
1587 long month
= temp
/ DAYS_PER_5_MONTHS
;
1588 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1590 // month is counted from March - convert to normal
1601 // year is offset by 4800
1604 // check that the algorithm gave us something reasonable
1605 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1606 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1608 // construct Tm from these values
1610 tm
.year
= (int)year
;
1611 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1612 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1613 tm
.mday
= (wxDateTime_t
)day
;
1614 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1615 timeOnly
-= tm
.msec
;
1616 timeOnly
/= 1000; // now we have time in seconds
1618 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1620 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1622 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1625 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1630 wxDateTime
& wxDateTime::SetYear(int year
)
1632 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1641 wxDateTime
& wxDateTime::SetMonth(Month month
)
1643 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1652 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1654 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1663 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1665 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1674 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1676 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1685 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1687 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1696 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1698 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1700 // we don't need to use GetTm() for this one
1701 m_time
-= m_time
% 1000l;
1702 m_time
+= millisecond
;
1707 // ----------------------------------------------------------------------------
1708 // wxDateTime arithmetics
1709 // ----------------------------------------------------------------------------
1711 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1715 tm
.year
+= diff
.GetYears();
1716 tm
.AddMonths(diff
.GetMonths());
1718 // check that the resulting date is valid
1719 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1721 // We suppose that when adding one month to Jan 31 we want to get Feb
1722 // 28 (or 29), i.e. adding a month to the last day of the month should
1723 // give the last day of the next month which is quite logical.
1725 // Unfortunately, there is no logic way to understand what should
1726 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1727 // We make it Feb 28 (last day too), but it is highly questionable.
1728 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1731 tm
.AddDays(diff
.GetTotalDays());
1735 wxASSERT_MSG( IsSameTime(tm
),
1736 wxT("Add(wxDateSpan) shouldn't modify time") );
1741 // ----------------------------------------------------------------------------
1742 // Weekday and monthday stuff
1743 // ----------------------------------------------------------------------------
1745 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1746 static inline int ConvertWeekDayToMondayBase(int wd
)
1748 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1753 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1755 wxASSERT_MSG( numWeek
> 0,
1756 wxT("invalid week number: weeks are counted from 1") );
1758 // Jan 4 always lies in the 1st week of the year
1759 wxDateTime
dt(4, Jan
, year
);
1760 dt
.SetToWeekDayInSameWeek(wd
);
1761 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1766 #if WXWIN_COMPATIBILITY_2_6
1767 // use a separate function to avoid warnings about using deprecated
1768 // SetToTheWeek in GetWeek below
1770 SetToTheWeek(int year
,
1771 wxDateTime::wxDateTime_t numWeek
,
1772 wxDateTime::WeekDay weekday
,
1773 wxDateTime::WeekFlags flags
)
1775 // Jan 4 always lies in the 1st week of the year
1776 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1777 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1778 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1783 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1787 int year
= GetYear();
1788 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1789 if ( GetYear() != year
)
1791 // oops... numWeek was too big
1798 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1800 WeekFlags flags
) const
1802 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1804 #endif // WXWIN_COMPATIBILITY_2_6
1806 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1809 // take the current month/year if none specified
1810 if ( year
== Inv_Year
)
1812 if ( month
== Inv_Month
)
1815 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1818 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1820 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1822 int wdayDst
= weekday
,
1823 wdayThis
= GetWeekDay();
1824 if ( wdayDst
== wdayThis
)
1830 if ( flags
== Default_First
)
1832 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1835 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1836 // is the first day in the week, but breaks down for Monday_First case so
1837 // we adjust the week days in this case
1838 if ( flags
== Monday_First
)
1840 if ( wdayThis
== Sun
)
1842 if ( wdayDst
== Sun
)
1845 //else: Sunday_First, nothing to do
1847 // go forward or back in time to the day we want
1848 if ( wdayDst
< wdayThis
)
1850 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1852 else // weekday > wdayThis
1854 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1858 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1860 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1863 WeekDay wdayThis
= GetWeekDay();
1864 if ( weekday
== wdayThis
)
1869 else if ( weekday
< wdayThis
)
1871 // need to advance a week
1872 diff
= 7 - (wdayThis
- weekday
);
1874 else // weekday > wdayThis
1876 diff
= weekday
- wdayThis
;
1879 return Add(wxDateSpan::Days(diff
));
1882 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1884 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1887 WeekDay wdayThis
= GetWeekDay();
1888 if ( weekday
== wdayThis
)
1893 else if ( weekday
> wdayThis
)
1895 // need to go to previous week
1896 diff
= 7 - (weekday
- wdayThis
);
1898 else // weekday < wdayThis
1900 diff
= wdayThis
- weekday
;
1903 return Subtract(wxDateSpan::Days(diff
));
1906 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1911 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1913 // we don't check explicitly that -5 <= n <= 5 because we will return false
1914 // anyhow in such case - but may be should still give an assert for it?
1916 // take the current month/year if none specified
1917 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1921 // TODO this probably could be optimised somehow...
1925 // get the first day of the month
1926 dt
.Set(1, month
, year
);
1929 WeekDay wdayFirst
= dt
.GetWeekDay();
1931 // go to the first weekday of the month
1932 int diff
= weekday
- wdayFirst
;
1936 // add advance n-1 weeks more
1939 dt
+= wxDateSpan::Days(diff
);
1941 else // count from the end of the month
1943 // get the last day of the month
1944 dt
.SetToLastMonthDay(month
, year
);
1947 WeekDay wdayLast
= dt
.GetWeekDay();
1949 // go to the last weekday of the month
1950 int diff
= wdayLast
- weekday
;
1954 // and rewind n-1 weeks from there
1957 dt
-= wxDateSpan::Days(diff
);
1960 // check that it is still in the same month
1961 if ( dt
.GetMonth() == month
)
1969 // no such day in this month
1975 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1977 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1980 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1982 return GetDayOfYearFromTm(GetTm(tz
));
1985 wxDateTime::wxDateTime_t
1986 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1988 if ( flags
== Default_First
)
1990 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1994 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1996 int wdTarget
= GetWeekDay(tz
);
1997 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1999 if ( flags
== Sunday_First
)
2001 // FIXME: First week is not calculated correctly.
2002 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2003 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2006 else // week starts with monday
2008 // adjust the weekdays to non-US style.
2009 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2010 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2012 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2014 // Week 01 of a year is per definition the first week that has the
2015 // Thursday in this year, which is equivalent to the week that
2016 // contains the fourth day of January. In other words, the first
2017 // week of a new year is the week that has the majority of its
2018 // days in the new year. Week 01 might also contain days from the
2019 // previous year and the week before week 01 of a year is the last
2020 // week (52 or 53) of the previous year even if it contains days
2021 // from the new year. A week starts with Monday (day 1) and ends
2022 // with Sunday (day 7).
2025 // if Jan 1 is Thursday or less, it is in the first week of this year
2026 if ( wdYearStart
< 4 )
2028 // count the number of entire weeks between Jan 1 and this date
2029 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2031 // be careful to check for overflow in the next year
2032 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2035 else // Jan 1 is in the last week of the previous year
2037 // check if we happen to be at the last week of previous year:
2038 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2039 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2041 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2045 return (wxDateTime::wxDateTime_t
)week
;
2048 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2049 const TimeZone
& tz
) const
2052 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
2053 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
2055 if ( flags
== Default_First
)
2057 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2060 // compute offset of dateFirst from the beginning of the week
2062 if ( flags
== Sunday_First
)
2063 firstOffset
= wdFirst
- Sun
;
2065 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
2067 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
2070 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2072 int year
= GetYear();
2073 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2074 wxT("invalid year day") );
2076 bool isLeap
= IsLeapYear(year
);
2077 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2079 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2080 // don't need it neither - because of the CHECK above we know that
2081 // yday lies in December then
2082 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2084 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2093 // ----------------------------------------------------------------------------
2094 // Julian day number conversion and related stuff
2095 // ----------------------------------------------------------------------------
2097 double wxDateTime::GetJulianDayNumber() const
2099 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2102 double wxDateTime::GetRataDie() const
2104 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2105 return GetJulianDayNumber() - 1721119.5 - 306;
2108 // ----------------------------------------------------------------------------
2109 // timezone and DST stuff
2110 // ----------------------------------------------------------------------------
2112 int wxDateTime::IsDST(wxDateTime::Country country
) const
2114 wxCHECK_MSG( country
== Country_Default
, -1,
2115 wxT("country support not implemented") );
2117 // use the C RTL for the dates in the standard range
2118 time_t timet
= GetTicks();
2119 if ( timet
!= (time_t)-1 )
2122 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2124 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2126 return tm
->tm_isdst
;
2130 int year
= GetYear();
2132 if ( !IsDSTApplicable(year
, country
) )
2134 // no DST time in this year in this country
2138 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2142 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2144 long secDiff
= GetTimeZone() + tz
.GetOffset();
2146 // we need to know whether DST is or not in effect for this date unless
2147 // the test disabled by the caller
2148 if ( !noDST
&& (IsDST() == 1) )
2150 // FIXME we assume that the DST is always shifted by 1 hour
2154 return Add(wxTimeSpan::Seconds(secDiff
));
2157 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2159 long secDiff
= GetTimeZone() + tz
.GetOffset();
2161 // we need to know whether DST is or not in effect for this date unless
2162 // the test disabled by the caller
2163 if ( !noDST
&& (IsDST() == 1) )
2165 // FIXME we assume that the DST is always shifted by 1 hour
2169 return Subtract(wxTimeSpan::Seconds(secDiff
));
2172 // ============================================================================
2173 // wxDateTimeHolidayAuthority and related classes
2174 // ============================================================================
2176 #include "wx/arrimpl.cpp"
2178 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2180 static int wxCMPFUNC_CONV
2181 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2183 wxDateTime dt1
= **first
,
2186 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2189 // ----------------------------------------------------------------------------
2190 // wxDateTimeHolidayAuthority
2191 // ----------------------------------------------------------------------------
2193 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2196 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2198 size_t count
= ms_authorities
.size();
2199 for ( size_t n
= 0; n
< count
; n
++ )
2201 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2212 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2213 const wxDateTime
& dtEnd
,
2214 wxDateTimeArray
& holidays
)
2216 wxDateTimeArray hol
;
2220 const size_t countAuth
= ms_authorities
.size();
2221 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2223 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2225 WX_APPEND_ARRAY(holidays
, hol
);
2228 holidays
.Sort(wxDateTimeCompareFunc
);
2230 return holidays
.size();
2234 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2236 WX_CLEAR_ARRAY(ms_authorities
);
2240 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2242 ms_authorities
.push_back(auth
);
2245 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2247 // required here for Darwin
2250 // ----------------------------------------------------------------------------
2251 // wxDateTimeWorkDays
2252 // ----------------------------------------------------------------------------
2254 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2256 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2258 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2261 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2262 const wxDateTime
& dtEnd
,
2263 wxDateTimeArray
& holidays
) const
2265 if ( dtStart
> dtEnd
)
2267 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2274 // instead of checking all days, start with the first Sat after dtStart and
2275 // end with the last Sun before dtEnd
2276 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2277 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2278 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2279 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2282 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2287 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2292 return holidays
.GetCount();
2295 // ============================================================================
2296 // other helper functions
2297 // ============================================================================
2299 // ----------------------------------------------------------------------------
2300 // iteration helpers: can be used to write a for loop over enum variable like
2302 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2303 // ----------------------------------------------------------------------------
2305 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2307 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2309 // no wrapping or the for loop above would never end!
2310 m
= (wxDateTime::Month
)(m
+ 1);
2313 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2315 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2317 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2318 : (wxDateTime::Month
)(m
- 1);
2321 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2323 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2325 // no wrapping or the for loop above would never end!
2326 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2329 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2331 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2333 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2334 : (wxDateTime::WeekDay
)(wd
- 1);
2339 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2342 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2344 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2347 wxDateTime
& wxDateTime::SetFromMSWSysDate(const SYSTEMTIME
& st
)
2350 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2355 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2357 const wxDateTime::Tm
tm(GetTm());
2359 st
->wYear
= (WXWORD
)tm
.year
;
2360 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2364 st
->wHour
= tm
.hour
;
2365 st
->wMinute
= tm
.min
;
2366 st
->wSecond
= tm
.sec
;
2367 st
->wMilliseconds
= tm
.msec
;
2370 void wxDateTime::GetAsMSWSysDate(SYSTEMTIME
* st
) const
2372 const wxDateTime::Tm
tm(GetTm());
2374 st
->wYear
= (WXWORD
)tm
.year
;
2375 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2382 st
->wMilliseconds
= 0;
2387 #endif // wxUSE_DATETIME