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
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows licence
17 ///////////////////////////////////////////////////////////////////////////////
20 * Implementation notes:
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
47 // ============================================================================
49 // ============================================================================
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
55 // For compilers that support precompilation, includes "wx.h".
56 #include "wx/wxprec.h"
62 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
66 #include "wx/msw/wrapwin.h"
68 #include "wx/string.h"
71 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
72 #include "wx/module.h"
76 #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
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 // debugging helper: just a convenient replacement of wxCHECK()
116 #define wxDATETIME_CHECK(expr, msg) \
117 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 class wxDateTimeHolidaysModule
: public wxModule
126 virtual bool OnInit()
128 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
133 virtual void OnExit()
135 wxDateTimeHolidayAuthority::ClearAllAuthorities();
136 wxDateTimeHolidayAuthority::ms_authorities
.clear();
140 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
143 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
150 static const int MONTHS_IN_YEAR
= 12;
152 static const int SEC_PER_MIN
= 60;
154 static const int MIN_PER_HOUR
= 60;
156 static const long SECONDS_PER_DAY
= 86400l;
158 static const int DAYS_PER_WEEK
= 7;
160 static const long MILLISECONDS_PER_DAY
= 86400000l;
162 // this is the integral part of JDN of the midnight of Jan 1, 1970
163 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
164 static const long EPOCH_JDN
= 2440587l;
166 // these values are only used in asserts so don't define them if asserts are
167 // disabled to avoid warnings about unused static variables
169 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
170 // reference date for us) is Nov 24, 4714BC
171 static const int JDN_0_YEAR
= -4713;
172 static const int JDN_0_MONTH
= wxDateTime::Nov
;
173 static const int JDN_0_DAY
= 24;
174 #endif // wxDEBUG_LEVEL
176 // the constants used for JDN calculations
177 static const long JDN_OFFSET
= 32046l;
178 static const long DAYS_PER_5_MONTHS
= 153l;
179 static const long DAYS_PER_4_YEARS
= 1461l;
180 static const long DAYS_PER_400_YEARS
= 146097l;
182 // this array contains the cumulated number of days in all previous months for
183 // normal and leap years
184 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
186 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
187 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
190 const long wxDateTime::TIME_T_FACTOR
= 1000l;
192 // ----------------------------------------------------------------------------
194 // ----------------------------------------------------------------------------
196 const char wxDefaultDateTimeFormat
[] = "%c";
197 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
199 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
200 // indicate an invalid wxDateTime object
201 const wxDateTime wxDefaultDateTime
;
203 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
205 // ----------------------------------------------------------------------------
207 // ----------------------------------------------------------------------------
209 // debugger helper: this function can be called from a debugger to show what
210 // the date really is
211 extern const char *wxDumpDate(const wxDateTime
* dt
)
213 static char buf
[128];
215 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
217 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
223 // get the number of days in the given month of the given year
225 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
227 // the number of days in month in Julian/Gregorian calendar: the first line
228 // is for normal years, the second one is for the leap ones
229 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
231 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
232 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
235 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
238 // return the integral part of the JDN for the midnight of the given date (to
239 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
240 // noon of the previous day)
241 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
242 wxDateTime::Month mon
,
245 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
247 // check the date validity
249 (year
> JDN_0_YEAR
) ||
250 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
251 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
252 wxT("date out of range - can't convert to JDN")
255 // make the year positive to avoid problems with negative numbers division
258 // months are counted from March here
260 if ( mon
>= wxDateTime::Mar
)
270 // now we can simply add all the contributions together
271 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
272 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
273 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
278 #ifdef wxHAS_STRFTIME
280 // this function is a wrapper around strftime(3) adding error checking
281 // NOTE: not static because used by datetimefmt.cpp
282 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
285 // Create temp wxString here to work around mingw/cygwin bug 1046059
286 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
289 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
291 // There is one special case in which strftime() can return 0 without
292 // indicating an error: "%p" may give empty string depending on the
293 // locale, so check for it explicitly. Apparently it's really the only
295 if ( format
!= wxS("%p") )
297 // if the format is valid, buffer must be too small?
298 wxFAIL_MSG(wxT("strftime() failed"));
308 #endif // wxHAS_STRFTIME
310 // if year and/or month have invalid values, replace them with the current ones
311 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
312 wxDateTime::Month
*month
)
314 struct tm
*tmNow
= NULL
;
317 if ( *year
== wxDateTime::Inv_Year
)
319 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
321 *year
= 1900 + tmNow
->tm_year
;
324 if ( *month
== wxDateTime::Inv_Month
)
327 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
329 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
333 // fill the struct tm with default values
334 // NOTE: not static because used by datetimefmt.cpp
335 void InitTm(struct tm
& tm
)
337 // struct tm may have etxra fields (undocumented and with unportable
338 // names) which, nevertheless, must be set to 0
339 memset(&tm
, 0, sizeof(struct tm
));
341 tm
.tm_mday
= 1; // mday 0 is invalid
342 tm
.tm_year
= 76; // any valid year
343 tm
.tm_isdst
= -1; // auto determine
346 // ============================================================================
347 // implementation of wxDateTime
348 // ============================================================================
350 // ----------------------------------------------------------------------------
352 // ----------------------------------------------------------------------------
356 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
357 mon
= wxDateTime::Inv_Month
;
364 wday
= wxDateTime::Inv_WeekDay
;
367 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
371 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
372 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
373 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
374 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
375 mon
= (wxDateTime::Month
)tm
.tm_mon
;
376 year
= 1900 + tm
.tm_year
;
377 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
378 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
381 bool wxDateTime::Tm::IsValid() const
383 if ( mon
== wxDateTime::Inv_Month
)
386 // We need to check this here to avoid crashing in GetNumOfDaysInMonth() if
387 // somebody passed us "(wxDateTime::Month)1000".
388 wxCHECK_MSG( mon
>= wxDateTime::Jan
&& mon
< wxDateTime::Inv_Month
, false,
389 wxS("Invalid month value") );
391 // we allow for the leap seconds, although we don't use them (yet)
392 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
393 (mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
394 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
397 void wxDateTime::Tm::ComputeWeekDay()
399 // compute the week day from day/month/year: we use the dumbest algorithm
400 // possible: just compute our JDN and then use the (simple to derive)
401 // formula: weekday = (JDN + 1.5) % 7
402 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
405 void wxDateTime::Tm::AddMonths(int monDiff
)
407 // normalize the months field
408 while ( monDiff
< -mon
)
412 monDiff
+= MONTHS_IN_YEAR
;
415 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
419 monDiff
-= MONTHS_IN_YEAR
;
422 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
424 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
426 // NB: we don't check here that the resulting date is valid, this function
427 // is private and the caller must check it if needed
430 void wxDateTime::Tm::AddDays(int dayDiff
)
432 // normalize the days field
433 while ( dayDiff
+ mday
< 1 )
437 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
440 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
441 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
443 mday
-= GetNumOfDaysInMonth(year
, mon
);
448 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
449 wxT("logic error") );
452 // ----------------------------------------------------------------------------
454 // ----------------------------------------------------------------------------
456 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
460 case wxDateTime::Local
:
461 // get the offset from C RTL: it returns the difference GMT-local
462 // while we want to have the offset _from_ GMT, hence the '-'
463 m_offset
= -wxGetTimeZone();
466 case wxDateTime::GMT_12
:
467 case wxDateTime::GMT_11
:
468 case wxDateTime::GMT_10
:
469 case wxDateTime::GMT_9
:
470 case wxDateTime::GMT_8
:
471 case wxDateTime::GMT_7
:
472 case wxDateTime::GMT_6
:
473 case wxDateTime::GMT_5
:
474 case wxDateTime::GMT_4
:
475 case wxDateTime::GMT_3
:
476 case wxDateTime::GMT_2
:
477 case wxDateTime::GMT_1
:
478 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
481 case wxDateTime::GMT0
:
482 case wxDateTime::GMT1
:
483 case wxDateTime::GMT2
:
484 case wxDateTime::GMT3
:
485 case wxDateTime::GMT4
:
486 case wxDateTime::GMT5
:
487 case wxDateTime::GMT6
:
488 case wxDateTime::GMT7
:
489 case wxDateTime::GMT8
:
490 case wxDateTime::GMT9
:
491 case wxDateTime::GMT10
:
492 case wxDateTime::GMT11
:
493 case wxDateTime::GMT12
:
494 case wxDateTime::GMT13
:
495 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
498 case wxDateTime::A_CST
:
499 // Central Standard Time in use in Australia = UTC + 9.5
500 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
504 wxFAIL_MSG( wxT("unknown time zone") );
508 // ----------------------------------------------------------------------------
510 // ----------------------------------------------------------------------------
513 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
515 time_t t
= GetTimeNow();
516 return wxLocaltime_r(&t
, tmstruct
);
520 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
522 if ( year
== Inv_Year
)
523 year
= GetCurrentYear();
525 if ( cal
== Gregorian
)
527 // in Gregorian calendar leap years are those divisible by 4 except
528 // those divisible by 100 unless they're also divisible by 400
529 // (in some countries, like Russia and Greece, additional corrections
530 // exist, but they won't manifest themselves until 2700)
531 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
533 else if ( cal
== Julian
)
535 // in Julian calendar the rule is simpler
536 return year
% 4 == 0;
540 wxFAIL_MSG(wxT("unknown calendar"));
547 int wxDateTime::GetCentury(int year
)
549 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
553 int wxDateTime::ConvertYearToBC(int year
)
556 return year
> 0 ? year
: year
- 1;
560 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
565 return Now().GetYear();
568 wxFAIL_MSG(wxT("TODO"));
572 wxFAIL_MSG(wxT("unsupported calendar"));
580 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
585 return Now().GetMonth();
588 wxFAIL_MSG(wxT("TODO"));
592 wxFAIL_MSG(wxT("unsupported calendar"));
600 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
602 if ( year
== Inv_Year
)
604 // take the current year if none given
605 year
= GetCurrentYear();
612 return IsLeapYear(year
) ? 366 : 365;
615 wxFAIL_MSG(wxT("unsupported calendar"));
623 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
625 wxDateTime::Calendar cal
)
627 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
629 if ( cal
== Gregorian
|| cal
== Julian
)
631 if ( year
== Inv_Year
)
633 // take the current year if none given
634 year
= GetCurrentYear();
637 return GetNumOfDaysInMonth(year
, month
);
641 wxFAIL_MSG(wxT("unsupported calendar"));
650 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
651 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
652 // asserts in this case)
654 // the return value of this function is used as an index into 2D array
655 // containing full names in its first row and abbreviated ones in the 2nd one
656 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
660 case wxDateTime::Name_Full
:
663 case wxDateTime::Name_Abbr
:
667 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
673 } // anonymous namespace
676 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
678 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
680 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
682 { "January", "February", "March", "April", "May", "June",
683 "July", "August", "September", "October", "November", "December" },
684 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
685 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
688 const int idx
= NameArrayIndexFromFlag(flags
);
692 return monthNames
[idx
][month
];
696 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
697 wxDateTime::NameFlags flags
)
699 #ifdef wxHAS_STRFTIME
700 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
702 // notice that we must set all the fields to avoid confusing libc (GNU one
703 // gets confused to a crash if we don't do this)
708 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
709 #else // !wxHAS_STRFTIME
710 return GetEnglishMonthName(month
, flags
);
711 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
715 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
717 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
719 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
721 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
723 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
726 const int idx
= NameArrayIndexFromFlag(flags
);
730 return weekdayNames
[idx
][wday
];
734 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
735 wxDateTime::NameFlags flags
)
737 #ifdef wxHAS_STRFTIME
738 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
740 // take some arbitrary Sunday (but notice that the day should be such that
741 // after adding wday to it below we still have a valid date, e.g. don't
749 // and offset it by the number of days needed to get the correct wday
752 // call mktime() to normalize it...
755 // ... and call strftime()
756 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
757 #else // !wxHAS_STRFTIME
758 return GetEnglishWeekDayName(wday
, flags
);
759 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
763 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
768 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
769 // and causes an assertion failed if the buffer is to small (which is good) - OR -
770 // if strftime does not return anything because the format string is invalid - OR -
771 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
772 // wxDateTime::ParseTime will try several different formats to parse the time.
773 // As a result, GetAmPmStrings might get called, even if the current locale
774 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
775 // assert, even though it is a perfectly legal use.
778 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
779 *am
= wxString(buffer
);
786 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
787 *pm
= wxString(buffer
);
794 // ----------------------------------------------------------------------------
795 // Country stuff: date calculations depend on the country (DST, work days,
796 // ...), so we need to know which rules to follow.
797 // ----------------------------------------------------------------------------
800 wxDateTime::Country
wxDateTime::GetCountry()
802 // TODO use LOCALE_ICOUNTRY setting under Win32
804 if ( ms_country
== Country_Unknown
)
806 // try to guess from the time zone name
807 time_t t
= time(NULL
);
809 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
811 wxString tz
= CallStrftime(wxT("%Z"), tm
);
812 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
816 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
818 ms_country
= Country_EEC
;
820 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
824 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
825 tz
== wxT("EST") || tz
== wxT("EDT") ||
826 tz
== wxT("CST") || tz
== wxT("CDT") ||
827 tz
== wxT("MST") || tz
== wxT("MDT") ||
828 tz
== wxT("PST") || tz
== wxT("PDT") )
834 // well, choose a default one
840 #endif // !__WXWINCE__/__WXWINCE__
846 void wxDateTime::SetCountry(wxDateTime::Country country
)
848 ms_country
= country
;
852 bool wxDateTime::IsWestEuropeanCountry(Country country
)
854 if ( country
== Country_Default
)
856 country
= GetCountry();
859 return (Country_WesternEurope_Start
<= country
) &&
860 (country
<= Country_WesternEurope_End
);
863 // ----------------------------------------------------------------------------
864 // DST calculations: we use 3 different rules for the West European countries,
865 // USA and for the rest of the world. This is undoubtedly false for many
866 // countries, but I lack the necessary info (and the time to gather it),
867 // please add the other rules here!
868 // ----------------------------------------------------------------------------
871 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
873 if ( year
== Inv_Year
)
875 // take the current year if none given
876 year
= GetCurrentYear();
879 if ( country
== Country_Default
)
881 country
= GetCountry();
888 // DST was first observed in the US and UK during WWI, reused
889 // during WWII and used again since 1966
890 return year
>= 1966 ||
891 (year
>= 1942 && year
<= 1945) ||
892 (year
== 1918 || year
== 1919);
895 // assume that it started after WWII
901 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
903 if ( year
== Inv_Year
)
905 // take the current year if none given
906 year
= GetCurrentYear();
909 if ( country
== Country_Default
)
911 country
= GetCountry();
914 if ( !IsDSTApplicable(year
, country
) )
916 return wxInvalidDateTime
;
921 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
923 // DST begins at 1 a.m. GMT on the last Sunday of March
924 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
927 wxFAIL_MSG( wxT("no last Sunday in March?") );
930 dt
+= wxTimeSpan::Hours(1);
932 else switch ( country
)
939 // don't know for sure - assume it was in effect all year
944 dt
.Set(1, Jan
, year
);
948 // DST was installed Feb 2, 1942 by the Congress
949 dt
.Set(2, Feb
, year
);
952 // Oil embargo changed the DST period in the US
954 dt
.Set(6, Jan
, 1974);
958 dt
.Set(23, Feb
, 1975);
962 // before 1986, DST begun on the last Sunday of April, but
963 // in 1986 Reagan changed it to begin at 2 a.m. of the
964 // first Sunday in April
967 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
970 wxFAIL_MSG( wxT("no first Sunday in April?") );
973 else if ( year
> 2006 )
974 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
975 // Starting in 2007, daylight time begins in the United States on the
976 // second Sunday in March and ends on the first Sunday in November
978 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
981 wxFAIL_MSG( wxT("no second Sunday in March?") );
986 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
989 wxFAIL_MSG( wxT("no first Sunday in April?") );
993 dt
+= wxTimeSpan::Hours(2);
995 // TODO what about timezone??
1001 // assume Mar 30 as the start of the DST for the rest of the world
1002 // - totally bogus, of course
1003 dt
.Set(30, Mar
, year
);
1010 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1012 if ( year
== Inv_Year
)
1014 // take the current year if none given
1015 year
= GetCurrentYear();
1018 if ( country
== Country_Default
)
1020 country
= GetCountry();
1023 if ( !IsDSTApplicable(year
, country
) )
1025 return wxInvalidDateTime
;
1030 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1032 // DST ends at 1 a.m. GMT on the last Sunday of October
1033 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1035 // weirder and weirder...
1036 wxFAIL_MSG( wxT("no last Sunday in October?") );
1039 dt
+= wxTimeSpan::Hours(1);
1041 else switch ( country
)
1048 // don't know for sure - assume it was in effect all year
1052 dt
.Set(31, Dec
, year
);
1056 // the time was reset after the end of the WWII
1057 dt
.Set(30, Sep
, year
);
1060 default: // default for switch (year)
1062 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1063 // Starting in 2007, daylight time begins in the United States on the
1064 // second Sunday in March and ends on the first Sunday in November
1066 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1069 wxFAIL_MSG( wxT("no first Sunday in November?") );
1074 // DST ends at 2 a.m. on the last Sunday of October
1076 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1078 // weirder and weirder...
1079 wxFAIL_MSG( wxT("no last Sunday in October?") );
1083 dt
+= wxTimeSpan::Hours(2);
1085 // TODO: what about timezone??
1089 default: // default for switch (country)
1090 // assume October 26th as the end of the DST - totally bogus too
1091 dt
.Set(26, Oct
, year
);
1097 // ----------------------------------------------------------------------------
1098 // constructors and assignment operators
1099 // ----------------------------------------------------------------------------
1101 // return the current time with ms precision
1102 /* static */ wxDateTime
wxDateTime::UNow()
1104 return wxDateTime(wxGetUTCTimeMillis());
1107 // the values in the tm structure contain the local time
1108 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1111 time_t timet
= mktime(&tm2
);
1113 if ( timet
== (time_t)-1 )
1115 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1116 // less than timezone - try to make it work for this case
1117 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1119 return Set((time_t)(
1121 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1122 tm2
.tm_min
* SEC_PER_MIN
+
1126 wxFAIL_MSG( wxT("mktime() failed") );
1128 *this = wxInvalidDateTime
;
1138 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1139 wxDateTime_t minute
,
1140 wxDateTime_t second
,
1141 wxDateTime_t millisec
)
1143 // we allow seconds to be 61 to account for the leap seconds, even if we
1144 // don't use them really
1145 wxDATETIME_CHECK( hour
< 24 &&
1149 wxT("Invalid time in wxDateTime::Set()") );
1151 // get the current date from system
1153 struct tm
*tm
= GetTmNow(&tmstruct
);
1155 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1157 // make a copy so it isn't clobbered by the call to mktime() below
1162 tm1
.tm_min
= minute
;
1163 tm1
.tm_sec
= second
;
1165 // and the DST in case it changes on this date
1168 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1169 tm1
.tm_isdst
= tm2
.tm_isdst
;
1173 // and finally adjust milliseconds
1174 return SetMillisecond(millisec
);
1177 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1181 wxDateTime_t minute
,
1182 wxDateTime_t second
,
1183 wxDateTime_t millisec
)
1185 wxDATETIME_CHECK( hour
< 24 &&
1189 wxT("Invalid time in wxDateTime::Set()") );
1191 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1193 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1194 wxT("Invalid date in wxDateTime::Set()") );
1196 // the range of time_t type (inclusive)
1197 static const int yearMinInRange
= 1970;
1198 static const int yearMaxInRange
= 2037;
1200 // test only the year instead of testing for the exact end of the Unix
1201 // time_t range - it doesn't bring anything to do more precise checks
1202 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1204 // use the standard library version if the date is in range - this is
1205 // probably more efficient than our code
1207 tm
.tm_year
= year
- 1900;
1213 tm
.tm_isdst
= -1; // mktime() will guess it
1217 // and finally adjust milliseconds
1219 SetMillisecond(millisec
);
1225 // do time calculations ourselves: we want to calculate the number of
1226 // milliseconds between the given date and the epoch
1228 // get the JDN for the midnight of this day
1229 m_time
= GetTruncatedJDN(day
, month
, year
);
1230 m_time
-= EPOCH_JDN
;
1231 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1233 // JDN corresponds to GMT, we take localtime
1234 Add(wxTimeSpan(hour
, minute
, second
+ wxGetTimeZone(), millisec
));
1240 wxDateTime
& wxDateTime::Set(double jdn
)
1242 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1244 jdn
-= EPOCH_JDN
+ 0.5;
1246 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1248 // JDNs always are in UTC, so we don't need any adjustments for time zone
1253 wxDateTime
& wxDateTime::ResetTime()
1257 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1270 wxDateTime
wxDateTime::GetDateOnly() const
1277 return wxDateTime(tm
);
1280 // ----------------------------------------------------------------------------
1281 // DOS Date and Time Format functions
1282 // ----------------------------------------------------------------------------
1283 // the dos date and time value is an unsigned 32 bit value in the format:
1284 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1286 // Y = year offset from 1980 (0-127)
1288 // D = day of month (1-31)
1290 // m = minute (0-59)
1291 // s = bisecond (0-29) each bisecond indicates two seconds
1292 // ----------------------------------------------------------------------------
1294 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1299 long year
= ddt
& 0xFE000000;
1304 long month
= ddt
& 0x1E00000;
1309 long day
= ddt
& 0x1F0000;
1313 long hour
= ddt
& 0xF800;
1317 long minute
= ddt
& 0x7E0;
1321 long second
= ddt
& 0x1F;
1322 tm
.tm_sec
= second
* 2;
1324 return Set(mktime(&tm
));
1327 unsigned long wxDateTime::GetAsDOS() const
1330 time_t ticks
= GetTicks();
1332 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1333 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1335 long year
= tm
->tm_year
;
1339 long month
= tm
->tm_mon
;
1343 long day
= tm
->tm_mday
;
1346 long hour
= tm
->tm_hour
;
1349 long minute
= tm
->tm_min
;
1352 long second
= tm
->tm_sec
;
1355 ddt
= year
| month
| day
| hour
| minute
| second
;
1359 // ----------------------------------------------------------------------------
1360 // time_t <-> broken down time conversions
1361 // ----------------------------------------------------------------------------
1363 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1365 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1367 time_t time
= GetTicks();
1368 if ( time
!= (time_t)-1 )
1370 // use C RTL functions
1373 if ( tz
.GetOffset() == -wxGetTimeZone() )
1375 // we are working with local time
1376 tm
= wxLocaltime_r(&time
, &tmstruct
);
1378 // should never happen
1379 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1383 time
+= (time_t)tz
.GetOffset();
1384 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1385 int time2
= (int) time
;
1391 tm
= wxGmtime_r(&time
, &tmstruct
);
1393 // should never happen
1394 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1398 tm
= (struct tm
*)NULL
;
1404 // adjust the milliseconds
1406 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1407 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1410 //else: use generic code below
1413 // remember the time and do the calculations with the date only - this
1414 // eliminates rounding errors of the floating point arithmetics
1416 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1418 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1420 // we want to always have positive time and timeMidnight to be really
1421 // the midnight before it
1424 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1427 timeMidnight
-= timeOnly
;
1429 // calculate the Gregorian date from JDN for the midnight of our date:
1430 // this will yield day, month (in 1..12 range) and year
1432 // actually, this is the JDN for the noon of the previous day
1433 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1435 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1437 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1439 // calculate the century
1440 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1441 long century
= temp
/ DAYS_PER_400_YEARS
;
1443 // then the year and day of year (1 <= dayOfYear <= 366)
1444 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1445 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1446 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1448 // and finally the month and day of the month
1449 temp
= dayOfYear
* 5 - 3;
1450 long month
= temp
/ DAYS_PER_5_MONTHS
;
1451 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1453 // month is counted from March - convert to normal
1464 // year is offset by 4800
1467 // check that the algorithm gave us something reasonable
1468 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1469 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1471 // construct Tm from these values
1473 tm
.year
= (int)year
;
1474 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1475 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1476 tm
.mday
= (wxDateTime_t
)day
;
1477 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1478 timeOnly
-= tm
.msec
;
1479 timeOnly
/= 1000; // now we have time in seconds
1481 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1483 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1485 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1488 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1493 wxDateTime
& wxDateTime::SetYear(int year
)
1495 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1504 wxDateTime
& wxDateTime::SetMonth(Month month
)
1506 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1515 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1517 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1526 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1528 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1537 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1539 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1548 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1550 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1559 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1561 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1563 // we don't need to use GetTm() for this one
1564 m_time
-= m_time
% 1000l;
1565 m_time
+= millisecond
;
1570 // ----------------------------------------------------------------------------
1571 // wxDateTime arithmetics
1572 // ----------------------------------------------------------------------------
1574 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1578 tm
.year
+= diff
.GetYears();
1579 tm
.AddMonths(diff
.GetMonths());
1581 // check that the resulting date is valid
1582 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1584 // We suppose that when adding one month to Jan 31 we want to get Feb
1585 // 28 (or 29), i.e. adding a month to the last day of the month should
1586 // give the last day of the next month which is quite logical.
1588 // Unfortunately, there is no logic way to understand what should
1589 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1590 // We make it Feb 28 (last day too), but it is highly questionable.
1591 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1594 tm
.AddDays(diff
.GetTotalDays());
1598 wxASSERT_MSG( IsSameTime(tm
),
1599 wxT("Add(wxDateSpan) shouldn't modify time") );
1604 wxDateSpan
wxDateTime::DiffAsDateSpan(const wxDateTime
& dt
) const
1606 wxASSERT_MSG( IsValid() && dt
.IsValid(), wxT("invalid wxDateTime"));
1608 // If dt is larger than this, calculations below needs to be inverted.
1613 int y
= GetYear() - dt
.GetYear();
1614 int m
= GetMonth() - dt
.GetMonth();
1615 int d
= GetDay() - dt
.GetDay();
1617 // If month diff is negative, dt is the year before, so decrease year
1618 // and set month diff to its inverse, e.g. January - December should be 1,
1620 if ( m
* inv
< 0 || (m
== 0 && d
* inv
< 0))
1622 m
+= inv
* MONTHS_IN_YEAR
;
1626 // Same logic for days as for months above.
1629 // Use number of days in month from the month which end date we're
1630 // crossing. That is month before this for positive diff, and this
1631 // month for negative diff.
1632 // If we're on january and using previous month, we get december
1633 // previous year, but don't care, december has same amount of days
1635 wxDateTime::Month monthfordays
= GetMonth();
1636 if (inv
> 0 && monthfordays
== wxDateTime::Jan
)
1637 monthfordays
= wxDateTime::Dec
;
1639 monthfordays
= static_cast<wxDateTime::Month
>(monthfordays
- 1);
1641 d
+= inv
* wxDateTime::GetNumberOfDays(monthfordays
, GetYear());
1645 int w
= d
/ DAYS_PER_WEEK
;
1647 // Remove weeks from d, since wxDateSpan only keep days as the ones
1648 // not in complete weeks
1649 d
-= w
* DAYS_PER_WEEK
;
1651 return wxDateSpan(y
, m
, w
, d
);
1654 // ----------------------------------------------------------------------------
1655 // Weekday and monthday stuff
1656 // ----------------------------------------------------------------------------
1658 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1659 static inline int ConvertWeekDayToMondayBase(int wd
)
1661 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1666 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1668 wxASSERT_MSG( numWeek
> 0,
1669 wxT("invalid week number: weeks are counted from 1") );
1671 // Jan 4 always lies in the 1st week of the year
1672 wxDateTime
dt(4, Jan
, year
);
1673 dt
.SetToWeekDayInSameWeek(wd
);
1674 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1679 #if WXWIN_COMPATIBILITY_2_6
1680 // use a separate function to avoid warnings about using deprecated
1681 // SetToTheWeek in GetWeek below
1683 SetToTheWeek(int year
,
1684 wxDateTime::wxDateTime_t numWeek
,
1685 wxDateTime::WeekDay weekday
,
1686 wxDateTime::WeekFlags flags
)
1688 // Jan 4 always lies in the 1st week of the year
1689 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1690 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1691 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1696 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1700 int year
= GetYear();
1701 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1702 if ( GetYear() != year
)
1704 // oops... numWeek was too big
1711 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1713 WeekFlags flags
) const
1715 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1717 #endif // WXWIN_COMPATIBILITY_2_6
1719 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1722 // take the current month/year if none specified
1723 if ( year
== Inv_Year
)
1725 if ( month
== Inv_Month
)
1728 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1731 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1733 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1735 int wdayDst
= weekday
,
1736 wdayThis
= GetWeekDay();
1737 if ( wdayDst
== wdayThis
)
1743 if ( flags
== Default_First
)
1745 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1748 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1749 // is the first day in the week, but breaks down for Monday_First case so
1750 // we adjust the week days in this case
1751 if ( flags
== Monday_First
)
1753 if ( wdayThis
== Sun
)
1755 if ( wdayDst
== Sun
)
1758 //else: Sunday_First, nothing to do
1760 // go forward or back in time to the day we want
1761 if ( wdayDst
< wdayThis
)
1763 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1765 else // weekday > wdayThis
1767 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1771 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1773 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1776 WeekDay wdayThis
= GetWeekDay();
1777 if ( weekday
== wdayThis
)
1782 else if ( weekday
< wdayThis
)
1784 // need to advance a week
1785 diff
= 7 - (wdayThis
- weekday
);
1787 else // weekday > wdayThis
1789 diff
= weekday
- wdayThis
;
1792 return Add(wxDateSpan::Days(diff
));
1795 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1797 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1800 WeekDay wdayThis
= GetWeekDay();
1801 if ( weekday
== wdayThis
)
1806 else if ( weekday
> wdayThis
)
1808 // need to go to previous week
1809 diff
= 7 - (weekday
- wdayThis
);
1811 else // weekday < wdayThis
1813 diff
= wdayThis
- weekday
;
1816 return Subtract(wxDateSpan::Days(diff
));
1819 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1824 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1826 // we don't check explicitly that -5 <= n <= 5 because we will return false
1827 // anyhow in such case - but may be should still give an assert for it?
1829 // take the current month/year if none specified
1830 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1834 // TODO this probably could be optimised somehow...
1838 // get the first day of the month
1839 dt
.Set(1, month
, year
);
1842 WeekDay wdayFirst
= dt
.GetWeekDay();
1844 // go to the first weekday of the month
1845 int diff
= weekday
- wdayFirst
;
1849 // add advance n-1 weeks more
1852 dt
+= wxDateSpan::Days(diff
);
1854 else // count from the end of the month
1856 // get the last day of the month
1857 dt
.SetToLastMonthDay(month
, year
);
1860 WeekDay wdayLast
= dt
.GetWeekDay();
1862 // go to the last weekday of the month
1863 int diff
= wdayLast
- weekday
;
1867 // and rewind n-1 weeks from there
1870 dt
-= wxDateSpan::Days(diff
);
1873 // check that it is still in the same month
1874 if ( dt
.GetMonth() == month
)
1882 // no such day in this month
1888 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1890 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1893 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1895 return GetDayOfYearFromTm(GetTm(tz
));
1898 wxDateTime::wxDateTime_t
1899 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1901 if ( flags
== Default_First
)
1903 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1907 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1909 int wdTarget
= GetWeekDay(tz
);
1910 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1912 if ( flags
== Sunday_First
)
1914 // FIXME: First week is not calculated correctly.
1915 week
= (nDayInYear
- wdTarget
+ 7) / 7;
1916 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1919 else // week starts with monday
1921 // adjust the weekdays to non-US style.
1922 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
1924 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
1926 // Week 01 of a year is per definition the first week that has the
1927 // Thursday in this year, which is equivalent to the week that
1928 // contains the fourth day of January. In other words, the first
1929 // week of a new year is the week that has the majority of its
1930 // days in the new year. Week 01 might also contain days from the
1931 // previous year and the week before week 01 of a year is the last
1932 // week (52 or 53) of the previous year even if it contains days
1933 // from the new year. A week starts with Monday (day 1) and ends
1934 // with Sunday (day 7).
1937 // if Jan 1 is Thursday or less, it is in the first week of this year
1938 int dayCountFix
= wdYearStart
< 4 ? 6 : -1;
1940 // count the number of week
1941 week
= (nDayInYear
+ wdYearStart
+ dayCountFix
) / DAYS_PER_WEEK
;
1943 // check if we happen to be at the last week of previous year:
1946 week
= wxDateTime(31, Dec
, GetYear() - 1).GetWeekOfYear();
1948 else if ( week
== 53 )
1950 int wdYearEnd
= (wdYearStart
+ 364 + IsLeapYear(GetYear()))
1953 // Week 53 only if last day of year is Thursday or later.
1954 if ( wdYearEnd
< 3 )
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