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 defined(__WXWINCE__) && defined(__VISUALC8__)
141 // _timezone is not present in dynamic run-time library
143 // Solution (1): use the function equivalent of _timezone
144 static long wxGetTimeZone()
150 #define WX_TIMEZONE wxGetTimeZone()
152 // Solution (2): using GetTimeZoneInformation
153 static long wxGetTimeZone()
155 TIME_ZONE_INFORMATION tzi
;
156 ::GetTimeZoneInformation(&tzi
);
157 return tzi
.Bias
; // x 60
159 #define WX_TIMEZONE wxGetTimeZone()
161 // Old method using _timezone: this symbol doesn't exist in the dynamic run-time library (i.e. using /MD)
162 #define WX_TIMEZONE _timezone
164 #else // unknown platform - try timezone
165 #define WX_TIMEZONE timezone
167 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
169 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
170 #if defined(__WXWINCE__) && defined(__VISUALC8__)
172 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
175 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
178 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
181 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
184 #else // !wxWinCE with VC8
186 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
187 static wxMutex timeLock
;
190 #ifndef HAVE_LOCALTIME_R
191 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
193 #if wxUSE_THREADS && !defined(__WINDOWS__)
194 // No need to waste time with a mutex on windows since it's using
195 // thread local storage for localtime anyway.
196 wxMutexLocker
locker(timeLock
);
199 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
205 const tm
* const t
= localtime(ticks
);
209 memcpy(temp
, t
, sizeof(struct tm
));
212 #endif // !HAVE_LOCALTIME_R
214 #ifndef HAVE_GMTIME_R
215 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
217 #if wxUSE_THREADS && !defined(__WINDOWS__)
218 // No need to waste time with a mutex on windows since it's
219 // using thread local storage for gmtime anyway.
220 wxMutexLocker
locker(timeLock
);
228 const tm
* const t
= gmtime(ticks
);
232 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
235 #endif // !HAVE_GMTIME_R
237 #endif // wxWinCE with VC8/other platforms
239 // ----------------------------------------------------------------------------
241 // ----------------------------------------------------------------------------
243 // debugging helper: just a convenient replacement of wxCHECK()
244 #define wxDATETIME_CHECK(expr, msg) \
245 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
247 // ----------------------------------------------------------------------------
249 // ----------------------------------------------------------------------------
251 class wxDateTimeHolidaysModule
: public wxModule
254 virtual bool OnInit()
256 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
261 virtual void OnExit()
263 wxDateTimeHolidayAuthority::ClearAllAuthorities();
264 wxDateTimeHolidayAuthority::ms_authorities
.clear();
268 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
271 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
273 // ----------------------------------------------------------------------------
275 // ----------------------------------------------------------------------------
278 static const int MONTHS_IN_YEAR
= 12;
280 static const int SEC_PER_MIN
= 60;
282 static const int MIN_PER_HOUR
= 60;
284 static const long SECONDS_PER_DAY
= 86400l;
286 static const int DAYS_PER_WEEK
= 7;
288 static const long MILLISECONDS_PER_DAY
= 86400000l;
290 // this is the integral part of JDN of the midnight of Jan 1, 1970
291 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
292 static const long EPOCH_JDN
= 2440587l;
294 // these values are only used in asserts so don't define them if asserts are
295 // disabled to avoid warnings about unused static variables
297 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
298 // reference date for us) is Nov 24, 4714BC
299 static const int JDN_0_YEAR
= -4713;
300 static const int JDN_0_MONTH
= wxDateTime::Nov
;
301 static const int JDN_0_DAY
= 24;
302 #endif // wxDEBUG_LEVEL
304 // the constants used for JDN calculations
305 static const long JDN_OFFSET
= 32046l;
306 static const long DAYS_PER_5_MONTHS
= 153l;
307 static const long DAYS_PER_4_YEARS
= 1461l;
308 static const long DAYS_PER_400_YEARS
= 146097l;
310 // this array contains the cumulated number of days in all previous months for
311 // normal and leap years
312 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
314 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
315 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
318 const long wxDateTime::TIME_T_FACTOR
= 1000l;
320 // ----------------------------------------------------------------------------
322 // ----------------------------------------------------------------------------
324 const char wxDefaultDateTimeFormat
[] = "%c";
325 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
327 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
328 // indicate an invalid wxDateTime object
329 const wxDateTime wxDefaultDateTime
;
331 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
333 // ----------------------------------------------------------------------------
335 // ----------------------------------------------------------------------------
337 // debugger helper: this function can be called from a debugger to show what
338 // the date really is
339 extern const char *wxDumpDate(const wxDateTime
* dt
)
341 static char buf
[128];
343 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
345 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
351 // get the number of days in the given month of the given year
353 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
355 // the number of days in month in Julian/Gregorian calendar: the first line
356 // is for normal years, the second one is for the leap ones
357 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
359 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
360 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
363 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
366 // returns the time zone in the C sense, i.e. the difference UTC - local
368 // NOTE: not static because used by datetimefmt.cpp
371 #ifdef WX_GMTOFF_IN_TM
372 // set to true when the timezone is set
373 static bool s_timezoneSet
= false;
374 static long gmtoffset
= LONG_MAX
; // invalid timezone
376 // ensure that the timezone variable is set by calling wxLocaltime_r
377 if ( !s_timezoneSet
)
379 // just call wxLocaltime_r() instead of figuring out whether this
380 // system supports tzset(), _tzset() or something else
384 wxLocaltime_r(&t
, &tm
);
385 s_timezoneSet
= true;
387 // note that GMT offset is the opposite of time zone and so to return
388 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
389 // cases we have to negate it
390 gmtoffset
= -tm
.tm_gmtoff
;
392 return (int)gmtoffset
;
393 #else // !WX_GMTOFF_IN_TM
395 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
398 // return the integral part of the JDN for the midnight of the given date (to
399 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
400 // noon of the previous day)
401 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
402 wxDateTime::Month mon
,
405 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
407 // check the date validity
409 (year
> JDN_0_YEAR
) ||
410 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
411 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
412 wxT("date out of range - can't convert to JDN")
415 // make the year positive to avoid problems with negative numbers division
418 // months are counted from March here
420 if ( mon
>= wxDateTime::Mar
)
430 // now we can simply add all the contributions together
431 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
432 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
433 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
438 #ifdef wxHAS_STRFTIME
440 // this function is a wrapper around strftime(3) adding error checking
441 // NOTE: not static because used by datetimefmt.cpp
442 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
445 // Create temp wxString here to work around mingw/cygwin bug 1046059
446 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
449 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
451 // if the format is valid, buffer must be too small?
452 wxFAIL_MSG(wxT("strftime() failed"));
461 #endif // wxHAS_STRFTIME
463 // if year and/or month have invalid values, replace them with the current ones
464 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
465 wxDateTime::Month
*month
)
467 struct tm
*tmNow
= NULL
;
470 if ( *year
== wxDateTime::Inv_Year
)
472 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
474 *year
= 1900 + tmNow
->tm_year
;
477 if ( *month
== wxDateTime::Inv_Month
)
480 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
482 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
486 // fill the struct tm with default values
487 // NOTE: not static because used by datetimefmt.cpp
488 void InitTm(struct tm
& tm
)
490 // struct tm may have etxra fields (undocumented and with unportable
491 // names) which, nevertheless, must be set to 0
492 memset(&tm
, 0, sizeof(struct tm
));
494 tm
.tm_mday
= 1; // mday 0 is invalid
495 tm
.tm_year
= 76; // any valid year
496 tm
.tm_isdst
= -1; // auto determine
499 // ============================================================================
500 // implementation of wxDateTime
501 // ============================================================================
503 // ----------------------------------------------------------------------------
505 // ----------------------------------------------------------------------------
509 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
510 mon
= wxDateTime::Inv_Month
;
512 hour
= min
= sec
= msec
= 0;
513 wday
= wxDateTime::Inv_WeekDay
;
516 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
520 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
521 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
522 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
523 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
524 mon
= (wxDateTime::Month
)tm
.tm_mon
;
525 year
= 1900 + tm
.tm_year
;
526 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
527 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
530 bool wxDateTime::Tm::IsValid() const
532 // we allow for the leap seconds, although we don't use them (yet)
533 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
534 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
535 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
538 void wxDateTime::Tm::ComputeWeekDay()
540 // compute the week day from day/month/year: we use the dumbest algorithm
541 // possible: just compute our JDN and then use the (simple to derive)
542 // formula: weekday = (JDN + 1.5) % 7
543 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
546 void wxDateTime::Tm::AddMonths(int monDiff
)
548 // normalize the months field
549 while ( monDiff
< -mon
)
553 monDiff
+= MONTHS_IN_YEAR
;
556 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
560 monDiff
-= MONTHS_IN_YEAR
;
563 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
565 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
567 // NB: we don't check here that the resulting date is valid, this function
568 // is private and the caller must check it if needed
571 void wxDateTime::Tm::AddDays(int dayDiff
)
573 // normalize the days field
574 while ( dayDiff
+ mday
< 1 )
578 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
581 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
582 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
584 mday
-= GetNumOfDaysInMonth(year
, mon
);
589 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
590 wxT("logic error") );
593 // ----------------------------------------------------------------------------
595 // ----------------------------------------------------------------------------
597 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
601 case wxDateTime::Local
:
602 // get the offset from C RTL: it returns the difference GMT-local
603 // while we want to have the offset _from_ GMT, hence the '-'
604 m_offset
= -GetTimeZone();
607 case wxDateTime::GMT_12
:
608 case wxDateTime::GMT_11
:
609 case wxDateTime::GMT_10
:
610 case wxDateTime::GMT_9
:
611 case wxDateTime::GMT_8
:
612 case wxDateTime::GMT_7
:
613 case wxDateTime::GMT_6
:
614 case wxDateTime::GMT_5
:
615 case wxDateTime::GMT_4
:
616 case wxDateTime::GMT_3
:
617 case wxDateTime::GMT_2
:
618 case wxDateTime::GMT_1
:
619 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
622 case wxDateTime::GMT0
:
623 case wxDateTime::GMT1
:
624 case wxDateTime::GMT2
:
625 case wxDateTime::GMT3
:
626 case wxDateTime::GMT4
:
627 case wxDateTime::GMT5
:
628 case wxDateTime::GMT6
:
629 case wxDateTime::GMT7
:
630 case wxDateTime::GMT8
:
631 case wxDateTime::GMT9
:
632 case wxDateTime::GMT10
:
633 case wxDateTime::GMT11
:
634 case wxDateTime::GMT12
:
635 case wxDateTime::GMT13
:
636 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
639 case wxDateTime::A_CST
:
640 // Central Standard Time in use in Australia = UTC + 9.5
641 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
645 wxFAIL_MSG( wxT("unknown time zone") );
649 // ----------------------------------------------------------------------------
651 // ----------------------------------------------------------------------------
654 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
656 time_t t
= GetTimeNow();
657 return wxLocaltime_r(&t
, tmstruct
);
661 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
663 if ( year
== Inv_Year
)
664 year
= GetCurrentYear();
666 if ( cal
== Gregorian
)
668 // in Gregorian calendar leap years are those divisible by 4 except
669 // those divisible by 100 unless they're also divisible by 400
670 // (in some countries, like Russia and Greece, additional corrections
671 // exist, but they won't manifest themselves until 2700)
672 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
674 else if ( cal
== Julian
)
676 // in Julian calendar the rule is simpler
677 return year
% 4 == 0;
681 wxFAIL_MSG(wxT("unknown calendar"));
688 int wxDateTime::GetCentury(int year
)
690 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
694 int wxDateTime::ConvertYearToBC(int year
)
697 return year
> 0 ? year
: year
- 1;
701 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
706 return Now().GetYear();
709 wxFAIL_MSG(wxT("TODO"));
713 wxFAIL_MSG(wxT("unsupported calendar"));
721 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
726 return Now().GetMonth();
729 wxFAIL_MSG(wxT("TODO"));
733 wxFAIL_MSG(wxT("unsupported calendar"));
741 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
743 if ( year
== Inv_Year
)
745 // take the current year if none given
746 year
= GetCurrentYear();
753 return IsLeapYear(year
) ? 366 : 365;
756 wxFAIL_MSG(wxT("unsupported calendar"));
764 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
766 wxDateTime::Calendar cal
)
768 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
770 if ( cal
== Gregorian
|| cal
== Julian
)
772 if ( year
== Inv_Year
)
774 // take the current year if none given
775 year
= GetCurrentYear();
778 return GetNumOfDaysInMonth(year
, month
);
782 wxFAIL_MSG(wxT("unsupported calendar"));
791 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
792 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
793 // asserts in this case)
795 // the return value of this function is used as an index into 2D array
796 // containing full names in its first row and abbreviated ones in the 2nd one
797 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
801 case wxDateTime::Name_Full
:
804 case wxDateTime::Name_Abbr
:
808 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
814 } // anonymous namespace
817 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
819 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
821 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
823 { "January", "February", "March", "April", "May", "June",
824 "July", "August", "September", "October", "November", "December" },
825 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
826 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
829 const int idx
= NameArrayIndexFromFlag(flags
);
833 return monthNames
[idx
][month
];
837 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
838 wxDateTime::NameFlags flags
)
840 #ifdef wxHAS_STRFTIME
841 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
843 // notice that we must set all the fields to avoid confusing libc (GNU one
844 // gets confused to a crash if we don't do this)
849 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
850 #else // !wxHAS_STRFTIME
851 return GetEnglishMonthName(month
, flags
);
852 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
856 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
858 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
860 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
862 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
864 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
867 const int idx
= NameArrayIndexFromFlag(flags
);
871 return weekdayNames
[idx
][wday
];
875 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
876 wxDateTime::NameFlags flags
)
878 #ifdef wxHAS_STRFTIME
879 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
881 // take some arbitrary Sunday (but notice that the day should be such that
882 // after adding wday to it below we still have a valid date, e.g. don't
890 // and offset it by the number of days needed to get the correct wday
893 // call mktime() to normalize it...
896 // ... and call strftime()
897 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
898 #else // !wxHAS_STRFTIME
899 return GetEnglishWeekDayName(wday
, flags
);
900 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
904 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
909 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
910 // and causes an assertion failed if the buffer is to small (which is good) - OR -
911 // if strftime does not return anything because the format string is invalid - OR -
912 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
913 // wxDateTime::ParseTime will try several different formats to parse the time.
914 // As a result, GetAmPmStrings might get called, even if the current locale
915 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
916 // assert, even though it is a perfectly legal use.
919 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
920 *am
= wxString(buffer
);
927 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
928 *pm
= wxString(buffer
);
935 // ----------------------------------------------------------------------------
936 // Country stuff: date calculations depend on the country (DST, work days,
937 // ...), so we need to know which rules to follow.
938 // ----------------------------------------------------------------------------
941 wxDateTime::Country
wxDateTime::GetCountry()
943 // TODO use LOCALE_ICOUNTRY setting under Win32
945 if ( ms_country
== Country_Unknown
)
947 // try to guess from the time zone name
948 time_t t
= time(NULL
);
950 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
952 wxString tz
= CallStrftime(wxT("%Z"), tm
);
953 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
957 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
959 ms_country
= Country_EEC
;
961 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
965 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
966 tz
== wxT("EST") || tz
== wxT("EDT") ||
967 tz
== wxT("CST") || tz
== wxT("CDT") ||
968 tz
== wxT("MST") || tz
== wxT("MDT") ||
969 tz
== wxT("PST") || tz
== wxT("PDT") )
975 // well, choose a default one
981 #endif // !__WXWINCE__/__WXWINCE__
987 void wxDateTime::SetCountry(wxDateTime::Country country
)
989 ms_country
= country
;
993 bool wxDateTime::IsWestEuropeanCountry(Country country
)
995 if ( country
== Country_Default
)
997 country
= GetCountry();
1000 return (Country_WesternEurope_Start
<= country
) &&
1001 (country
<= Country_WesternEurope_End
);
1004 // ----------------------------------------------------------------------------
1005 // DST calculations: we use 3 different rules for the West European countries,
1006 // USA and for the rest of the world. This is undoubtedly false for many
1007 // countries, but I lack the necessary info (and the time to gather it),
1008 // please add the other rules here!
1009 // ----------------------------------------------------------------------------
1012 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1014 if ( year
== Inv_Year
)
1016 // take the current year if none given
1017 year
= GetCurrentYear();
1020 if ( country
== Country_Default
)
1022 country
= GetCountry();
1029 // DST was first observed in the US and UK during WWI, reused
1030 // during WWII and used again since 1966
1031 return year
>= 1966 ||
1032 (year
>= 1942 && year
<= 1945) ||
1033 (year
== 1918 || year
== 1919);
1036 // assume that it started after WWII
1042 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1044 if ( year
== Inv_Year
)
1046 // take the current year if none given
1047 year
= GetCurrentYear();
1050 if ( country
== Country_Default
)
1052 country
= GetCountry();
1055 if ( !IsDSTApplicable(year
, country
) )
1057 return wxInvalidDateTime
;
1062 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1064 // DST begins at 1 a.m. GMT on the last Sunday of March
1065 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1068 wxFAIL_MSG( wxT("no last Sunday in March?") );
1071 dt
+= wxTimeSpan::Hours(1);
1073 else switch ( country
)
1080 // don't know for sure - assume it was in effect all year
1085 dt
.Set(1, Jan
, year
);
1089 // DST was installed Feb 2, 1942 by the Congress
1090 dt
.Set(2, Feb
, year
);
1093 // Oil embargo changed the DST period in the US
1095 dt
.Set(6, Jan
, 1974);
1099 dt
.Set(23, Feb
, 1975);
1103 // before 1986, DST begun on the last Sunday of April, but
1104 // in 1986 Reagan changed it to begin at 2 a.m. of the
1105 // first Sunday in April
1108 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1111 wxFAIL_MSG( wxT("no first Sunday in April?") );
1114 else if ( year
> 2006 )
1115 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1116 // Starting in 2007, daylight time begins in the United States on the
1117 // second Sunday in March and ends on the first Sunday in November
1119 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1122 wxFAIL_MSG( wxT("no second Sunday in March?") );
1127 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1130 wxFAIL_MSG( wxT("no first Sunday in April?") );
1134 dt
+= wxTimeSpan::Hours(2);
1136 // TODO what about timezone??
1142 // assume Mar 30 as the start of the DST for the rest of the world
1143 // - totally bogus, of course
1144 dt
.Set(30, Mar
, year
);
1151 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1153 if ( year
== Inv_Year
)
1155 // take the current year if none given
1156 year
= GetCurrentYear();
1159 if ( country
== Country_Default
)
1161 country
= GetCountry();
1164 if ( !IsDSTApplicable(year
, country
) )
1166 return wxInvalidDateTime
;
1171 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1173 // DST ends at 1 a.m. GMT on the last Sunday of October
1174 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1176 // weirder and weirder...
1177 wxFAIL_MSG( wxT("no last Sunday in October?") );
1180 dt
+= wxTimeSpan::Hours(1);
1182 else switch ( country
)
1189 // don't know for sure - assume it was in effect all year
1193 dt
.Set(31, Dec
, year
);
1197 // the time was reset after the end of the WWII
1198 dt
.Set(30, Sep
, year
);
1201 default: // default for switch (year)
1203 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1204 // Starting in 2007, daylight time begins in the United States on the
1205 // second Sunday in March and ends on the first Sunday in November
1207 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1210 wxFAIL_MSG( wxT("no first Sunday in November?") );
1215 // DST ends at 2 a.m. on the last Sunday of October
1217 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1219 // weirder and weirder...
1220 wxFAIL_MSG( wxT("no last Sunday in October?") );
1224 dt
+= wxTimeSpan::Hours(2);
1226 // TODO: what about timezone??
1230 default: // default for switch (country)
1231 // assume October 26th as the end of the DST - totally bogus too
1232 dt
.Set(26, Oct
, year
);
1238 // ----------------------------------------------------------------------------
1239 // constructors and assignment operators
1240 // ----------------------------------------------------------------------------
1242 // return the current time with ms precision
1243 /* static */ wxDateTime
wxDateTime::UNow()
1245 return wxDateTime(wxGetLocalTimeMillis());
1248 // the values in the tm structure contain the local time
1249 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1252 time_t timet
= mktime(&tm2
);
1254 if ( timet
== (time_t)-1 )
1256 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1257 // less than timezone - try to make it work for this case
1258 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1260 return Set((time_t)(
1262 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1263 tm2
.tm_min
* SEC_PER_MIN
+
1267 wxFAIL_MSG( wxT("mktime() failed") );
1269 *this = wxInvalidDateTime
;
1279 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1280 wxDateTime_t minute
,
1281 wxDateTime_t second
,
1282 wxDateTime_t millisec
)
1284 // we allow seconds to be 61 to account for the leap seconds, even if we
1285 // don't use them really
1286 wxDATETIME_CHECK( hour
< 24 &&
1290 wxT("Invalid time in wxDateTime::Set()") );
1292 // get the current date from system
1294 struct tm
*tm
= GetTmNow(&tmstruct
);
1296 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1298 // make a copy so it isn't clobbered by the call to mktime() below
1303 tm1
.tm_min
= minute
;
1304 tm1
.tm_sec
= second
;
1306 // and the DST in case it changes on this date
1309 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1310 tm1
.tm_isdst
= tm2
.tm_isdst
;
1314 // and finally adjust milliseconds
1315 return SetMillisecond(millisec
);
1318 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1322 wxDateTime_t minute
,
1323 wxDateTime_t second
,
1324 wxDateTime_t millisec
)
1326 wxDATETIME_CHECK( hour
< 24 &&
1330 wxT("Invalid time in wxDateTime::Set()") );
1332 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1334 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1335 wxT("Invalid date in wxDateTime::Set()") );
1337 // the range of time_t type (inclusive)
1338 static const int yearMinInRange
= 1970;
1339 static const int yearMaxInRange
= 2037;
1341 // test only the year instead of testing for the exact end of the Unix
1342 // time_t range - it doesn't bring anything to do more precise checks
1343 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1345 // use the standard library version if the date is in range - this is
1346 // probably more efficient than our code
1348 tm
.tm_year
= year
- 1900;
1354 tm
.tm_isdst
= -1; // mktime() will guess it
1358 // and finally adjust milliseconds
1360 SetMillisecond(millisec
);
1366 // do time calculations ourselves: we want to calculate the number of
1367 // milliseconds between the given date and the epoch
1369 // get the JDN for the midnight of this day
1370 m_time
= GetTruncatedJDN(day
, month
, year
);
1371 m_time
-= EPOCH_JDN
;
1372 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1374 // JDN corresponds to GMT, we take localtime
1375 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1381 wxDateTime
& wxDateTime::Set(double jdn
)
1383 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1385 jdn
-= EPOCH_JDN
+ 0.5;
1387 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1389 // JDNs always are in UTC, so we don't need any adjustments for time zone
1394 wxDateTime
& wxDateTime::ResetTime()
1398 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1411 wxDateTime
wxDateTime::GetDateOnly() const
1418 return wxDateTime(tm
);
1421 // ----------------------------------------------------------------------------
1422 // DOS Date and Time Format functions
1423 // ----------------------------------------------------------------------------
1424 // the dos date and time value is an unsigned 32 bit value in the format:
1425 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1427 // Y = year offset from 1980 (0-127)
1429 // D = day of month (1-31)
1431 // m = minute (0-59)
1432 // s = bisecond (0-29) each bisecond indicates two seconds
1433 // ----------------------------------------------------------------------------
1435 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1440 long year
= ddt
& 0xFE000000;
1445 long month
= ddt
& 0x1E00000;
1450 long day
= ddt
& 0x1F0000;
1454 long hour
= ddt
& 0xF800;
1458 long minute
= ddt
& 0x7E0;
1462 long second
= ddt
& 0x1F;
1463 tm
.tm_sec
= second
* 2;
1465 return Set(mktime(&tm
));
1468 unsigned long wxDateTime::GetAsDOS() const
1471 time_t ticks
= GetTicks();
1473 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1474 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1476 long year
= tm
->tm_year
;
1480 long month
= tm
->tm_mon
;
1484 long day
= tm
->tm_mday
;
1487 long hour
= tm
->tm_hour
;
1490 long minute
= tm
->tm_min
;
1493 long second
= tm
->tm_sec
;
1496 ddt
= year
| month
| day
| hour
| minute
| second
;
1500 // ----------------------------------------------------------------------------
1501 // time_t <-> broken down time conversions
1502 // ----------------------------------------------------------------------------
1504 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1506 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1508 time_t time
= GetTicks();
1509 if ( time
!= (time_t)-1 )
1511 // use C RTL functions
1514 if ( tz
.GetOffset() == -GetTimeZone() )
1516 // we are working with local time
1517 tm
= wxLocaltime_r(&time
, &tmstruct
);
1519 // should never happen
1520 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1524 time
+= (time_t)tz
.GetOffset();
1525 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1526 int time2
= (int) time
;
1532 tm
= wxGmtime_r(&time
, &tmstruct
);
1534 // should never happen
1535 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1539 tm
= (struct tm
*)NULL
;
1545 // adjust the milliseconds
1547 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1548 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1551 //else: use generic code below
1554 // remember the time and do the calculations with the date only - this
1555 // eliminates rounding errors of the floating point arithmetics
1557 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1559 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1561 // we want to always have positive time and timeMidnight to be really
1562 // the midnight before it
1565 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1568 timeMidnight
-= timeOnly
;
1570 // calculate the Gregorian date from JDN for the midnight of our date:
1571 // this will yield day, month (in 1..12 range) and year
1573 // actually, this is the JDN for the noon of the previous day
1574 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1576 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1578 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1580 // calculate the century
1581 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1582 long century
= temp
/ DAYS_PER_400_YEARS
;
1584 // then the year and day of year (1 <= dayOfYear <= 366)
1585 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1586 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1587 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1589 // and finally the month and day of the month
1590 temp
= dayOfYear
* 5 - 3;
1591 long month
= temp
/ DAYS_PER_5_MONTHS
;
1592 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1594 // month is counted from March - convert to normal
1605 // year is offset by 4800
1608 // check that the algorithm gave us something reasonable
1609 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1610 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1612 // construct Tm from these values
1614 tm
.year
= (int)year
;
1615 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1616 tm
.mday
= (wxDateTime_t
)day
;
1617 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1618 timeOnly
-= tm
.msec
;
1619 timeOnly
/= 1000; // now we have time in seconds
1621 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1623 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1625 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1628 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1633 wxDateTime
& wxDateTime::SetYear(int year
)
1635 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1644 wxDateTime
& wxDateTime::SetMonth(Month month
)
1646 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1655 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1657 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1666 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1668 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1677 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1679 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1688 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1690 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1699 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1701 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1703 // we don't need to use GetTm() for this one
1704 m_time
-= m_time
% 1000l;
1705 m_time
+= millisecond
;
1710 // ----------------------------------------------------------------------------
1711 // wxDateTime arithmetics
1712 // ----------------------------------------------------------------------------
1714 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1718 tm
.year
+= diff
.GetYears();
1719 tm
.AddMonths(diff
.GetMonths());
1721 // check that the resulting date is valid
1722 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1724 // We suppose that when adding one month to Jan 31 we want to get Feb
1725 // 28 (or 29), i.e. adding a month to the last day of the month should
1726 // give the last day of the next month which is quite logical.
1728 // Unfortunately, there is no logic way to understand what should
1729 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1730 // We make it Feb 28 (last day too), but it is highly questionable.
1731 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1734 tm
.AddDays(diff
.GetTotalDays());
1738 wxASSERT_MSG( IsSameTime(tm
),
1739 wxT("Add(wxDateSpan) shouldn't modify time") );
1744 // ----------------------------------------------------------------------------
1745 // Weekday and monthday stuff
1746 // ----------------------------------------------------------------------------
1748 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1749 static inline int ConvertWeekDayToMondayBase(int wd
)
1751 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1756 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1758 wxASSERT_MSG( numWeek
> 0,
1759 wxT("invalid week number: weeks are counted from 1") );
1761 // Jan 4 always lies in the 1st week of the year
1762 wxDateTime
dt(4, Jan
, year
);
1763 dt
.SetToWeekDayInSameWeek(wd
);
1764 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1769 #if WXWIN_COMPATIBILITY_2_6
1770 // use a separate function to avoid warnings about using deprecated
1771 // SetToTheWeek in GetWeek below
1773 SetToTheWeek(int year
,
1774 wxDateTime::wxDateTime_t numWeek
,
1775 wxDateTime::WeekDay weekday
,
1776 wxDateTime::WeekFlags flags
)
1778 // Jan 4 always lies in the 1st week of the year
1779 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1780 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1781 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1786 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1790 int year
= GetYear();
1791 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1792 if ( GetYear() != year
)
1794 // oops... numWeek was too big
1801 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1803 WeekFlags flags
) const
1805 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1807 #endif // WXWIN_COMPATIBILITY_2_6
1809 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1812 // take the current month/year if none specified
1813 if ( year
== Inv_Year
)
1815 if ( month
== Inv_Month
)
1818 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1821 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1823 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1825 int wdayDst
= weekday
,
1826 wdayThis
= GetWeekDay();
1827 if ( wdayDst
== wdayThis
)
1833 if ( flags
== Default_First
)
1835 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1838 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1839 // is the first day in the week, but breaks down for Monday_First case so
1840 // we adjust the week days in this case
1841 if ( flags
== Monday_First
)
1843 if ( wdayThis
== Sun
)
1845 if ( wdayDst
== Sun
)
1848 //else: Sunday_First, nothing to do
1850 // go forward or back in time to the day we want
1851 if ( wdayDst
< wdayThis
)
1853 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1855 else // weekday > wdayThis
1857 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1861 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1863 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1866 WeekDay wdayThis
= GetWeekDay();
1867 if ( weekday
== wdayThis
)
1872 else if ( weekday
< wdayThis
)
1874 // need to advance a week
1875 diff
= 7 - (wdayThis
- weekday
);
1877 else // weekday > wdayThis
1879 diff
= weekday
- wdayThis
;
1882 return Add(wxDateSpan::Days(diff
));
1885 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1887 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1890 WeekDay wdayThis
= GetWeekDay();
1891 if ( weekday
== wdayThis
)
1896 else if ( weekday
> wdayThis
)
1898 // need to go to previous week
1899 diff
= 7 - (weekday
- wdayThis
);
1901 else // weekday < wdayThis
1903 diff
= wdayThis
- weekday
;
1906 return Subtract(wxDateSpan::Days(diff
));
1909 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1914 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1916 // we don't check explicitly that -5 <= n <= 5 because we will return false
1917 // anyhow in such case - but may be should still give an assert for it?
1919 // take the current month/year if none specified
1920 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1924 // TODO this probably could be optimised somehow...
1928 // get the first day of the month
1929 dt
.Set(1, month
, year
);
1932 WeekDay wdayFirst
= dt
.GetWeekDay();
1934 // go to the first weekday of the month
1935 int diff
= weekday
- wdayFirst
;
1939 // add advance n-1 weeks more
1942 dt
+= wxDateSpan::Days(diff
);
1944 else // count from the end of the month
1946 // get the last day of the month
1947 dt
.SetToLastMonthDay(month
, year
);
1950 WeekDay wdayLast
= dt
.GetWeekDay();
1952 // go to the last weekday of the month
1953 int diff
= wdayLast
- weekday
;
1957 // and rewind n-1 weeks from there
1960 dt
-= wxDateSpan::Days(diff
);
1963 // check that it is still in the same month
1964 if ( dt
.GetMonth() == month
)
1972 // no such day in this month
1978 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1980 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1983 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1985 return GetDayOfYearFromTm(GetTm(tz
));
1988 wxDateTime::wxDateTime_t
1989 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1991 if ( flags
== Default_First
)
1993 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1997 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1999 int wdTarget
= GetWeekDay(tz
);
2000 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
2002 if ( flags
== Sunday_First
)
2004 // FIXME: First week is not calculated correctly.
2005 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2006 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2009 else // week starts with monday
2011 // adjust the weekdays to non-US style.
2012 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2013 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2015 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2017 // Week 01 of a year is per definition the first week that has the
2018 // Thursday in this year, which is equivalent to the week that
2019 // contains the fourth day of January. In other words, the first
2020 // week of a new year is the week that has the majority of its
2021 // days in the new year. Week 01 might also contain days from the
2022 // previous year and the week before week 01 of a year is the last
2023 // week (52 or 53) of the previous year even if it contains days
2024 // from the new year. A week starts with Monday (day 1) and ends
2025 // with Sunday (day 7).
2028 // if Jan 1 is Thursday or less, it is in the first week of this year
2029 if ( wdYearStart
< 4 )
2031 // count the number of entire weeks between Jan 1 and this date
2032 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2034 // be careful to check for overflow in the next year
2035 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2038 else // Jan 1 is in the last week of the previous year
2040 // check if we happen to be at the last week of previous year:
2041 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2042 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2044 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2048 return (wxDateTime::wxDateTime_t
)week
;
2051 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2052 const TimeZone
& tz
) const
2055 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
2056 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
2058 if ( flags
== Default_First
)
2060 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2063 // compute offset of dateFirst from the beginning of the week
2065 if ( flags
== Sunday_First
)
2066 firstOffset
= wdFirst
- Sun
;
2068 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
2070 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
2073 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2075 int year
= GetYear();
2076 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2077 wxT("invalid year day") );
2079 bool isLeap
= IsLeapYear(year
);
2080 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2082 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2083 // don't need it neither - because of the CHECK above we know that
2084 // yday lies in December then
2085 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2087 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2096 // ----------------------------------------------------------------------------
2097 // Julian day number conversion and related stuff
2098 // ----------------------------------------------------------------------------
2100 double wxDateTime::GetJulianDayNumber() const
2102 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2105 double wxDateTime::GetRataDie() const
2107 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2108 return GetJulianDayNumber() - 1721119.5 - 306;
2111 // ----------------------------------------------------------------------------
2112 // timezone and DST stuff
2113 // ----------------------------------------------------------------------------
2115 int wxDateTime::IsDST(wxDateTime::Country country
) const
2117 wxCHECK_MSG( country
== Country_Default
, -1,
2118 wxT("country support not implemented") );
2120 // use the C RTL for the dates in the standard range
2121 time_t timet
= GetTicks();
2122 if ( timet
!= (time_t)-1 )
2125 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2127 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2129 return tm
->tm_isdst
;
2133 int year
= GetYear();
2135 if ( !IsDSTApplicable(year
, country
) )
2137 // no DST time in this year in this country
2141 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2145 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2147 long secDiff
= GetTimeZone() + tz
.GetOffset();
2149 // we need to know whether DST is or not in effect for this date unless
2150 // the test disabled by the caller
2151 if ( !noDST
&& (IsDST() == 1) )
2153 // FIXME we assume that the DST is always shifted by 1 hour
2157 return Add(wxTimeSpan::Seconds(secDiff
));
2160 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2162 long secDiff
= GetTimeZone() + tz
.GetOffset();
2164 // we need to know whether DST is or not in effect for this date unless
2165 // the test disabled by the caller
2166 if ( !noDST
&& (IsDST() == 1) )
2168 // FIXME we assume that the DST is always shifted by 1 hour
2172 return Subtract(wxTimeSpan::Seconds(secDiff
));
2175 // ============================================================================
2176 // wxDateTimeHolidayAuthority and related classes
2177 // ============================================================================
2179 #include "wx/arrimpl.cpp"
2181 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2183 static int wxCMPFUNC_CONV
2184 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2186 wxDateTime dt1
= **first
,
2189 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2192 // ----------------------------------------------------------------------------
2193 // wxDateTimeHolidayAuthority
2194 // ----------------------------------------------------------------------------
2196 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2199 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2201 size_t count
= ms_authorities
.size();
2202 for ( size_t n
= 0; n
< count
; n
++ )
2204 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2215 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2216 const wxDateTime
& dtEnd
,
2217 wxDateTimeArray
& holidays
)
2219 wxDateTimeArray hol
;
2223 const size_t countAuth
= ms_authorities
.size();
2224 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2226 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2228 WX_APPEND_ARRAY(holidays
, hol
);
2231 holidays
.Sort(wxDateTimeCompareFunc
);
2233 return holidays
.size();
2237 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2239 WX_CLEAR_ARRAY(ms_authorities
);
2243 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2245 ms_authorities
.push_back(auth
);
2248 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2250 // required here for Darwin
2253 // ----------------------------------------------------------------------------
2254 // wxDateTimeWorkDays
2255 // ----------------------------------------------------------------------------
2257 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2259 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2261 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2264 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2265 const wxDateTime
& dtEnd
,
2266 wxDateTimeArray
& holidays
) const
2268 if ( dtStart
> dtEnd
)
2270 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2277 // instead of checking all days, start with the first Sat after dtStart and
2278 // end with the last Sun before dtEnd
2279 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2280 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2281 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2282 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2285 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2290 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2295 return holidays
.GetCount();
2298 // ============================================================================
2299 // other helper functions
2300 // ============================================================================
2302 // ----------------------------------------------------------------------------
2303 // iteration helpers: can be used to write a for loop over enum variable like
2305 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2306 // ----------------------------------------------------------------------------
2308 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2310 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2312 // no wrapping or the for loop above would never end!
2313 m
= (wxDateTime::Month
)(m
+ 1);
2316 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2318 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2320 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2321 : (wxDateTime::Month
)(m
- 1);
2324 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2326 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2328 // no wrapping or the for loop above would never end!
2329 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2332 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2334 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2336 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2337 : (wxDateTime::WeekDay
)(wd
- 1);
2342 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2345 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2347 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2350 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2352 const wxDateTime::Tm
tm(GetTm());
2354 st
->wYear
= (WXWORD
)tm
.year
;
2355 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2359 st
->wHour
= tm
.hour
;
2360 st
->wMinute
= tm
.min
;
2361 st
->wSecond
= tm
.sec
;
2362 st
->wMilliseconds
= tm
.msec
;
2366 #endif // wxUSE_DATETIME