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"
79 #include "wx/tokenzr.h"
90 #include "wx/datetime.h"
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 #if wxUSE_EXTENDED_RTTI
98 template<> void wxStringReadValue(const wxString
&s
, wxDateTime
&data
)
100 data
.ParseFormat(s
,"%Y-%m-%d %H:%M:%S", NULL
);
103 template<> void wxStringWriteValue(wxString
&s
, const wxDateTime
&data
)
105 s
= data
.Format("%Y-%m-%d %H:%M:%S");
108 wxCUSTOM_TYPE_INFO(wxDateTime
, wxToStringConverter
<wxDateTime
> , wxFromStringConverter
<wxDateTime
>)
110 #endif // wxUSE_EXTENDED_RTTI
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 // debugging helper: just a convenient replacement of wxCHECK()
117 #define wxDATETIME_CHECK(expr, msg) \
118 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 class wxDateTimeHolidaysModule
: public wxModule
127 virtual bool OnInit()
129 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
134 virtual void OnExit()
136 wxDateTimeHolidayAuthority::ClearAllAuthorities();
137 wxDateTimeHolidayAuthority::ms_authorities
.clear();
141 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
144 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
151 static const int MONTHS_IN_YEAR
= 12;
153 static const int SEC_PER_MIN
= 60;
155 static const int MIN_PER_HOUR
= 60;
157 static const long SECONDS_PER_DAY
= 86400l;
159 static const int DAYS_PER_WEEK
= 7;
161 static const long MILLISECONDS_PER_DAY
= 86400000l;
163 // this is the integral part of JDN of the midnight of Jan 1, 1970
164 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
165 static const long EPOCH_JDN
= 2440587l;
167 // these values are only used in asserts so don't define them if asserts are
168 // disabled to avoid warnings about unused static variables
170 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
171 // reference date for us) is Nov 24, 4714BC
172 static const int JDN_0_YEAR
= -4713;
173 static const int JDN_0_MONTH
= wxDateTime::Nov
;
174 static const int JDN_0_DAY
= 24;
175 #endif // wxDEBUG_LEVEL
177 // the constants used for JDN calculations
178 static const long JDN_OFFSET
= 32046l;
179 static const long DAYS_PER_5_MONTHS
= 153l;
180 static const long DAYS_PER_4_YEARS
= 1461l;
181 static const long DAYS_PER_400_YEARS
= 146097l;
183 // this array contains the cumulated number of days in all previous months for
184 // normal and leap years
185 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
187 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
188 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
191 const long wxDateTime::TIME_T_FACTOR
= 1000l;
193 // ----------------------------------------------------------------------------
195 // ----------------------------------------------------------------------------
197 const char wxDefaultDateTimeFormat
[] = "%c";
198 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
200 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
201 // indicate an invalid wxDateTime object
202 const wxDateTime wxDefaultDateTime
;
204 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
206 // ----------------------------------------------------------------------------
208 // ----------------------------------------------------------------------------
210 // debugger helper: this function can be called from a debugger to show what
211 // the date really is
212 extern const char *wxDumpDate(const wxDateTime
* dt
)
214 static char buf
[128];
216 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
218 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
224 // get the number of days in the given month of the given year
226 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
228 // the number of days in month in Julian/Gregorian calendar: the first line
229 // is for normal years, the second one is for the leap ones
230 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
232 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
233 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
236 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
239 // return the integral part of the JDN for the midnight of the given date (to
240 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
241 // noon of the previous day)
242 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
243 wxDateTime::Month mon
,
246 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
248 // check the date validity
250 (year
> JDN_0_YEAR
) ||
251 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
252 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
253 wxT("date out of range - can't convert to JDN")
256 // make the year positive to avoid problems with negative numbers division
259 // months are counted from March here
261 if ( mon
>= wxDateTime::Mar
)
271 // now we can simply add all the contributions together
272 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
273 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
274 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
279 #ifdef wxHAS_STRFTIME
281 // this function is a wrapper around strftime(3) adding error checking
282 // NOTE: not static because used by datetimefmt.cpp
283 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
286 // Create temp wxString here to work around mingw/cygwin bug 1046059
287 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
290 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
292 // There is one special case in which strftime() can return 0 without
293 // indicating an error: "%p" may give empty string depending on the
294 // locale, so check for it explicitly. Apparently it's really the only
296 if ( format
!= wxS("%p") )
298 // if the format is valid, buffer must be too small?
299 wxFAIL_MSG(wxT("strftime() failed"));
309 #endif // wxHAS_STRFTIME
311 // if year and/or month have invalid values, replace them with the current ones
312 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
313 wxDateTime::Month
*month
)
315 struct tm
*tmNow
= NULL
;
318 if ( *year
== wxDateTime::Inv_Year
)
320 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
322 *year
= 1900 + tmNow
->tm_year
;
325 if ( *month
== wxDateTime::Inv_Month
)
328 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
330 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
334 // fill the struct tm with default values
335 // NOTE: not static because used by datetimefmt.cpp
336 void InitTm(struct tm
& tm
)
338 // struct tm may have etxra fields (undocumented and with unportable
339 // names) which, nevertheless, must be set to 0
340 memset(&tm
, 0, sizeof(struct tm
));
342 tm
.tm_mday
= 1; // mday 0 is invalid
343 tm
.tm_year
= 76; // any valid year
344 tm
.tm_isdst
= -1; // auto determine
347 // ============================================================================
348 // implementation of wxDateTime
349 // ============================================================================
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
357 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
358 mon
= wxDateTime::Inv_Month
;
365 wday
= wxDateTime::Inv_WeekDay
;
368 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
372 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
373 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
374 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
375 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
376 mon
= (wxDateTime::Month
)tm
.tm_mon
;
377 year
= 1900 + tm
.tm_year
;
378 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
379 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
382 bool wxDateTime::Tm::IsValid() const
384 if ( mon
== wxDateTime::Inv_Month
)
387 // We need to check this here to avoid crashing in GetNumOfDaysInMonth() if
388 // somebody passed us "(wxDateTime::Month)1000".
389 wxCHECK_MSG( mon
>= wxDateTime::Jan
&& mon
< wxDateTime::Inv_Month
, false,
390 wxS("Invalid month value") );
392 // we allow for the leap seconds, although we don't use them (yet)
393 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
394 (mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
395 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
398 void wxDateTime::Tm::ComputeWeekDay()
400 // compute the week day from day/month/year: we use the dumbest algorithm
401 // possible: just compute our JDN and then use the (simple to derive)
402 // formula: weekday = (JDN + 1.5) % 7
403 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
406 void wxDateTime::Tm::AddMonths(int monDiff
)
408 // normalize the months field
409 while ( monDiff
< -mon
)
413 monDiff
+= MONTHS_IN_YEAR
;
416 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
420 monDiff
-= MONTHS_IN_YEAR
;
423 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
425 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
427 // NB: we don't check here that the resulting date is valid, this function
428 // is private and the caller must check it if needed
431 void wxDateTime::Tm::AddDays(int dayDiff
)
433 // normalize the days field
434 while ( dayDiff
+ mday
< 1 )
438 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
441 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
442 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
444 mday
-= GetNumOfDaysInMonth(year
, mon
);
449 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
450 wxT("logic error") );
453 // ----------------------------------------------------------------------------
455 // ----------------------------------------------------------------------------
457 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
461 case wxDateTime::Local
:
462 // get the offset from C RTL: it returns the difference GMT-local
463 // while we want to have the offset _from_ GMT, hence the '-'
464 m_offset
= -wxGetTimeZone();
467 case wxDateTime::GMT_12
:
468 case wxDateTime::GMT_11
:
469 case wxDateTime::GMT_10
:
470 case wxDateTime::GMT_9
:
471 case wxDateTime::GMT_8
:
472 case wxDateTime::GMT_7
:
473 case wxDateTime::GMT_6
:
474 case wxDateTime::GMT_5
:
475 case wxDateTime::GMT_4
:
476 case wxDateTime::GMT_3
:
477 case wxDateTime::GMT_2
:
478 case wxDateTime::GMT_1
:
479 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
482 case wxDateTime::GMT0
:
483 case wxDateTime::GMT1
:
484 case wxDateTime::GMT2
:
485 case wxDateTime::GMT3
:
486 case wxDateTime::GMT4
:
487 case wxDateTime::GMT5
:
488 case wxDateTime::GMT6
:
489 case wxDateTime::GMT7
:
490 case wxDateTime::GMT8
:
491 case wxDateTime::GMT9
:
492 case wxDateTime::GMT10
:
493 case wxDateTime::GMT11
:
494 case wxDateTime::GMT12
:
495 case wxDateTime::GMT13
:
496 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
499 case wxDateTime::A_CST
:
500 // Central Standard Time in use in Australia = UTC + 9.5
501 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
505 wxFAIL_MSG( wxT("unknown time zone") );
509 // ----------------------------------------------------------------------------
511 // ----------------------------------------------------------------------------
514 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
516 time_t t
= GetTimeNow();
517 return wxLocaltime_r(&t
, tmstruct
);
521 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
523 if ( year
== Inv_Year
)
524 year
= GetCurrentYear();
526 if ( cal
== Gregorian
)
528 // in Gregorian calendar leap years are those divisible by 4 except
529 // those divisible by 100 unless they're also divisible by 400
530 // (in some countries, like Russia and Greece, additional corrections
531 // exist, but they won't manifest themselves until 2700)
532 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
534 else if ( cal
== Julian
)
536 // in Julian calendar the rule is simpler
537 return year
% 4 == 0;
541 wxFAIL_MSG(wxT("unknown calendar"));
548 int wxDateTime::GetCentury(int year
)
550 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
554 int wxDateTime::ConvertYearToBC(int year
)
557 return year
> 0 ? year
: year
- 1;
561 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
566 return Now().GetYear();
569 wxFAIL_MSG(wxT("TODO"));
573 wxFAIL_MSG(wxT("unsupported calendar"));
581 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
586 return Now().GetMonth();
589 wxFAIL_MSG(wxT("TODO"));
593 wxFAIL_MSG(wxT("unsupported calendar"));
601 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
603 if ( year
== Inv_Year
)
605 // take the current year if none given
606 year
= GetCurrentYear();
613 return IsLeapYear(year
) ? 366 : 365;
616 wxFAIL_MSG(wxT("unsupported calendar"));
624 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
626 wxDateTime::Calendar cal
)
628 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
630 if ( cal
== Gregorian
|| cal
== Julian
)
632 if ( year
== Inv_Year
)
634 // take the current year if none given
635 year
= GetCurrentYear();
638 return GetNumOfDaysInMonth(year
, month
);
642 wxFAIL_MSG(wxT("unsupported calendar"));
651 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
652 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
653 // asserts in this case)
655 // the return value of this function is used as an index into 2D array
656 // containing full names in its first row and abbreviated ones in the 2nd one
657 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
661 case wxDateTime::Name_Full
:
664 case wxDateTime::Name_Abbr
:
668 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
674 } // anonymous namespace
677 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
679 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
681 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
683 { "January", "February", "March", "April", "May", "June",
684 "July", "August", "September", "October", "November", "December" },
685 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
686 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
689 const int idx
= NameArrayIndexFromFlag(flags
);
693 return monthNames
[idx
][month
];
697 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
698 wxDateTime::NameFlags flags
)
700 #ifdef wxHAS_STRFTIME
701 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
703 // notice that we must set all the fields to avoid confusing libc (GNU one
704 // gets confused to a crash if we don't do this)
709 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
710 #else // !wxHAS_STRFTIME
711 return GetEnglishMonthName(month
, flags
);
712 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
716 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
718 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
720 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
722 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
724 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
727 const int idx
= NameArrayIndexFromFlag(flags
);
731 return weekdayNames
[idx
][wday
];
735 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
736 wxDateTime::NameFlags flags
)
738 #ifdef wxHAS_STRFTIME
739 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
741 // take some arbitrary Sunday (but notice that the day should be such that
742 // after adding wday to it below we still have a valid date, e.g. don't
750 // and offset it by the number of days needed to get the correct wday
753 // call mktime() to normalize it...
756 // ... and call strftime()
757 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
758 #else // !wxHAS_STRFTIME
759 return GetEnglishWeekDayName(wday
, flags
);
760 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
764 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
769 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
770 // and causes an assertion failed if the buffer is to small (which is good) - OR -
771 // if strftime does not return anything because the format string is invalid - OR -
772 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
773 // wxDateTime::ParseTime will try several different formats to parse the time.
774 // As a result, GetAmPmStrings might get called, even if the current locale
775 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
776 // assert, even though it is a perfectly legal use.
779 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
780 *am
= wxString(buffer
);
787 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
788 *pm
= wxString(buffer
);
795 // ----------------------------------------------------------------------------
796 // Country stuff: date calculations depend on the country (DST, work days,
797 // ...), so we need to know which rules to follow.
798 // ----------------------------------------------------------------------------
801 wxDateTime::Country
wxDateTime::GetCountry()
803 // TODO use LOCALE_ICOUNTRY setting under Win32
805 if ( ms_country
== Country_Unknown
)
807 // try to guess from the time zone name
808 time_t t
= time(NULL
);
810 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
812 wxString tz
= CallStrftime(wxT("%Z"), tm
);
813 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
817 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
819 ms_country
= Country_EEC
;
821 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
825 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
826 tz
== wxT("EST") || tz
== wxT("EDT") ||
827 tz
== wxT("CST") || tz
== wxT("CDT") ||
828 tz
== wxT("MST") || tz
== wxT("MDT") ||
829 tz
== wxT("PST") || tz
== wxT("PDT") )
835 // well, choose a default one
841 #endif // !__WXWINCE__/__WXWINCE__
847 void wxDateTime::SetCountry(wxDateTime::Country country
)
849 ms_country
= country
;
853 bool wxDateTime::IsWestEuropeanCountry(Country country
)
855 if ( country
== Country_Default
)
857 country
= GetCountry();
860 return (Country_WesternEurope_Start
<= country
) &&
861 (country
<= Country_WesternEurope_End
);
864 // ----------------------------------------------------------------------------
865 // DST calculations: we use 3 different rules for the West European countries,
866 // USA and for the rest of the world. This is undoubtedly false for many
867 // countries, but I lack the necessary info (and the time to gather it),
868 // please add the other rules here!
869 // ----------------------------------------------------------------------------
872 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
874 if ( year
== Inv_Year
)
876 // take the current year if none given
877 year
= GetCurrentYear();
880 if ( country
== Country_Default
)
882 country
= GetCountry();
889 // DST was first observed in the US and UK during WWI, reused
890 // during WWII and used again since 1966
891 return year
>= 1966 ||
892 (year
>= 1942 && year
<= 1945) ||
893 (year
== 1918 || year
== 1919);
896 // assume that it started after WWII
902 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
904 if ( year
== Inv_Year
)
906 // take the current year if none given
907 year
= GetCurrentYear();
910 if ( country
== Country_Default
)
912 country
= GetCountry();
915 if ( !IsDSTApplicable(year
, country
) )
917 return wxInvalidDateTime
;
922 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
924 // DST begins at 1 a.m. GMT on the last Sunday of March
925 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
928 wxFAIL_MSG( wxT("no last Sunday in March?") );
931 dt
+= wxTimeSpan::Hours(1);
933 else switch ( country
)
940 // don't know for sure - assume it was in effect all year
945 dt
.Set(1, Jan
, year
);
949 // DST was installed Feb 2, 1942 by the Congress
950 dt
.Set(2, Feb
, year
);
953 // Oil embargo changed the DST period in the US
955 dt
.Set(6, Jan
, 1974);
959 dt
.Set(23, Feb
, 1975);
963 // before 1986, DST begun on the last Sunday of April, but
964 // in 1986 Reagan changed it to begin at 2 a.m. of the
965 // first Sunday in April
968 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
971 wxFAIL_MSG( wxT("no first Sunday in April?") );
974 else if ( year
> 2006 )
975 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
976 // Starting in 2007, daylight time begins in the United States on the
977 // second Sunday in March and ends on the first Sunday in November
979 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
982 wxFAIL_MSG( wxT("no second Sunday in March?") );
987 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
990 wxFAIL_MSG( wxT("no first Sunday in April?") );
994 dt
+= wxTimeSpan::Hours(2);
996 // TODO what about timezone??
1002 // assume Mar 30 as the start of the DST for the rest of the world
1003 // - totally bogus, of course
1004 dt
.Set(30, Mar
, year
);
1011 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1013 if ( year
== Inv_Year
)
1015 // take the current year if none given
1016 year
= GetCurrentYear();
1019 if ( country
== Country_Default
)
1021 country
= GetCountry();
1024 if ( !IsDSTApplicable(year
, country
) )
1026 return wxInvalidDateTime
;
1031 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1033 // DST ends at 1 a.m. GMT on the last Sunday of October
1034 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1036 // weirder and weirder...
1037 wxFAIL_MSG( wxT("no last Sunday in October?") );
1040 dt
+= wxTimeSpan::Hours(1);
1042 else switch ( country
)
1049 // don't know for sure - assume it was in effect all year
1053 dt
.Set(31, Dec
, year
);
1057 // the time was reset after the end of the WWII
1058 dt
.Set(30, Sep
, year
);
1061 default: // default for switch (year)
1063 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1064 // Starting in 2007, daylight time begins in the United States on the
1065 // second Sunday in March and ends on the first Sunday in November
1067 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1070 wxFAIL_MSG( wxT("no first Sunday in November?") );
1075 // DST ends at 2 a.m. on the last Sunday of October
1077 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1079 // weirder and weirder...
1080 wxFAIL_MSG( wxT("no last Sunday in October?") );
1084 dt
+= wxTimeSpan::Hours(2);
1086 // TODO: what about timezone??
1090 default: // default for switch (country)
1091 // assume October 26th as the end of the DST - totally bogus too
1092 dt
.Set(26, Oct
, year
);
1098 // ----------------------------------------------------------------------------
1099 // constructors and assignment operators
1100 // ----------------------------------------------------------------------------
1102 // return the current time with ms precision
1103 /* static */ wxDateTime
wxDateTime::UNow()
1105 return wxDateTime(wxGetUTCTimeMillis());
1108 // the values in the tm structure contain the local time
1109 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1112 time_t timet
= mktime(&tm2
);
1114 if ( timet
== (time_t)-1 )
1116 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1117 // less than timezone - try to make it work for this case
1118 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1120 return Set((time_t)(
1122 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1123 tm2
.tm_min
* SEC_PER_MIN
+
1127 wxFAIL_MSG( wxT("mktime() failed") );
1129 *this = wxInvalidDateTime
;
1139 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1140 wxDateTime_t minute
,
1141 wxDateTime_t second
,
1142 wxDateTime_t millisec
)
1144 // we allow seconds to be 61 to account for the leap seconds, even if we
1145 // don't use them really
1146 wxDATETIME_CHECK( hour
< 24 &&
1150 wxT("Invalid time in wxDateTime::Set()") );
1152 // get the current date from system
1154 struct tm
*tm
= GetTmNow(&tmstruct
);
1156 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1158 // make a copy so it isn't clobbered by the call to mktime() below
1163 tm1
.tm_min
= minute
;
1164 tm1
.tm_sec
= second
;
1166 // and the DST in case it changes on this date
1169 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1170 tm1
.tm_isdst
= tm2
.tm_isdst
;
1174 // and finally adjust milliseconds
1175 return SetMillisecond(millisec
);
1178 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1182 wxDateTime_t minute
,
1183 wxDateTime_t second
,
1184 wxDateTime_t millisec
)
1186 wxDATETIME_CHECK( hour
< 24 &&
1190 wxT("Invalid time in wxDateTime::Set()") );
1192 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1194 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1195 wxT("Invalid date in wxDateTime::Set()") );
1197 // the range of time_t type (inclusive)
1198 static const int yearMinInRange
= 1970;
1199 static const int yearMaxInRange
= 2037;
1201 // test only the year instead of testing for the exact end of the Unix
1202 // time_t range - it doesn't bring anything to do more precise checks
1203 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1205 // use the standard library version if the date is in range - this is
1206 // probably more efficient than our code
1208 tm
.tm_year
= year
- 1900;
1214 tm
.tm_isdst
= -1; // mktime() will guess it
1218 // and finally adjust milliseconds
1220 SetMillisecond(millisec
);
1226 // do time calculations ourselves: we want to calculate the number of
1227 // milliseconds between the given date and the epoch
1229 // get the JDN for the midnight of this day
1230 m_time
= GetTruncatedJDN(day
, month
, year
);
1231 m_time
-= EPOCH_JDN
;
1232 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1234 // JDN corresponds to GMT, we take localtime
1235 Add(wxTimeSpan(hour
, minute
, second
+ wxGetTimeZone(), millisec
));
1241 wxDateTime
& wxDateTime::Set(double jdn
)
1243 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1245 jdn
-= EPOCH_JDN
+ 0.5;
1247 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1249 // JDNs always are in UTC, so we don't need any adjustments for time zone
1254 wxDateTime
& wxDateTime::ResetTime()
1258 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1271 wxDateTime
wxDateTime::GetDateOnly() const
1278 return wxDateTime(tm
);
1281 // ----------------------------------------------------------------------------
1282 // DOS Date and Time Format functions
1283 // ----------------------------------------------------------------------------
1284 // the dos date and time value is an unsigned 32 bit value in the format:
1285 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1287 // Y = year offset from 1980 (0-127)
1289 // D = day of month (1-31)
1291 // m = minute (0-59)
1292 // s = bisecond (0-29) each bisecond indicates two seconds
1293 // ----------------------------------------------------------------------------
1295 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1300 long year
= ddt
& 0xFE000000;
1305 long month
= ddt
& 0x1E00000;
1310 long day
= ddt
& 0x1F0000;
1314 long hour
= ddt
& 0xF800;
1318 long minute
= ddt
& 0x7E0;
1322 long second
= ddt
& 0x1F;
1323 tm
.tm_sec
= second
* 2;
1325 return Set(mktime(&tm
));
1328 unsigned long wxDateTime::GetAsDOS() const
1331 time_t ticks
= GetTicks();
1333 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1334 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1336 long year
= tm
->tm_year
;
1340 long month
= tm
->tm_mon
;
1344 long day
= tm
->tm_mday
;
1347 long hour
= tm
->tm_hour
;
1350 long minute
= tm
->tm_min
;
1353 long second
= tm
->tm_sec
;
1356 ddt
= year
| month
| day
| hour
| minute
| second
;
1360 // ----------------------------------------------------------------------------
1361 // time_t <-> broken down time conversions
1362 // ----------------------------------------------------------------------------
1364 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1366 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1368 time_t time
= GetTicks();
1369 if ( time
!= (time_t)-1 )
1371 // use C RTL functions
1374 if ( tz
.GetOffset() == -wxGetTimeZone() )
1376 // we are working with local time
1377 tm
= wxLocaltime_r(&time
, &tmstruct
);
1379 // should never happen
1380 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1384 time
+= (time_t)tz
.GetOffset();
1385 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1386 int time2
= (int) time
;
1392 tm
= wxGmtime_r(&time
, &tmstruct
);
1394 // should never happen
1395 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1399 tm
= (struct tm
*)NULL
;
1405 // adjust the milliseconds
1407 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1408 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1411 //else: use generic code below
1414 // remember the time and do the calculations with the date only - this
1415 // eliminates rounding errors of the floating point arithmetics
1417 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1419 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1421 // we want to always have positive time and timeMidnight to be really
1422 // the midnight before it
1425 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1428 timeMidnight
-= timeOnly
;
1430 // calculate the Gregorian date from JDN for the midnight of our date:
1431 // this will yield day, month (in 1..12 range) and year
1433 // actually, this is the JDN for the noon of the previous day
1434 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1436 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1438 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1440 // calculate the century
1441 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1442 long century
= temp
/ DAYS_PER_400_YEARS
;
1444 // then the year and day of year (1 <= dayOfYear <= 366)
1445 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1446 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1447 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1449 // and finally the month and day of the month
1450 temp
= dayOfYear
* 5 - 3;
1451 long month
= temp
/ DAYS_PER_5_MONTHS
;
1452 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1454 // month is counted from March - convert to normal
1465 // year is offset by 4800
1468 // check that the algorithm gave us something reasonable
1469 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1470 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1472 // construct Tm from these values
1474 tm
.year
= (int)year
;
1475 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1476 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1477 tm
.mday
= (wxDateTime_t
)day
;
1478 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1479 timeOnly
-= tm
.msec
;
1480 timeOnly
/= 1000; // now we have time in seconds
1482 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1484 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1486 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1489 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1494 wxDateTime
& wxDateTime::SetYear(int year
)
1496 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1505 wxDateTime
& wxDateTime::SetMonth(Month month
)
1507 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1516 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1518 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1527 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1529 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1538 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1540 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1549 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1551 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1560 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1562 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1564 // we don't need to use GetTm() for this one
1565 m_time
-= m_time
% 1000l;
1566 m_time
+= millisecond
;
1571 // ----------------------------------------------------------------------------
1572 // wxDateTime arithmetics
1573 // ----------------------------------------------------------------------------
1575 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1579 tm
.year
+= diff
.GetYears();
1580 tm
.AddMonths(diff
.GetMonths());
1582 // check that the resulting date is valid
1583 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1585 // We suppose that when adding one month to Jan 31 we want to get Feb
1586 // 28 (or 29), i.e. adding a month to the last day of the month should
1587 // give the last day of the next month which is quite logical.
1589 // Unfortunately, there is no logic way to understand what should
1590 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1591 // We make it Feb 28 (last day too), but it is highly questionable.
1592 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1595 tm
.AddDays(diff
.GetTotalDays());
1599 wxASSERT_MSG( IsSameTime(tm
),
1600 wxT("Add(wxDateSpan) shouldn't modify time") );
1605 wxDateSpan
wxDateTime::DiffAsDateSpan(const wxDateTime
& dt
) const
1607 wxASSERT_MSG( IsValid() && dt
.IsValid(), wxT("invalid wxDateTime"));
1609 // If dt is larger than this, calculations below needs to be inverted.
1614 int y
= GetYear() - dt
.GetYear();
1615 int m
= GetMonth() - dt
.GetMonth();
1616 int d
= GetDay() - dt
.GetDay();
1618 // If month diff is negative, dt is the year before, so decrease year
1619 // and set month diff to its inverse, e.g. January - December should be 1,
1621 if ( m
* inv
< 0 || (m
== 0 && d
* inv
< 0))
1623 m
+= inv
* MONTHS_IN_YEAR
;
1627 // Same logic for days as for months above.
1630 // Use number of days in month from the month which end date we're
1631 // crossing. That is month before this for positive diff, and this
1632 // month for negative diff.
1633 // If we're on january and using previous month, we get december
1634 // previous year, but don't care, december has same amount of days
1636 wxDateTime::Month monthfordays
= GetMonth();
1637 if (inv
> 0 && monthfordays
== wxDateTime::Jan
)
1638 monthfordays
= wxDateTime::Dec
;
1640 monthfordays
= static_cast<wxDateTime::Month
>(monthfordays
- 1);
1642 d
+= inv
* wxDateTime::GetNumberOfDays(monthfordays
, GetYear());
1646 int w
= d
/ DAYS_PER_WEEK
;
1648 // Remove weeks from d, since wxDateSpan only keep days as the ones
1649 // not in complete weeks
1650 d
-= w
* DAYS_PER_WEEK
;
1652 return wxDateSpan(y
, m
, w
, d
);
1655 // ----------------------------------------------------------------------------
1656 // Weekday and monthday stuff
1657 // ----------------------------------------------------------------------------
1659 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1660 static inline int ConvertWeekDayToMondayBase(int wd
)
1662 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1667 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1669 wxASSERT_MSG( numWeek
> 0,
1670 wxT("invalid week number: weeks are counted from 1") );
1672 // Jan 4 always lies in the 1st week of the year
1673 wxDateTime
dt(4, Jan
, year
);
1674 dt
.SetToWeekDayInSameWeek(wd
);
1675 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1680 #if WXWIN_COMPATIBILITY_2_6
1681 // use a separate function to avoid warnings about using deprecated
1682 // SetToTheWeek in GetWeek below
1684 SetToTheWeek(int year
,
1685 wxDateTime::wxDateTime_t numWeek
,
1686 wxDateTime::WeekDay weekday
,
1687 wxDateTime::WeekFlags flags
)
1689 // Jan 4 always lies in the 1st week of the year
1690 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1691 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1692 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1697 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1701 int year
= GetYear();
1702 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1703 if ( GetYear() != year
)
1705 // oops... numWeek was too big
1712 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1714 WeekFlags flags
) const
1716 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1718 #endif // WXWIN_COMPATIBILITY_2_6
1720 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1723 // take the current month/year if none specified
1724 if ( year
== Inv_Year
)
1726 if ( month
== Inv_Month
)
1729 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1732 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1734 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1736 int wdayDst
= weekday
,
1737 wdayThis
= GetWeekDay();
1738 if ( wdayDst
== wdayThis
)
1744 if ( flags
== Default_First
)
1746 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1749 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1750 // is the first day in the week, but breaks down for Monday_First case so
1751 // we adjust the week days in this case
1752 if ( flags
== Monday_First
)
1754 if ( wdayThis
== Sun
)
1756 if ( wdayDst
== Sun
)
1759 //else: Sunday_First, nothing to do
1761 // go forward or back in time to the day we want
1762 if ( wdayDst
< wdayThis
)
1764 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1766 else // weekday > wdayThis
1768 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1772 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1774 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1777 WeekDay wdayThis
= GetWeekDay();
1778 if ( weekday
== wdayThis
)
1783 else if ( weekday
< wdayThis
)
1785 // need to advance a week
1786 diff
= 7 - (wdayThis
- weekday
);
1788 else // weekday > wdayThis
1790 diff
= weekday
- wdayThis
;
1793 return Add(wxDateSpan::Days(diff
));
1796 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1798 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1801 WeekDay wdayThis
= GetWeekDay();
1802 if ( weekday
== wdayThis
)
1807 else if ( weekday
> wdayThis
)
1809 // need to go to previous week
1810 diff
= 7 - (weekday
- wdayThis
);
1812 else // weekday < wdayThis
1814 diff
= wdayThis
- weekday
;
1817 return Subtract(wxDateSpan::Days(diff
));
1820 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1825 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1827 // we don't check explicitly that -5 <= n <= 5 because we will return false
1828 // anyhow in such case - but may be should still give an assert for it?
1830 // take the current month/year if none specified
1831 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1835 // TODO this probably could be optimised somehow...
1839 // get the first day of the month
1840 dt
.Set(1, month
, year
);
1843 WeekDay wdayFirst
= dt
.GetWeekDay();
1845 // go to the first weekday of the month
1846 int diff
= weekday
- wdayFirst
;
1850 // add advance n-1 weeks more
1853 dt
+= wxDateSpan::Days(diff
);
1855 else // count from the end of the month
1857 // get the last day of the month
1858 dt
.SetToLastMonthDay(month
, year
);
1861 WeekDay wdayLast
= dt
.GetWeekDay();
1863 // go to the last weekday of the month
1864 int diff
= wdayLast
- weekday
;
1868 // and rewind n-1 weeks from there
1871 dt
-= wxDateSpan::Days(diff
);
1874 // check that it is still in the same month
1875 if ( dt
.GetMonth() == month
)
1883 // no such day in this month
1889 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1891 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1894 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1896 return GetDayOfYearFromTm(GetTm(tz
));
1899 wxDateTime::wxDateTime_t
1900 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1902 if ( flags
== Default_First
)
1904 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1908 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1910 int wdTarget
= GetWeekDay(tz
);
1911 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1913 if ( flags
== Sunday_First
)
1915 // FIXME: First week is not calculated correctly.
1916 week
= (nDayInYear
- wdTarget
+ 7) / 7;
1917 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1920 else // week starts with monday
1922 // adjust the weekdays to non-US style.
1923 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
1924 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
1926 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
1928 // Week 01 of a year is per definition the first week that has the
1929 // Thursday in this year, which is equivalent to the week that
1930 // contains the fourth day of January. In other words, the first
1931 // week of a new year is the week that has the majority of its
1932 // days in the new year. Week 01 might also contain days from the
1933 // previous year and the week before week 01 of a year is the last
1934 // week (52 or 53) of the previous year even if it contains days
1935 // from the new year. A week starts with Monday (day 1) and ends
1936 // with Sunday (day 7).
1939 // if Jan 1 is Thursday or less, it is in the first week of this year
1940 if ( wdYearStart
< 4 )
1942 // count the number of entire weeks between Jan 1 and this date
1943 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
1945 // be careful to check for overflow in the next year
1946 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
1949 else // Jan 1 is in the last week of the previous year
1951 // check if we happen to be at the last week of previous year:
1952 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
1953 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
1955 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
1959 return (wxDateTime::wxDateTime_t
)week
;
1962 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1963 const TimeZone
& tz
) const
1966 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
1967 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
1969 if ( flags
== Default_First
)
1971 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1974 // compute offset of dateFirst from the beginning of the week
1976 if ( flags
== Sunday_First
)
1977 firstOffset
= wdFirst
- Sun
;
1979 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
1981 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
1984 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
1986 int year
= GetYear();
1987 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
1988 wxT("invalid year day") );
1990 bool isLeap
= IsLeapYear(year
);
1991 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
1993 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1994 // don't need it neither - because of the CHECK above we know that
1995 // yday lies in December then
1996 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
1998 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2007 // ----------------------------------------------------------------------------
2008 // Julian day number conversion and related stuff
2009 // ----------------------------------------------------------------------------
2011 double wxDateTime::GetJulianDayNumber() const
2013 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2016 double wxDateTime::GetRataDie() const
2018 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2019 return GetJulianDayNumber() - 1721119.5 - 306;
2022 // ----------------------------------------------------------------------------
2023 // timezone and DST stuff
2024 // ----------------------------------------------------------------------------
2026 int wxDateTime::IsDST(wxDateTime::Country country
) const
2028 wxCHECK_MSG( country
== Country_Default
, -1,
2029 wxT("country support not implemented") );
2031 // use the C RTL for the dates in the standard range
2032 time_t timet
= GetTicks();
2033 if ( timet
!= (time_t)-1 )
2036 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2038 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2040 return tm
->tm_isdst
;
2044 int year
= GetYear();
2046 if ( !IsDSTApplicable(year
, country
) )
2048 // no DST time in this year in this country
2052 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2056 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2058 long secDiff
= wxGetTimeZone() + tz
.GetOffset();
2060 // we need to know whether DST is or not in effect for this date unless
2061 // the test disabled by the caller
2062 if ( !noDST
&& (IsDST() == 1) )
2064 // FIXME we assume that the DST is always shifted by 1 hour
2068 return Add(wxTimeSpan::Seconds(secDiff
));
2071 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2073 long secDiff
= wxGetTimeZone() + tz
.GetOffset();
2075 // we need to know whether DST is or not in effect for this date unless
2076 // the test disabled by the caller
2077 if ( !noDST
&& (IsDST() == 1) )
2079 // FIXME we assume that the DST is always shifted by 1 hour
2083 return Subtract(wxTimeSpan::Seconds(secDiff
));
2086 // ============================================================================
2087 // wxDateTimeHolidayAuthority and related classes
2088 // ============================================================================
2090 #include "wx/arrimpl.cpp"
2092 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2094 static int wxCMPFUNC_CONV
2095 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2097 wxDateTime dt1
= **first
,
2100 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2103 // ----------------------------------------------------------------------------
2104 // wxDateTimeHolidayAuthority
2105 // ----------------------------------------------------------------------------
2107 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2110 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2112 size_t count
= ms_authorities
.size();
2113 for ( size_t n
= 0; n
< count
; n
++ )
2115 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2126 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2127 const wxDateTime
& dtEnd
,
2128 wxDateTimeArray
& holidays
)
2130 wxDateTimeArray hol
;
2134 const size_t countAuth
= ms_authorities
.size();
2135 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2137 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2139 WX_APPEND_ARRAY(holidays
, hol
);
2142 holidays
.Sort(wxDateTimeCompareFunc
);
2144 return holidays
.size();
2148 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2150 WX_CLEAR_ARRAY(ms_authorities
);
2154 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2156 ms_authorities
.push_back(auth
);
2159 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2161 // required here for Darwin
2164 // ----------------------------------------------------------------------------
2165 // wxDateTimeWorkDays
2166 // ----------------------------------------------------------------------------
2168 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2170 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2172 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2175 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2176 const wxDateTime
& dtEnd
,
2177 wxDateTimeArray
& holidays
) const
2179 if ( dtStart
> dtEnd
)
2181 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2188 // instead of checking all days, start with the first Sat after dtStart and
2189 // end with the last Sun before dtEnd
2190 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2191 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2192 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2193 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2196 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2201 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2206 return holidays
.GetCount();
2209 // ============================================================================
2210 // other helper functions
2211 // ============================================================================
2213 // ----------------------------------------------------------------------------
2214 // iteration helpers: can be used to write a for loop over enum variable like
2216 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2217 // ----------------------------------------------------------------------------
2219 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2221 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2223 // no wrapping or the for loop above would never end!
2224 m
= (wxDateTime::Month
)(m
+ 1);
2227 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2229 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2231 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2232 : (wxDateTime::Month
)(m
- 1);
2235 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2237 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2239 // no wrapping or the for loop above would never end!
2240 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2243 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2245 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2247 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2248 : (wxDateTime::WeekDay
)(wd
- 1);
2253 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2256 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2258 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2261 wxDateTime
& wxDateTime::SetFromMSWSysDate(const SYSTEMTIME
& st
)
2264 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2269 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2271 const wxDateTime::Tm
tm(GetTm());
2273 st
->wYear
= (WXWORD
)tm
.year
;
2274 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2278 st
->wHour
= tm
.hour
;
2279 st
->wMinute
= tm
.min
;
2280 st
->wSecond
= tm
.sec
;
2281 st
->wMilliseconds
= tm
.msec
;
2284 void wxDateTime::GetAsMSWSysDate(SYSTEMTIME
* st
) const
2286 const wxDateTime::Tm
tm(GetTm());
2288 st
->wYear
= (WXWORD
)tm
.year
;
2289 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2296 st
->wMilliseconds
= 0;
2299 #endif // __WINDOWS__
2301 #endif // wxUSE_DATETIME