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()
149 #define WX_TIMEZONE wxGetTimeZone()
150 #else // unknown platform - try timezone
151 #define WX_TIMEZONE timezone
153 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
155 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
156 #if defined(__WXWINCE__) && defined(__VISUALC8__)
158 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
161 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
164 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
167 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
170 #else // !wxWinCE with VC8
172 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
173 static wxMutex timeLock
;
176 #ifndef HAVE_LOCALTIME_R
177 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
179 #if wxUSE_THREADS && !defined(__WINDOWS__)
180 // No need to waste time with a mutex on windows since it's using
181 // thread local storage for localtime anyway.
182 wxMutexLocker
locker(timeLock
);
185 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
191 const tm
* const t
= localtime(ticks
);
195 memcpy(temp
, t
, sizeof(struct tm
));
198 #endif // !HAVE_LOCALTIME_R
200 #ifndef HAVE_GMTIME_R
201 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
203 #if wxUSE_THREADS && !defined(__WINDOWS__)
204 // No need to waste time with a mutex on windows since it's
205 // using thread local storage for gmtime anyway.
206 wxMutexLocker
locker(timeLock
);
214 const tm
* const t
= gmtime(ticks
);
218 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
221 #endif // !HAVE_GMTIME_R
223 #endif // wxWinCE with VC8/other platforms
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 // debugging helper: just a convenient replacement of wxCHECK()
230 #define wxDATETIME_CHECK(expr, msg) \
231 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
233 // ----------------------------------------------------------------------------
235 // ----------------------------------------------------------------------------
237 class wxDateTimeHolidaysModule
: public wxModule
240 virtual bool OnInit()
242 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
247 virtual void OnExit()
249 wxDateTimeHolidayAuthority::ClearAllAuthorities();
250 wxDateTimeHolidayAuthority::ms_authorities
.clear();
254 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
257 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
264 static const int MONTHS_IN_YEAR
= 12;
266 static const int SEC_PER_MIN
= 60;
268 static const int MIN_PER_HOUR
= 60;
270 static const long SECONDS_PER_DAY
= 86400l;
272 static const int DAYS_PER_WEEK
= 7;
274 static const long MILLISECONDS_PER_DAY
= 86400000l;
276 // this is the integral part of JDN of the midnight of Jan 1, 1970
277 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
278 static const long EPOCH_JDN
= 2440587l;
280 // these values are only used in asserts so don't define them if asserts are
281 // disabled to avoid warnings about unused static variables
283 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
284 // reference date for us) is Nov 24, 4714BC
285 static const int JDN_0_YEAR
= -4713;
286 static const int JDN_0_MONTH
= wxDateTime::Nov
;
287 static const int JDN_0_DAY
= 24;
288 #endif // wxDEBUG_LEVEL
290 // the constants used for JDN calculations
291 static const long JDN_OFFSET
= 32046l;
292 static const long DAYS_PER_5_MONTHS
= 153l;
293 static const long DAYS_PER_4_YEARS
= 1461l;
294 static const long DAYS_PER_400_YEARS
= 146097l;
296 // this array contains the cumulated number of days in all previous months for
297 // normal and leap years
298 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
300 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
301 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
304 const long wxDateTime::TIME_T_FACTOR
= 1000l;
306 // ----------------------------------------------------------------------------
308 // ----------------------------------------------------------------------------
310 const char wxDefaultDateTimeFormat
[] = "%c";
311 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
313 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
314 // indicate an invalid wxDateTime object
315 const wxDateTime wxDefaultDateTime
;
317 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
319 // ----------------------------------------------------------------------------
321 // ----------------------------------------------------------------------------
323 // debugger helper: this function can be called from a debugger to show what
324 // the date really is
325 extern const char *wxDumpDate(const wxDateTime
* dt
)
327 static char buf
[128];
329 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
331 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
337 // get the number of days in the given month of the given year
339 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
341 // the number of days in month in Julian/Gregorian calendar: the first line
342 // is for normal years, the second one is for the leap ones
343 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
345 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
346 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
349 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
352 // returns the time zone in the C sense, i.e. the difference UTC - local
354 // NOTE: not static because used by datetimefmt.cpp
357 #ifdef WX_GMTOFF_IN_TM
358 // set to true when the timezone is set
359 static bool s_timezoneSet
= false;
360 static long gmtoffset
= LONG_MAX
; // invalid timezone
362 // ensure that the timezone variable is set by calling wxLocaltime_r
363 if ( !s_timezoneSet
)
365 // just call wxLocaltime_r() instead of figuring out whether this
366 // system supports tzset(), _tzset() or something else
370 wxLocaltime_r(&t
, &tm
);
371 s_timezoneSet
= true;
373 // note that GMT offset is the opposite of time zone and so to return
374 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
375 // cases we have to negate it
376 gmtoffset
= -tm
.tm_gmtoff
;
378 return (int)gmtoffset
;
379 #else // !WX_GMTOFF_IN_TM
381 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
384 // return the integral part of the JDN for the midnight of the given date (to
385 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
386 // noon of the previous day)
387 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
388 wxDateTime::Month mon
,
391 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
393 // check the date validity
395 (year
> JDN_0_YEAR
) ||
396 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
397 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
398 wxT("date out of range - can't convert to JDN")
401 // make the year positive to avoid problems with negative numbers division
404 // months are counted from March here
406 if ( mon
>= wxDateTime::Mar
)
416 // now we can simply add all the contributions together
417 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
418 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
419 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
424 #ifdef wxHAS_STRFTIME
426 // this function is a wrapper around strftime(3) adding error checking
427 // NOTE: not static because used by datetimefmt.cpp
428 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
431 // Create temp wxString here to work around mingw/cygwin bug 1046059
432 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
435 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
437 // if the format is valid, buffer must be too small?
438 wxFAIL_MSG(wxT("strftime() failed"));
447 #endif // wxHAS_STRFTIME
449 // if year and/or month have invalid values, replace them with the current ones
450 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
451 wxDateTime::Month
*month
)
453 struct tm
*tmNow
= NULL
;
456 if ( *year
== wxDateTime::Inv_Year
)
458 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
460 *year
= 1900 + tmNow
->tm_year
;
463 if ( *month
== wxDateTime::Inv_Month
)
466 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
468 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
472 // fill the struct tm with default values
473 // NOTE: not static because used by datetimefmt.cpp
474 void InitTm(struct tm
& tm
)
476 // struct tm may have etxra fields (undocumented and with unportable
477 // names) which, nevertheless, must be set to 0
478 memset(&tm
, 0, sizeof(struct tm
));
480 tm
.tm_mday
= 1; // mday 0 is invalid
481 tm
.tm_year
= 76; // any valid year
482 tm
.tm_isdst
= -1; // auto determine
485 // ============================================================================
486 // implementation of wxDateTime
487 // ============================================================================
489 // ----------------------------------------------------------------------------
491 // ----------------------------------------------------------------------------
495 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
496 mon
= wxDateTime::Inv_Month
;
503 wday
= wxDateTime::Inv_WeekDay
;
506 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
510 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
511 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
512 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
513 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
514 mon
= (wxDateTime::Month
)tm
.tm_mon
;
515 year
= 1900 + tm
.tm_year
;
516 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
517 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
520 bool wxDateTime::Tm::IsValid() const
522 // we allow for the leap seconds, although we don't use them (yet)
523 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
524 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
525 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
528 void wxDateTime::Tm::ComputeWeekDay()
530 // compute the week day from day/month/year: we use the dumbest algorithm
531 // possible: just compute our JDN and then use the (simple to derive)
532 // formula: weekday = (JDN + 1.5) % 7
533 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
536 void wxDateTime::Tm::AddMonths(int monDiff
)
538 // normalize the months field
539 while ( monDiff
< -mon
)
543 monDiff
+= MONTHS_IN_YEAR
;
546 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
550 monDiff
-= MONTHS_IN_YEAR
;
553 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
555 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
557 // NB: we don't check here that the resulting date is valid, this function
558 // is private and the caller must check it if needed
561 void wxDateTime::Tm::AddDays(int dayDiff
)
563 // normalize the days field
564 while ( dayDiff
+ mday
< 1 )
568 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
571 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
572 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
574 mday
-= GetNumOfDaysInMonth(year
, mon
);
579 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
580 wxT("logic error") );
583 // ----------------------------------------------------------------------------
585 // ----------------------------------------------------------------------------
587 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
591 case wxDateTime::Local
:
592 // get the offset from C RTL: it returns the difference GMT-local
593 // while we want to have the offset _from_ GMT, hence the '-'
594 m_offset
= -GetTimeZone();
597 case wxDateTime::GMT_12
:
598 case wxDateTime::GMT_11
:
599 case wxDateTime::GMT_10
:
600 case wxDateTime::GMT_9
:
601 case wxDateTime::GMT_8
:
602 case wxDateTime::GMT_7
:
603 case wxDateTime::GMT_6
:
604 case wxDateTime::GMT_5
:
605 case wxDateTime::GMT_4
:
606 case wxDateTime::GMT_3
:
607 case wxDateTime::GMT_2
:
608 case wxDateTime::GMT_1
:
609 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
612 case wxDateTime::GMT0
:
613 case wxDateTime::GMT1
:
614 case wxDateTime::GMT2
:
615 case wxDateTime::GMT3
:
616 case wxDateTime::GMT4
:
617 case wxDateTime::GMT5
:
618 case wxDateTime::GMT6
:
619 case wxDateTime::GMT7
:
620 case wxDateTime::GMT8
:
621 case wxDateTime::GMT9
:
622 case wxDateTime::GMT10
:
623 case wxDateTime::GMT11
:
624 case wxDateTime::GMT12
:
625 case wxDateTime::GMT13
:
626 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
629 case wxDateTime::A_CST
:
630 // Central Standard Time in use in Australia = UTC + 9.5
631 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
635 wxFAIL_MSG( wxT("unknown time zone") );
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
644 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
646 time_t t
= GetTimeNow();
647 return wxLocaltime_r(&t
, tmstruct
);
651 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
653 if ( year
== Inv_Year
)
654 year
= GetCurrentYear();
656 if ( cal
== Gregorian
)
658 // in Gregorian calendar leap years are those divisible by 4 except
659 // those divisible by 100 unless they're also divisible by 400
660 // (in some countries, like Russia and Greece, additional corrections
661 // exist, but they won't manifest themselves until 2700)
662 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
664 else if ( cal
== Julian
)
666 // in Julian calendar the rule is simpler
667 return year
% 4 == 0;
671 wxFAIL_MSG(wxT("unknown calendar"));
678 int wxDateTime::GetCentury(int year
)
680 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
684 int wxDateTime::ConvertYearToBC(int year
)
687 return year
> 0 ? year
: year
- 1;
691 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
696 return Now().GetYear();
699 wxFAIL_MSG(wxT("TODO"));
703 wxFAIL_MSG(wxT("unsupported calendar"));
711 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
716 return Now().GetMonth();
719 wxFAIL_MSG(wxT("TODO"));
723 wxFAIL_MSG(wxT("unsupported calendar"));
731 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
733 if ( year
== Inv_Year
)
735 // take the current year if none given
736 year
= GetCurrentYear();
743 return IsLeapYear(year
) ? 366 : 365;
746 wxFAIL_MSG(wxT("unsupported calendar"));
754 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
756 wxDateTime::Calendar cal
)
758 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
760 if ( cal
== Gregorian
|| cal
== Julian
)
762 if ( year
== Inv_Year
)
764 // take the current year if none given
765 year
= GetCurrentYear();
768 return GetNumOfDaysInMonth(year
, month
);
772 wxFAIL_MSG(wxT("unsupported calendar"));
781 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
782 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
783 // asserts in this case)
785 // the return value of this function is used as an index into 2D array
786 // containing full names in its first row and abbreviated ones in the 2nd one
787 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
791 case wxDateTime::Name_Full
:
794 case wxDateTime::Name_Abbr
:
798 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
804 } // anonymous namespace
807 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
809 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
811 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
813 { "January", "February", "March", "April", "May", "June",
814 "July", "August", "September", "October", "November", "December" },
815 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
816 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
819 const int idx
= NameArrayIndexFromFlag(flags
);
823 return monthNames
[idx
][month
];
827 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
828 wxDateTime::NameFlags flags
)
830 #ifdef wxHAS_STRFTIME
831 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
833 // notice that we must set all the fields to avoid confusing libc (GNU one
834 // gets confused to a crash if we don't do this)
839 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
840 #else // !wxHAS_STRFTIME
841 return GetEnglishMonthName(month
, flags
);
842 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
846 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
848 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
850 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
852 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
854 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
857 const int idx
= NameArrayIndexFromFlag(flags
);
861 return weekdayNames
[idx
][wday
];
865 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
866 wxDateTime::NameFlags flags
)
868 #ifdef wxHAS_STRFTIME
869 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
871 // take some arbitrary Sunday (but notice that the day should be such that
872 // after adding wday to it below we still have a valid date, e.g. don't
880 // and offset it by the number of days needed to get the correct wday
883 // call mktime() to normalize it...
886 // ... and call strftime()
887 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
888 #else // !wxHAS_STRFTIME
889 return GetEnglishWeekDayName(wday
, flags
);
890 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
894 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
899 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
900 // and causes an assertion failed if the buffer is to small (which is good) - OR -
901 // if strftime does not return anything because the format string is invalid - OR -
902 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
903 // wxDateTime::ParseTime will try several different formats to parse the time.
904 // As a result, GetAmPmStrings might get called, even if the current locale
905 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
906 // assert, even though it is a perfectly legal use.
909 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
910 *am
= wxString(buffer
);
917 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
918 *pm
= wxString(buffer
);
925 // ----------------------------------------------------------------------------
926 // Country stuff: date calculations depend on the country (DST, work days,
927 // ...), so we need to know which rules to follow.
928 // ----------------------------------------------------------------------------
931 wxDateTime::Country
wxDateTime::GetCountry()
933 // TODO use LOCALE_ICOUNTRY setting under Win32
935 if ( ms_country
== Country_Unknown
)
937 // try to guess from the time zone name
938 time_t t
= time(NULL
);
940 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
942 wxString tz
= CallStrftime(wxT("%Z"), tm
);
943 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
947 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
949 ms_country
= Country_EEC
;
951 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
955 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
956 tz
== wxT("EST") || tz
== wxT("EDT") ||
957 tz
== wxT("CST") || tz
== wxT("CDT") ||
958 tz
== wxT("MST") || tz
== wxT("MDT") ||
959 tz
== wxT("PST") || tz
== wxT("PDT") )
965 // well, choose a default one
971 #endif // !__WXWINCE__/__WXWINCE__
977 void wxDateTime::SetCountry(wxDateTime::Country country
)
979 ms_country
= country
;
983 bool wxDateTime::IsWestEuropeanCountry(Country country
)
985 if ( country
== Country_Default
)
987 country
= GetCountry();
990 return (Country_WesternEurope_Start
<= country
) &&
991 (country
<= Country_WesternEurope_End
);
994 // ----------------------------------------------------------------------------
995 // DST calculations: we use 3 different rules for the West European countries,
996 // USA and for the rest of the world. This is undoubtedly false for many
997 // countries, but I lack the necessary info (and the time to gather it),
998 // please add the other rules here!
999 // ----------------------------------------------------------------------------
1002 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1004 if ( year
== Inv_Year
)
1006 // take the current year if none given
1007 year
= GetCurrentYear();
1010 if ( country
== Country_Default
)
1012 country
= GetCountry();
1019 // DST was first observed in the US and UK during WWI, reused
1020 // during WWII and used again since 1966
1021 return year
>= 1966 ||
1022 (year
>= 1942 && year
<= 1945) ||
1023 (year
== 1918 || year
== 1919);
1026 // assume that it started after WWII
1032 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1034 if ( year
== Inv_Year
)
1036 // take the current year if none given
1037 year
= GetCurrentYear();
1040 if ( country
== Country_Default
)
1042 country
= GetCountry();
1045 if ( !IsDSTApplicable(year
, country
) )
1047 return wxInvalidDateTime
;
1052 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1054 // DST begins at 1 a.m. GMT on the last Sunday of March
1055 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1058 wxFAIL_MSG( wxT("no last Sunday in March?") );
1061 dt
+= wxTimeSpan::Hours(1);
1063 else switch ( country
)
1070 // don't know for sure - assume it was in effect all year
1075 dt
.Set(1, Jan
, year
);
1079 // DST was installed Feb 2, 1942 by the Congress
1080 dt
.Set(2, Feb
, year
);
1083 // Oil embargo changed the DST period in the US
1085 dt
.Set(6, Jan
, 1974);
1089 dt
.Set(23, Feb
, 1975);
1093 // before 1986, DST begun on the last Sunday of April, but
1094 // in 1986 Reagan changed it to begin at 2 a.m. of the
1095 // first Sunday in April
1098 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1101 wxFAIL_MSG( wxT("no first Sunday in April?") );
1104 else if ( year
> 2006 )
1105 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1106 // Starting in 2007, daylight time begins in the United States on the
1107 // second Sunday in March and ends on the first Sunday in November
1109 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1112 wxFAIL_MSG( wxT("no second Sunday in March?") );
1117 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1120 wxFAIL_MSG( wxT("no first Sunday in April?") );
1124 dt
+= wxTimeSpan::Hours(2);
1126 // TODO what about timezone??
1132 // assume Mar 30 as the start of the DST for the rest of the world
1133 // - totally bogus, of course
1134 dt
.Set(30, Mar
, year
);
1141 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1143 if ( year
== Inv_Year
)
1145 // take the current year if none given
1146 year
= GetCurrentYear();
1149 if ( country
== Country_Default
)
1151 country
= GetCountry();
1154 if ( !IsDSTApplicable(year
, country
) )
1156 return wxInvalidDateTime
;
1161 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1163 // DST ends at 1 a.m. GMT on the last Sunday of October
1164 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1166 // weirder and weirder...
1167 wxFAIL_MSG( wxT("no last Sunday in October?") );
1170 dt
+= wxTimeSpan::Hours(1);
1172 else switch ( country
)
1179 // don't know for sure - assume it was in effect all year
1183 dt
.Set(31, Dec
, year
);
1187 // the time was reset after the end of the WWII
1188 dt
.Set(30, Sep
, year
);
1191 default: // default for switch (year)
1193 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1194 // Starting in 2007, daylight time begins in the United States on the
1195 // second Sunday in March and ends on the first Sunday in November
1197 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1200 wxFAIL_MSG( wxT("no first Sunday in November?") );
1205 // DST ends at 2 a.m. on the last Sunday of October
1207 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1209 // weirder and weirder...
1210 wxFAIL_MSG( wxT("no last Sunday in October?") );
1214 dt
+= wxTimeSpan::Hours(2);
1216 // TODO: what about timezone??
1220 default: // default for switch (country)
1221 // assume October 26th as the end of the DST - totally bogus too
1222 dt
.Set(26, Oct
, year
);
1228 // ----------------------------------------------------------------------------
1229 // constructors and assignment operators
1230 // ----------------------------------------------------------------------------
1232 // return the current time with ms precision
1233 /* static */ wxDateTime
wxDateTime::UNow()
1235 return wxDateTime(wxGetLocalTimeMillis());
1238 // the values in the tm structure contain the local time
1239 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1242 time_t timet
= mktime(&tm2
);
1244 if ( timet
== (time_t)-1 )
1246 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1247 // less than timezone - try to make it work for this case
1248 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1250 return Set((time_t)(
1252 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1253 tm2
.tm_min
* SEC_PER_MIN
+
1257 wxFAIL_MSG( wxT("mktime() failed") );
1259 *this = wxInvalidDateTime
;
1269 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1270 wxDateTime_t minute
,
1271 wxDateTime_t second
,
1272 wxDateTime_t millisec
)
1274 // we allow seconds to be 61 to account for the leap seconds, even if we
1275 // don't use them really
1276 wxDATETIME_CHECK( hour
< 24 &&
1280 wxT("Invalid time in wxDateTime::Set()") );
1282 // get the current date from system
1284 struct tm
*tm
= GetTmNow(&tmstruct
);
1286 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1288 // make a copy so it isn't clobbered by the call to mktime() below
1293 tm1
.tm_min
= minute
;
1294 tm1
.tm_sec
= second
;
1296 // and the DST in case it changes on this date
1299 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1300 tm1
.tm_isdst
= tm2
.tm_isdst
;
1304 // and finally adjust milliseconds
1305 return SetMillisecond(millisec
);
1308 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1312 wxDateTime_t minute
,
1313 wxDateTime_t second
,
1314 wxDateTime_t millisec
)
1316 wxDATETIME_CHECK( hour
< 24 &&
1320 wxT("Invalid time in wxDateTime::Set()") );
1322 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1324 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1325 wxT("Invalid date in wxDateTime::Set()") );
1327 // the range of time_t type (inclusive)
1328 static const int yearMinInRange
= 1970;
1329 static const int yearMaxInRange
= 2037;
1331 // test only the year instead of testing for the exact end of the Unix
1332 // time_t range - it doesn't bring anything to do more precise checks
1333 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1335 // use the standard library version if the date is in range - this is
1336 // probably more efficient than our code
1338 tm
.tm_year
= year
- 1900;
1344 tm
.tm_isdst
= -1; // mktime() will guess it
1348 // and finally adjust milliseconds
1350 SetMillisecond(millisec
);
1356 // do time calculations ourselves: we want to calculate the number of
1357 // milliseconds between the given date and the epoch
1359 // get the JDN for the midnight of this day
1360 m_time
= GetTruncatedJDN(day
, month
, year
);
1361 m_time
-= EPOCH_JDN
;
1362 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1364 // JDN corresponds to GMT, we take localtime
1365 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1371 wxDateTime
& wxDateTime::Set(double jdn
)
1373 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1375 jdn
-= EPOCH_JDN
+ 0.5;
1377 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1379 // JDNs always are in UTC, so we don't need any adjustments for time zone
1384 wxDateTime
& wxDateTime::ResetTime()
1388 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1401 wxDateTime
wxDateTime::GetDateOnly() const
1408 return wxDateTime(tm
);
1411 // ----------------------------------------------------------------------------
1412 // DOS Date and Time Format functions
1413 // ----------------------------------------------------------------------------
1414 // the dos date and time value is an unsigned 32 bit value in the format:
1415 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1417 // Y = year offset from 1980 (0-127)
1419 // D = day of month (1-31)
1421 // m = minute (0-59)
1422 // s = bisecond (0-29) each bisecond indicates two seconds
1423 // ----------------------------------------------------------------------------
1425 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1430 long year
= ddt
& 0xFE000000;
1435 long month
= ddt
& 0x1E00000;
1440 long day
= ddt
& 0x1F0000;
1444 long hour
= ddt
& 0xF800;
1448 long minute
= ddt
& 0x7E0;
1452 long second
= ddt
& 0x1F;
1453 tm
.tm_sec
= second
* 2;
1455 return Set(mktime(&tm
));
1458 unsigned long wxDateTime::GetAsDOS() const
1461 time_t ticks
= GetTicks();
1463 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1464 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1466 long year
= tm
->tm_year
;
1470 long month
= tm
->tm_mon
;
1474 long day
= tm
->tm_mday
;
1477 long hour
= tm
->tm_hour
;
1480 long minute
= tm
->tm_min
;
1483 long second
= tm
->tm_sec
;
1486 ddt
= year
| month
| day
| hour
| minute
| second
;
1490 // ----------------------------------------------------------------------------
1491 // time_t <-> broken down time conversions
1492 // ----------------------------------------------------------------------------
1494 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1496 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1498 time_t time
= GetTicks();
1499 if ( time
!= (time_t)-1 )
1501 // use C RTL functions
1504 if ( tz
.GetOffset() == -GetTimeZone() )
1506 // we are working with local time
1507 tm
= wxLocaltime_r(&time
, &tmstruct
);
1509 // should never happen
1510 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1514 time
+= (time_t)tz
.GetOffset();
1515 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1516 int time2
= (int) time
;
1522 tm
= wxGmtime_r(&time
, &tmstruct
);
1524 // should never happen
1525 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1529 tm
= (struct tm
*)NULL
;
1535 // adjust the milliseconds
1537 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1538 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1541 //else: use generic code below
1544 // remember the time and do the calculations with the date only - this
1545 // eliminates rounding errors of the floating point arithmetics
1547 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1549 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1551 // we want to always have positive time and timeMidnight to be really
1552 // the midnight before it
1555 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1558 timeMidnight
-= timeOnly
;
1560 // calculate the Gregorian date from JDN for the midnight of our date:
1561 // this will yield day, month (in 1..12 range) and year
1563 // actually, this is the JDN for the noon of the previous day
1564 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1566 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1568 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1570 // calculate the century
1571 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1572 long century
= temp
/ DAYS_PER_400_YEARS
;
1574 // then the year and day of year (1 <= dayOfYear <= 366)
1575 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1576 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1577 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1579 // and finally the month and day of the month
1580 temp
= dayOfYear
* 5 - 3;
1581 long month
= temp
/ DAYS_PER_5_MONTHS
;
1582 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1584 // month is counted from March - convert to normal
1595 // year is offset by 4800
1598 // check that the algorithm gave us something reasonable
1599 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1600 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1602 // construct Tm from these values
1604 tm
.year
= (int)year
;
1605 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1606 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1607 tm
.mday
= (wxDateTime_t
)day
;
1608 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1609 timeOnly
-= tm
.msec
;
1610 timeOnly
/= 1000; // now we have time in seconds
1612 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1614 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1616 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1619 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1624 wxDateTime
& wxDateTime::SetYear(int year
)
1626 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1635 wxDateTime
& wxDateTime::SetMonth(Month month
)
1637 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1646 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1648 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1657 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1659 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1668 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1670 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1679 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1681 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1690 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1692 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1694 // we don't need to use GetTm() for this one
1695 m_time
-= m_time
% 1000l;
1696 m_time
+= millisecond
;
1701 // ----------------------------------------------------------------------------
1702 // wxDateTime arithmetics
1703 // ----------------------------------------------------------------------------
1705 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1709 tm
.year
+= diff
.GetYears();
1710 tm
.AddMonths(diff
.GetMonths());
1712 // check that the resulting date is valid
1713 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1715 // We suppose that when adding one month to Jan 31 we want to get Feb
1716 // 28 (or 29), i.e. adding a month to the last day of the month should
1717 // give the last day of the next month which is quite logical.
1719 // Unfortunately, there is no logic way to understand what should
1720 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1721 // We make it Feb 28 (last day too), but it is highly questionable.
1722 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1725 tm
.AddDays(diff
.GetTotalDays());
1729 wxASSERT_MSG( IsSameTime(tm
),
1730 wxT("Add(wxDateSpan) shouldn't modify time") );
1735 // ----------------------------------------------------------------------------
1736 // Weekday and monthday stuff
1737 // ----------------------------------------------------------------------------
1739 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1740 static inline int ConvertWeekDayToMondayBase(int wd
)
1742 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1747 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1749 wxASSERT_MSG( numWeek
> 0,
1750 wxT("invalid week number: weeks are counted from 1") );
1752 // Jan 4 always lies in the 1st week of the year
1753 wxDateTime
dt(4, Jan
, year
);
1754 dt
.SetToWeekDayInSameWeek(wd
);
1755 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1760 #if WXWIN_COMPATIBILITY_2_6
1761 // use a separate function to avoid warnings about using deprecated
1762 // SetToTheWeek in GetWeek below
1764 SetToTheWeek(int year
,
1765 wxDateTime::wxDateTime_t numWeek
,
1766 wxDateTime::WeekDay weekday
,
1767 wxDateTime::WeekFlags flags
)
1769 // Jan 4 always lies in the 1st week of the year
1770 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1771 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1772 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1777 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1781 int year
= GetYear();
1782 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1783 if ( GetYear() != year
)
1785 // oops... numWeek was too big
1792 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1794 WeekFlags flags
) const
1796 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1798 #endif // WXWIN_COMPATIBILITY_2_6
1800 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1803 // take the current month/year if none specified
1804 if ( year
== Inv_Year
)
1806 if ( month
== Inv_Month
)
1809 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1812 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1814 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1816 int wdayDst
= weekday
,
1817 wdayThis
= GetWeekDay();
1818 if ( wdayDst
== wdayThis
)
1824 if ( flags
== Default_First
)
1826 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1829 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1830 // is the first day in the week, but breaks down for Monday_First case so
1831 // we adjust the week days in this case
1832 if ( flags
== Monday_First
)
1834 if ( wdayThis
== Sun
)
1836 if ( wdayDst
== Sun
)
1839 //else: Sunday_First, nothing to do
1841 // go forward or back in time to the day we want
1842 if ( wdayDst
< wdayThis
)
1844 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1846 else // weekday > wdayThis
1848 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1852 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1854 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1857 WeekDay wdayThis
= GetWeekDay();
1858 if ( weekday
== wdayThis
)
1863 else if ( weekday
< wdayThis
)
1865 // need to advance a week
1866 diff
= 7 - (wdayThis
- weekday
);
1868 else // weekday > wdayThis
1870 diff
= weekday
- wdayThis
;
1873 return Add(wxDateSpan::Days(diff
));
1876 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1878 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1881 WeekDay wdayThis
= GetWeekDay();
1882 if ( weekday
== wdayThis
)
1887 else if ( weekday
> wdayThis
)
1889 // need to go to previous week
1890 diff
= 7 - (weekday
- wdayThis
);
1892 else // weekday < wdayThis
1894 diff
= wdayThis
- weekday
;
1897 return Subtract(wxDateSpan::Days(diff
));
1900 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1905 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1907 // we don't check explicitly that -5 <= n <= 5 because we will return false
1908 // anyhow in such case - but may be should still give an assert for it?
1910 // take the current month/year if none specified
1911 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1915 // TODO this probably could be optimised somehow...
1919 // get the first day of the month
1920 dt
.Set(1, month
, year
);
1923 WeekDay wdayFirst
= dt
.GetWeekDay();
1925 // go to the first weekday of the month
1926 int diff
= weekday
- wdayFirst
;
1930 // add advance n-1 weeks more
1933 dt
+= wxDateSpan::Days(diff
);
1935 else // count from the end of the month
1937 // get the last day of the month
1938 dt
.SetToLastMonthDay(month
, year
);
1941 WeekDay wdayLast
= dt
.GetWeekDay();
1943 // go to the last weekday of the month
1944 int diff
= wdayLast
- weekday
;
1948 // and rewind n-1 weeks from there
1951 dt
-= wxDateSpan::Days(diff
);
1954 // check that it is still in the same month
1955 if ( dt
.GetMonth() == month
)
1963 // no such day in this month
1969 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1971 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1974 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1976 return GetDayOfYearFromTm(GetTm(tz
));
1979 wxDateTime::wxDateTime_t
1980 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1982 if ( flags
== Default_First
)
1984 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1988 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1990 int wdTarget
= GetWeekDay(tz
);
1991 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1993 if ( flags
== Sunday_First
)
1995 // FIXME: First week is not calculated correctly.
1996 week
= (nDayInYear
- wdTarget
+ 7) / 7;
1997 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2000 else // week starts with monday
2002 // adjust the weekdays to non-US style.
2003 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2004 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2006 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2008 // Week 01 of a year is per definition the first week that has the
2009 // Thursday in this year, which is equivalent to the week that
2010 // contains the fourth day of January. In other words, the first
2011 // week of a new year is the week that has the majority of its
2012 // days in the new year. Week 01 might also contain days from the
2013 // previous year and the week before week 01 of a year is the last
2014 // week (52 or 53) of the previous year even if it contains days
2015 // from the new year. A week starts with Monday (day 1) and ends
2016 // with Sunday (day 7).
2019 // if Jan 1 is Thursday or less, it is in the first week of this year
2020 if ( wdYearStart
< 4 )
2022 // count the number of entire weeks between Jan 1 and this date
2023 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2025 // be careful to check for overflow in the next year
2026 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2029 else // Jan 1 is in the last week of the previous year
2031 // check if we happen to be at the last week of previous year:
2032 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2033 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2035 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2039 return (wxDateTime::wxDateTime_t
)week
;
2042 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2043 const TimeZone
& tz
) const
2046 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
2047 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
2049 if ( flags
== Default_First
)
2051 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2054 // compute offset of dateFirst from the beginning of the week
2056 if ( flags
== Sunday_First
)
2057 firstOffset
= wdFirst
- Sun
;
2059 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
2061 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
2064 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2066 int year
= GetYear();
2067 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2068 wxT("invalid year day") );
2070 bool isLeap
= IsLeapYear(year
);
2071 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2073 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2074 // don't need it neither - because of the CHECK above we know that
2075 // yday lies in December then
2076 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2078 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2087 // ----------------------------------------------------------------------------
2088 // Julian day number conversion and related stuff
2089 // ----------------------------------------------------------------------------
2091 double wxDateTime::GetJulianDayNumber() const
2093 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2096 double wxDateTime::GetRataDie() const
2098 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2099 return GetJulianDayNumber() - 1721119.5 - 306;
2102 // ----------------------------------------------------------------------------
2103 // timezone and DST stuff
2104 // ----------------------------------------------------------------------------
2106 int wxDateTime::IsDST(wxDateTime::Country country
) const
2108 wxCHECK_MSG( country
== Country_Default
, -1,
2109 wxT("country support not implemented") );
2111 // use the C RTL for the dates in the standard range
2112 time_t timet
= GetTicks();
2113 if ( timet
!= (time_t)-1 )
2116 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2118 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2120 return tm
->tm_isdst
;
2124 int year
= GetYear();
2126 if ( !IsDSTApplicable(year
, country
) )
2128 // no DST time in this year in this country
2132 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2136 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2138 long secDiff
= GetTimeZone() + tz
.GetOffset();
2140 // we need to know whether DST is or not in effect for this date unless
2141 // the test disabled by the caller
2142 if ( !noDST
&& (IsDST() == 1) )
2144 // FIXME we assume that the DST is always shifted by 1 hour
2148 return Add(wxTimeSpan::Seconds(secDiff
));
2151 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2153 long secDiff
= GetTimeZone() + tz
.GetOffset();
2155 // we need to know whether DST is or not in effect for this date unless
2156 // the test disabled by the caller
2157 if ( !noDST
&& (IsDST() == 1) )
2159 // FIXME we assume that the DST is always shifted by 1 hour
2163 return Subtract(wxTimeSpan::Seconds(secDiff
));
2166 // ============================================================================
2167 // wxDateTimeHolidayAuthority and related classes
2168 // ============================================================================
2170 #include "wx/arrimpl.cpp"
2172 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2174 static int wxCMPFUNC_CONV
2175 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2177 wxDateTime dt1
= **first
,
2180 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2183 // ----------------------------------------------------------------------------
2184 // wxDateTimeHolidayAuthority
2185 // ----------------------------------------------------------------------------
2187 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2190 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2192 size_t count
= ms_authorities
.size();
2193 for ( size_t n
= 0; n
< count
; n
++ )
2195 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2206 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2207 const wxDateTime
& dtEnd
,
2208 wxDateTimeArray
& holidays
)
2210 wxDateTimeArray hol
;
2214 const size_t countAuth
= ms_authorities
.size();
2215 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2217 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2219 WX_APPEND_ARRAY(holidays
, hol
);
2222 holidays
.Sort(wxDateTimeCompareFunc
);
2224 return holidays
.size();
2228 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2230 WX_CLEAR_ARRAY(ms_authorities
);
2234 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2236 ms_authorities
.push_back(auth
);
2239 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2241 // required here for Darwin
2244 // ----------------------------------------------------------------------------
2245 // wxDateTimeWorkDays
2246 // ----------------------------------------------------------------------------
2248 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2250 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2252 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2255 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2256 const wxDateTime
& dtEnd
,
2257 wxDateTimeArray
& holidays
) const
2259 if ( dtStart
> dtEnd
)
2261 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2268 // instead of checking all days, start with the first Sat after dtStart and
2269 // end with the last Sun before dtEnd
2270 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2271 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2272 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2273 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2276 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2281 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2286 return holidays
.GetCount();
2289 // ============================================================================
2290 // other helper functions
2291 // ============================================================================
2293 // ----------------------------------------------------------------------------
2294 // iteration helpers: can be used to write a for loop over enum variable like
2296 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2297 // ----------------------------------------------------------------------------
2299 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2301 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2303 // no wrapping or the for loop above would never end!
2304 m
= (wxDateTime::Month
)(m
+ 1);
2307 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2309 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2311 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2312 : (wxDateTime::Month
)(m
- 1);
2315 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2317 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2319 // no wrapping or the for loop above would never end!
2320 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2323 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2325 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2327 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2328 : (wxDateTime::WeekDay
)(wd
- 1);
2333 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2336 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2338 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2341 wxDateTime
& wxDateTime::SetFromMSWSysDate(const SYSTEMTIME
& st
)
2344 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2349 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2351 const wxDateTime::Tm
tm(GetTm());
2353 st
->wYear
= (WXWORD
)tm
.year
;
2354 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2358 st
->wHour
= tm
.hour
;
2359 st
->wMinute
= tm
.min
;
2360 st
->wSecond
= tm
.sec
;
2361 st
->wMilliseconds
= tm
.msec
;
2364 void wxDateTime::GetAsMSWSysDate(SYSTEMTIME
* st
) const
2366 const wxDateTime::Tm
tm(GetTm());
2368 st
->wYear
= (WXWORD
)tm
.year
;
2369 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2376 st
->wMilliseconds
= 0;
2381 #endif // wxUSE_DATETIME