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
113 // ----------------------------------------------------------------------------
114 // conditional compilation
115 // ----------------------------------------------------------------------------
117 #if defined(__MWERKS__) && wxUSE_UNICODE
121 #if defined(__DJGPP__) || defined(__WINE__)
122 #include <sys/timeb.h>
126 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
127 #if defined(__WXWINCE__) && defined(__VISUALC8__)
129 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
132 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
135 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
138 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
141 #else // !wxWinCE with VC8
143 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
144 static wxMutex timeLock
;
147 #ifndef HAVE_LOCALTIME_R
148 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
150 #if wxUSE_THREADS && !defined(__WINDOWS__)
151 // No need to waste time with a mutex on windows since it's using
152 // thread local storage for localtime anyway.
153 wxMutexLocker
locker(timeLock
);
156 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
162 const tm
* const t
= localtime(ticks
);
166 memcpy(temp
, t
, sizeof(struct tm
));
169 #endif // !HAVE_LOCALTIME_R
171 #ifndef HAVE_GMTIME_R
172 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
174 #if wxUSE_THREADS && !defined(__WINDOWS__)
175 // No need to waste time with a mutex on windows since it's
176 // using thread local storage for gmtime anyway.
177 wxMutexLocker
locker(timeLock
);
185 const tm
* const t
= gmtime(ticks
);
189 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
192 #endif // !HAVE_GMTIME_R
194 #endif // wxWinCE with VC8/other platforms
196 // ----------------------------------------------------------------------------
198 // ----------------------------------------------------------------------------
200 // debugging helper: just a convenient replacement of wxCHECK()
201 #define wxDATETIME_CHECK(expr, msg) \
202 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
204 // ----------------------------------------------------------------------------
206 // ----------------------------------------------------------------------------
208 class wxDateTimeHolidaysModule
: public wxModule
211 virtual bool OnInit()
213 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
218 virtual void OnExit()
220 wxDateTimeHolidayAuthority::ClearAllAuthorities();
221 wxDateTimeHolidayAuthority::ms_authorities
.clear();
225 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
228 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
230 // ----------------------------------------------------------------------------
232 // ----------------------------------------------------------------------------
235 static const int MONTHS_IN_YEAR
= 12;
237 static const int SEC_PER_MIN
= 60;
239 static const int MIN_PER_HOUR
= 60;
241 static const long SECONDS_PER_DAY
= 86400l;
243 static const int DAYS_PER_WEEK
= 7;
245 static const long MILLISECONDS_PER_DAY
= 86400000l;
247 // this is the integral part of JDN of the midnight of Jan 1, 1970
248 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
249 static const long EPOCH_JDN
= 2440587l;
251 // these values are only used in asserts so don't define them if asserts are
252 // disabled to avoid warnings about unused static variables
254 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
255 // reference date for us) is Nov 24, 4714BC
256 static const int JDN_0_YEAR
= -4713;
257 static const int JDN_0_MONTH
= wxDateTime::Nov
;
258 static const int JDN_0_DAY
= 24;
259 #endif // wxDEBUG_LEVEL
261 // the constants used for JDN calculations
262 static const long JDN_OFFSET
= 32046l;
263 static const long DAYS_PER_5_MONTHS
= 153l;
264 static const long DAYS_PER_4_YEARS
= 1461l;
265 static const long DAYS_PER_400_YEARS
= 146097l;
267 // this array contains the cumulated number of days in all previous months for
268 // normal and leap years
269 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
271 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
272 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
275 const long wxDateTime::TIME_T_FACTOR
= 1000l;
277 // ----------------------------------------------------------------------------
279 // ----------------------------------------------------------------------------
281 const char wxDefaultDateTimeFormat
[] = "%c";
282 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
284 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
285 // indicate an invalid wxDateTime object
286 const wxDateTime wxDefaultDateTime
;
288 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
290 // ----------------------------------------------------------------------------
292 // ----------------------------------------------------------------------------
294 // debugger helper: this function can be called from a debugger to show what
295 // the date really is
296 extern const char *wxDumpDate(const wxDateTime
* dt
)
298 static char buf
[128];
300 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
302 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
308 // get the number of days in the given month of the given year
310 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
312 // the number of days in month in Julian/Gregorian calendar: the first line
313 // is for normal years, the second one is for the leap ones
314 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
316 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
317 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
320 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
323 // return the integral part of the JDN for the midnight of the given date (to
324 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
325 // noon of the previous day)
326 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
327 wxDateTime::Month mon
,
330 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
332 // check the date validity
334 (year
> JDN_0_YEAR
) ||
335 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
336 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
337 wxT("date out of range - can't convert to JDN")
340 // make the year positive to avoid problems with negative numbers division
343 // months are counted from March here
345 if ( mon
>= wxDateTime::Mar
)
355 // now we can simply add all the contributions together
356 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
357 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
358 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
363 #ifdef wxHAS_STRFTIME
365 // this function is a wrapper around strftime(3) adding error checking
366 // NOTE: not static because used by datetimefmt.cpp
367 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
370 // Create temp wxString here to work around mingw/cygwin bug 1046059
371 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
374 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
376 // There is one special case in which strftime() can return 0 without
377 // indicating an error: "%p" may give empty string depending on the
378 // locale, so check for it explicitly. Apparently it's really the only
380 if ( format
!= wxS("%p") )
382 // if the format is valid, buffer must be too small?
383 wxFAIL_MSG(wxT("strftime() failed"));
393 #endif // wxHAS_STRFTIME
395 // if year and/or month have invalid values, replace them with the current ones
396 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
397 wxDateTime::Month
*month
)
399 struct tm
*tmNow
= NULL
;
402 if ( *year
== wxDateTime::Inv_Year
)
404 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
406 *year
= 1900 + tmNow
->tm_year
;
409 if ( *month
== wxDateTime::Inv_Month
)
412 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
414 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
418 // fill the struct tm with default values
419 // NOTE: not static because used by datetimefmt.cpp
420 void InitTm(struct tm
& tm
)
422 // struct tm may have etxra fields (undocumented and with unportable
423 // names) which, nevertheless, must be set to 0
424 memset(&tm
, 0, sizeof(struct tm
));
426 tm
.tm_mday
= 1; // mday 0 is invalid
427 tm
.tm_year
= 76; // any valid year
428 tm
.tm_isdst
= -1; // auto determine
431 // ============================================================================
432 // implementation of wxDateTime
433 // ============================================================================
435 // ----------------------------------------------------------------------------
437 // ----------------------------------------------------------------------------
441 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
442 mon
= wxDateTime::Inv_Month
;
449 wday
= wxDateTime::Inv_WeekDay
;
452 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
456 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
457 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
458 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
459 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
460 mon
= (wxDateTime::Month
)tm
.tm_mon
;
461 year
= 1900 + tm
.tm_year
;
462 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
463 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
466 bool wxDateTime::Tm::IsValid() const
468 if ( mon
== wxDateTime::Inv_Month
)
471 // We need to check this here to avoid crashing in GetNumOfDaysInMonth() if
472 // somebody passed us "(wxDateTime::Month)1000".
473 wxCHECK_MSG( mon
>= wxDateTime::Jan
&& mon
< wxDateTime::Inv_Month
, false,
474 wxS("Invalid month value") );
476 // we allow for the leap seconds, although we don't use them (yet)
477 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
478 (mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
479 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
482 void wxDateTime::Tm::ComputeWeekDay()
484 // compute the week day from day/month/year: we use the dumbest algorithm
485 // possible: just compute our JDN and then use the (simple to derive)
486 // formula: weekday = (JDN + 1.5) % 7
487 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
490 void wxDateTime::Tm::AddMonths(int monDiff
)
492 // normalize the months field
493 while ( monDiff
< -mon
)
497 monDiff
+= MONTHS_IN_YEAR
;
500 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
504 monDiff
-= MONTHS_IN_YEAR
;
507 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
509 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
511 // NB: we don't check here that the resulting date is valid, this function
512 // is private and the caller must check it if needed
515 void wxDateTime::Tm::AddDays(int dayDiff
)
517 // normalize the days field
518 while ( dayDiff
+ mday
< 1 )
522 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
525 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
526 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
528 mday
-= GetNumOfDaysInMonth(year
, mon
);
533 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
534 wxT("logic error") );
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
541 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
545 case wxDateTime::Local
:
546 // get the offset from C RTL: it returns the difference GMT-local
547 // while we want to have the offset _from_ GMT, hence the '-'
548 m_offset
= -wxGetTimeZone();
551 case wxDateTime::GMT_12
:
552 case wxDateTime::GMT_11
:
553 case wxDateTime::GMT_10
:
554 case wxDateTime::GMT_9
:
555 case wxDateTime::GMT_8
:
556 case wxDateTime::GMT_7
:
557 case wxDateTime::GMT_6
:
558 case wxDateTime::GMT_5
:
559 case wxDateTime::GMT_4
:
560 case wxDateTime::GMT_3
:
561 case wxDateTime::GMT_2
:
562 case wxDateTime::GMT_1
:
563 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
566 case wxDateTime::GMT0
:
567 case wxDateTime::GMT1
:
568 case wxDateTime::GMT2
:
569 case wxDateTime::GMT3
:
570 case wxDateTime::GMT4
:
571 case wxDateTime::GMT5
:
572 case wxDateTime::GMT6
:
573 case wxDateTime::GMT7
:
574 case wxDateTime::GMT8
:
575 case wxDateTime::GMT9
:
576 case wxDateTime::GMT10
:
577 case wxDateTime::GMT11
:
578 case wxDateTime::GMT12
:
579 case wxDateTime::GMT13
:
580 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
583 case wxDateTime::A_CST
:
584 // Central Standard Time in use in Australia = UTC + 9.5
585 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
589 wxFAIL_MSG( wxT("unknown time zone") );
593 // ----------------------------------------------------------------------------
595 // ----------------------------------------------------------------------------
598 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
600 time_t t
= GetTimeNow();
601 return wxLocaltime_r(&t
, tmstruct
);
605 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
607 if ( year
== Inv_Year
)
608 year
= GetCurrentYear();
610 if ( cal
== Gregorian
)
612 // in Gregorian calendar leap years are those divisible by 4 except
613 // those divisible by 100 unless they're also divisible by 400
614 // (in some countries, like Russia and Greece, additional corrections
615 // exist, but they won't manifest themselves until 2700)
616 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
618 else if ( cal
== Julian
)
620 // in Julian calendar the rule is simpler
621 return year
% 4 == 0;
625 wxFAIL_MSG(wxT("unknown calendar"));
632 int wxDateTime::GetCentury(int year
)
634 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
638 int wxDateTime::ConvertYearToBC(int year
)
641 return year
> 0 ? year
: year
- 1;
645 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
650 return Now().GetYear();
653 wxFAIL_MSG(wxT("TODO"));
657 wxFAIL_MSG(wxT("unsupported calendar"));
665 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
670 return Now().GetMonth();
673 wxFAIL_MSG(wxT("TODO"));
677 wxFAIL_MSG(wxT("unsupported calendar"));
685 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
687 if ( year
== Inv_Year
)
689 // take the current year if none given
690 year
= GetCurrentYear();
697 return IsLeapYear(year
) ? 366 : 365;
700 wxFAIL_MSG(wxT("unsupported calendar"));
708 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
710 wxDateTime::Calendar cal
)
712 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
714 if ( cal
== Gregorian
|| cal
== Julian
)
716 if ( year
== Inv_Year
)
718 // take the current year if none given
719 year
= GetCurrentYear();
722 return GetNumOfDaysInMonth(year
, month
);
726 wxFAIL_MSG(wxT("unsupported calendar"));
735 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
736 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
737 // asserts in this case)
739 // the return value of this function is used as an index into 2D array
740 // containing full names in its first row and abbreviated ones in the 2nd one
741 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
745 case wxDateTime::Name_Full
:
748 case wxDateTime::Name_Abbr
:
752 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
758 } // anonymous namespace
761 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
763 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
765 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
767 { "January", "February", "March", "April", "May", "June",
768 "July", "August", "September", "October", "November", "December" },
769 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
770 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
773 const int idx
= NameArrayIndexFromFlag(flags
);
777 return monthNames
[idx
][month
];
781 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
782 wxDateTime::NameFlags flags
)
784 #ifdef wxHAS_STRFTIME
785 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
787 // notice that we must set all the fields to avoid confusing libc (GNU one
788 // gets confused to a crash if we don't do this)
793 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
794 #else // !wxHAS_STRFTIME
795 return GetEnglishMonthName(month
, flags
);
796 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
800 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
802 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
804 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
806 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
808 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
811 const int idx
= NameArrayIndexFromFlag(flags
);
815 return weekdayNames
[idx
][wday
];
819 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
820 wxDateTime::NameFlags flags
)
822 #ifdef wxHAS_STRFTIME
823 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
825 // take some arbitrary Sunday (but notice that the day should be such that
826 // after adding wday to it below we still have a valid date, e.g. don't
834 // and offset it by the number of days needed to get the correct wday
837 // call mktime() to normalize it...
840 // ... and call strftime()
841 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
842 #else // !wxHAS_STRFTIME
843 return GetEnglishWeekDayName(wday
, flags
);
844 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
848 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
853 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
854 // and causes an assertion failed if the buffer is to small (which is good) - OR -
855 // if strftime does not return anything because the format string is invalid - OR -
856 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
857 // wxDateTime::ParseTime will try several different formats to parse the time.
858 // As a result, GetAmPmStrings might get called, even if the current locale
859 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
860 // assert, even though it is a perfectly legal use.
863 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
864 *am
= wxString(buffer
);
871 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
872 *pm
= wxString(buffer
);
879 // ----------------------------------------------------------------------------
880 // Country stuff: date calculations depend on the country (DST, work days,
881 // ...), so we need to know which rules to follow.
882 // ----------------------------------------------------------------------------
885 wxDateTime::Country
wxDateTime::GetCountry()
887 // TODO use LOCALE_ICOUNTRY setting under Win32
889 if ( ms_country
== Country_Unknown
)
891 // try to guess from the time zone name
892 time_t t
= time(NULL
);
894 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
896 wxString tz
= CallStrftime(wxT("%Z"), tm
);
897 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
901 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
903 ms_country
= Country_EEC
;
905 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
909 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
910 tz
== wxT("EST") || tz
== wxT("EDT") ||
911 tz
== wxT("CST") || tz
== wxT("CDT") ||
912 tz
== wxT("MST") || tz
== wxT("MDT") ||
913 tz
== wxT("PST") || tz
== wxT("PDT") )
919 // well, choose a default one
925 #endif // !__WXWINCE__/__WXWINCE__
931 void wxDateTime::SetCountry(wxDateTime::Country country
)
933 ms_country
= country
;
937 bool wxDateTime::IsWestEuropeanCountry(Country country
)
939 if ( country
== Country_Default
)
941 country
= GetCountry();
944 return (Country_WesternEurope_Start
<= country
) &&
945 (country
<= Country_WesternEurope_End
);
948 // ----------------------------------------------------------------------------
949 // DST calculations: we use 3 different rules for the West European countries,
950 // USA and for the rest of the world. This is undoubtedly false for many
951 // countries, but I lack the necessary info (and the time to gather it),
952 // please add the other rules here!
953 // ----------------------------------------------------------------------------
956 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
958 if ( year
== Inv_Year
)
960 // take the current year if none given
961 year
= GetCurrentYear();
964 if ( country
== Country_Default
)
966 country
= GetCountry();
973 // DST was first observed in the US and UK during WWI, reused
974 // during WWII and used again since 1966
975 return year
>= 1966 ||
976 (year
>= 1942 && year
<= 1945) ||
977 (year
== 1918 || year
== 1919);
980 // assume that it started after WWII
986 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
988 if ( year
== Inv_Year
)
990 // take the current year if none given
991 year
= GetCurrentYear();
994 if ( country
== Country_Default
)
996 country
= GetCountry();
999 if ( !IsDSTApplicable(year
, country
) )
1001 return wxInvalidDateTime
;
1006 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1008 // DST begins at 1 a.m. GMT on the last Sunday of March
1009 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1012 wxFAIL_MSG( wxT("no last Sunday in March?") );
1015 dt
+= wxTimeSpan::Hours(1);
1017 else switch ( country
)
1024 // don't know for sure - assume it was in effect all year
1029 dt
.Set(1, Jan
, year
);
1033 // DST was installed Feb 2, 1942 by the Congress
1034 dt
.Set(2, Feb
, year
);
1037 // Oil embargo changed the DST period in the US
1039 dt
.Set(6, Jan
, 1974);
1043 dt
.Set(23, Feb
, 1975);
1047 // before 1986, DST begun on the last Sunday of April, but
1048 // in 1986 Reagan changed it to begin at 2 a.m. of the
1049 // first Sunday in April
1052 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1055 wxFAIL_MSG( wxT("no first Sunday in April?") );
1058 else if ( year
> 2006 )
1059 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1060 // Starting in 2007, daylight time begins in the United States on the
1061 // second Sunday in March and ends on the first Sunday in November
1063 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1066 wxFAIL_MSG( wxT("no second Sunday in March?") );
1071 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1074 wxFAIL_MSG( wxT("no first Sunday in April?") );
1078 dt
+= wxTimeSpan::Hours(2);
1080 // TODO what about timezone??
1086 // assume Mar 30 as the start of the DST for the rest of the world
1087 // - totally bogus, of course
1088 dt
.Set(30, Mar
, year
);
1095 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1097 if ( year
== Inv_Year
)
1099 // take the current year if none given
1100 year
= GetCurrentYear();
1103 if ( country
== Country_Default
)
1105 country
= GetCountry();
1108 if ( !IsDSTApplicable(year
, country
) )
1110 return wxInvalidDateTime
;
1115 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1117 // DST ends at 1 a.m. GMT on the last Sunday of October
1118 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1120 // weirder and weirder...
1121 wxFAIL_MSG( wxT("no last Sunday in October?") );
1124 dt
+= wxTimeSpan::Hours(1);
1126 else switch ( country
)
1133 // don't know for sure - assume it was in effect all year
1137 dt
.Set(31, Dec
, year
);
1141 // the time was reset after the end of the WWII
1142 dt
.Set(30, Sep
, year
);
1145 default: // default for switch (year)
1147 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1148 // Starting in 2007, daylight time begins in the United States on the
1149 // second Sunday in March and ends on the first Sunday in November
1151 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1154 wxFAIL_MSG( wxT("no first Sunday in November?") );
1159 // DST ends at 2 a.m. on the last Sunday of October
1161 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1163 // weirder and weirder...
1164 wxFAIL_MSG( wxT("no last Sunday in October?") );
1168 dt
+= wxTimeSpan::Hours(2);
1170 // TODO: what about timezone??
1174 default: // default for switch (country)
1175 // assume October 26th as the end of the DST - totally bogus too
1176 dt
.Set(26, Oct
, year
);
1182 // ----------------------------------------------------------------------------
1183 // constructors and assignment operators
1184 // ----------------------------------------------------------------------------
1186 // return the current time with ms precision
1187 /* static */ wxDateTime
wxDateTime::UNow()
1189 return wxDateTime(wxGetLocalTimeMillis());
1192 // the values in the tm structure contain the local time
1193 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1196 time_t timet
= mktime(&tm2
);
1198 if ( timet
== (time_t)-1 )
1200 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1201 // less than timezone - try to make it work for this case
1202 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1204 return Set((time_t)(
1206 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1207 tm2
.tm_min
* SEC_PER_MIN
+
1211 wxFAIL_MSG( wxT("mktime() failed") );
1213 *this = wxInvalidDateTime
;
1223 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1224 wxDateTime_t minute
,
1225 wxDateTime_t second
,
1226 wxDateTime_t millisec
)
1228 // we allow seconds to be 61 to account for the leap seconds, even if we
1229 // don't use them really
1230 wxDATETIME_CHECK( hour
< 24 &&
1234 wxT("Invalid time in wxDateTime::Set()") );
1236 // get the current date from system
1238 struct tm
*tm
= GetTmNow(&tmstruct
);
1240 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1242 // make a copy so it isn't clobbered by the call to mktime() below
1247 tm1
.tm_min
= minute
;
1248 tm1
.tm_sec
= second
;
1250 // and the DST in case it changes on this date
1253 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1254 tm1
.tm_isdst
= tm2
.tm_isdst
;
1258 // and finally adjust milliseconds
1259 return SetMillisecond(millisec
);
1262 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1266 wxDateTime_t minute
,
1267 wxDateTime_t second
,
1268 wxDateTime_t millisec
)
1270 wxDATETIME_CHECK( hour
< 24 &&
1274 wxT("Invalid time in wxDateTime::Set()") );
1276 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1278 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1279 wxT("Invalid date in wxDateTime::Set()") );
1281 // the range of time_t type (inclusive)
1282 static const int yearMinInRange
= 1970;
1283 static const int yearMaxInRange
= 2037;
1285 // test only the year instead of testing for the exact end of the Unix
1286 // time_t range - it doesn't bring anything to do more precise checks
1287 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1289 // use the standard library version if the date is in range - this is
1290 // probably more efficient than our code
1292 tm
.tm_year
= year
- 1900;
1298 tm
.tm_isdst
= -1; // mktime() will guess it
1302 // and finally adjust milliseconds
1304 SetMillisecond(millisec
);
1310 // do time calculations ourselves: we want to calculate the number of
1311 // milliseconds between the given date and the epoch
1313 // get the JDN for the midnight of this day
1314 m_time
= GetTruncatedJDN(day
, month
, year
);
1315 m_time
-= EPOCH_JDN
;
1316 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1318 // JDN corresponds to GMT, we take localtime
1319 Add(wxTimeSpan(hour
, minute
, second
+ wxGetTimeZone(), millisec
));
1325 wxDateTime
& wxDateTime::Set(double jdn
)
1327 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1329 jdn
-= EPOCH_JDN
+ 0.5;
1331 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1333 // JDNs always are in UTC, so we don't need any adjustments for time zone
1338 wxDateTime
& wxDateTime::ResetTime()
1342 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1355 wxDateTime
wxDateTime::GetDateOnly() const
1362 return wxDateTime(tm
);
1365 // ----------------------------------------------------------------------------
1366 // DOS Date and Time Format functions
1367 // ----------------------------------------------------------------------------
1368 // the dos date and time value is an unsigned 32 bit value in the format:
1369 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1371 // Y = year offset from 1980 (0-127)
1373 // D = day of month (1-31)
1375 // m = minute (0-59)
1376 // s = bisecond (0-29) each bisecond indicates two seconds
1377 // ----------------------------------------------------------------------------
1379 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1384 long year
= ddt
& 0xFE000000;
1389 long month
= ddt
& 0x1E00000;
1394 long day
= ddt
& 0x1F0000;
1398 long hour
= ddt
& 0xF800;
1402 long minute
= ddt
& 0x7E0;
1406 long second
= ddt
& 0x1F;
1407 tm
.tm_sec
= second
* 2;
1409 return Set(mktime(&tm
));
1412 unsigned long wxDateTime::GetAsDOS() const
1415 time_t ticks
= GetTicks();
1417 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1418 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1420 long year
= tm
->tm_year
;
1424 long month
= tm
->tm_mon
;
1428 long day
= tm
->tm_mday
;
1431 long hour
= tm
->tm_hour
;
1434 long minute
= tm
->tm_min
;
1437 long second
= tm
->tm_sec
;
1440 ddt
= year
| month
| day
| hour
| minute
| second
;
1444 // ----------------------------------------------------------------------------
1445 // time_t <-> broken down time conversions
1446 // ----------------------------------------------------------------------------
1448 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1450 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1452 time_t time
= GetTicks();
1453 if ( time
!= (time_t)-1 )
1455 // use C RTL functions
1458 if ( tz
.GetOffset() == -wxGetTimeZone() )
1460 // we are working with local time
1461 tm
= wxLocaltime_r(&time
, &tmstruct
);
1463 // should never happen
1464 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1468 time
+= (time_t)tz
.GetOffset();
1469 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1470 int time2
= (int) time
;
1476 tm
= wxGmtime_r(&time
, &tmstruct
);
1478 // should never happen
1479 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1483 tm
= (struct tm
*)NULL
;
1489 // adjust the milliseconds
1491 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1492 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1495 //else: use generic code below
1498 // remember the time and do the calculations with the date only - this
1499 // eliminates rounding errors of the floating point arithmetics
1501 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1503 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1505 // we want to always have positive time and timeMidnight to be really
1506 // the midnight before it
1509 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1512 timeMidnight
-= timeOnly
;
1514 // calculate the Gregorian date from JDN for the midnight of our date:
1515 // this will yield day, month (in 1..12 range) and year
1517 // actually, this is the JDN for the noon of the previous day
1518 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1520 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1522 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1524 // calculate the century
1525 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1526 long century
= temp
/ DAYS_PER_400_YEARS
;
1528 // then the year and day of year (1 <= dayOfYear <= 366)
1529 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1530 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1531 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1533 // and finally the month and day of the month
1534 temp
= dayOfYear
* 5 - 3;
1535 long month
= temp
/ DAYS_PER_5_MONTHS
;
1536 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1538 // month is counted from March - convert to normal
1549 // year is offset by 4800
1552 // check that the algorithm gave us something reasonable
1553 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1554 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1556 // construct Tm from these values
1558 tm
.year
= (int)year
;
1559 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1560 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1561 tm
.mday
= (wxDateTime_t
)day
;
1562 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1563 timeOnly
-= tm
.msec
;
1564 timeOnly
/= 1000; // now we have time in seconds
1566 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1568 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1570 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1573 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1578 wxDateTime
& wxDateTime::SetYear(int year
)
1580 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1589 wxDateTime
& wxDateTime::SetMonth(Month month
)
1591 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1600 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1602 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1611 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1613 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1622 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1624 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1633 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1635 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1644 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1646 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1648 // we don't need to use GetTm() for this one
1649 m_time
-= m_time
% 1000l;
1650 m_time
+= millisecond
;
1655 // ----------------------------------------------------------------------------
1656 // wxDateTime arithmetics
1657 // ----------------------------------------------------------------------------
1659 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1663 tm
.year
+= diff
.GetYears();
1664 tm
.AddMonths(diff
.GetMonths());
1666 // check that the resulting date is valid
1667 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1669 // We suppose that when adding one month to Jan 31 we want to get Feb
1670 // 28 (or 29), i.e. adding a month to the last day of the month should
1671 // give the last day of the next month which is quite logical.
1673 // Unfortunately, there is no logic way to understand what should
1674 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1675 // We make it Feb 28 (last day too), but it is highly questionable.
1676 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1679 tm
.AddDays(diff
.GetTotalDays());
1683 wxASSERT_MSG( IsSameTime(tm
),
1684 wxT("Add(wxDateSpan) shouldn't modify time") );
1689 // ----------------------------------------------------------------------------
1690 // Weekday and monthday stuff
1691 // ----------------------------------------------------------------------------
1693 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1694 static inline int ConvertWeekDayToMondayBase(int wd
)
1696 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1701 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1703 wxASSERT_MSG( numWeek
> 0,
1704 wxT("invalid week number: weeks are counted from 1") );
1706 // Jan 4 always lies in the 1st week of the year
1707 wxDateTime
dt(4, Jan
, year
);
1708 dt
.SetToWeekDayInSameWeek(wd
);
1709 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1714 #if WXWIN_COMPATIBILITY_2_6
1715 // use a separate function to avoid warnings about using deprecated
1716 // SetToTheWeek in GetWeek below
1718 SetToTheWeek(int year
,
1719 wxDateTime::wxDateTime_t numWeek
,
1720 wxDateTime::WeekDay weekday
,
1721 wxDateTime::WeekFlags flags
)
1723 // Jan 4 always lies in the 1st week of the year
1724 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1725 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1726 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1731 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1735 int year
= GetYear();
1736 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1737 if ( GetYear() != year
)
1739 // oops... numWeek was too big
1746 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1748 WeekFlags flags
) const
1750 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1752 #endif // WXWIN_COMPATIBILITY_2_6
1754 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1757 // take the current month/year if none specified
1758 if ( year
== Inv_Year
)
1760 if ( month
== Inv_Month
)
1763 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1766 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1768 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1770 int wdayDst
= weekday
,
1771 wdayThis
= GetWeekDay();
1772 if ( wdayDst
== wdayThis
)
1778 if ( flags
== Default_First
)
1780 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1783 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1784 // is the first day in the week, but breaks down for Monday_First case so
1785 // we adjust the week days in this case
1786 if ( flags
== Monday_First
)
1788 if ( wdayThis
== Sun
)
1790 if ( wdayDst
== Sun
)
1793 //else: Sunday_First, nothing to do
1795 // go forward or back in time to the day we want
1796 if ( wdayDst
< wdayThis
)
1798 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1800 else // weekday > wdayThis
1802 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1806 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1808 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1811 WeekDay wdayThis
= GetWeekDay();
1812 if ( weekday
== wdayThis
)
1817 else if ( weekday
< wdayThis
)
1819 // need to advance a week
1820 diff
= 7 - (wdayThis
- weekday
);
1822 else // weekday > wdayThis
1824 diff
= weekday
- wdayThis
;
1827 return Add(wxDateSpan::Days(diff
));
1830 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1832 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1835 WeekDay wdayThis
= GetWeekDay();
1836 if ( weekday
== wdayThis
)
1841 else if ( weekday
> wdayThis
)
1843 // need to go to previous week
1844 diff
= 7 - (weekday
- wdayThis
);
1846 else // weekday < wdayThis
1848 diff
= wdayThis
- weekday
;
1851 return Subtract(wxDateSpan::Days(diff
));
1854 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1859 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1861 // we don't check explicitly that -5 <= n <= 5 because we will return false
1862 // anyhow in such case - but may be should still give an assert for it?
1864 // take the current month/year if none specified
1865 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1869 // TODO this probably could be optimised somehow...
1873 // get the first day of the month
1874 dt
.Set(1, month
, year
);
1877 WeekDay wdayFirst
= dt
.GetWeekDay();
1879 // go to the first weekday of the month
1880 int diff
= weekday
- wdayFirst
;
1884 // add advance n-1 weeks more
1887 dt
+= wxDateSpan::Days(diff
);
1889 else // count from the end of the month
1891 // get the last day of the month
1892 dt
.SetToLastMonthDay(month
, year
);
1895 WeekDay wdayLast
= dt
.GetWeekDay();
1897 // go to the last weekday of the month
1898 int diff
= wdayLast
- weekday
;
1902 // and rewind n-1 weeks from there
1905 dt
-= wxDateSpan::Days(diff
);
1908 // check that it is still in the same month
1909 if ( dt
.GetMonth() == month
)
1917 // no such day in this month
1923 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1925 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1928 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1930 return GetDayOfYearFromTm(GetTm(tz
));
1933 wxDateTime::wxDateTime_t
1934 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1936 if ( flags
== Default_First
)
1938 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1942 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1944 int wdTarget
= GetWeekDay(tz
);
1945 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1947 if ( flags
== Sunday_First
)
1949 // FIXME: First week is not calculated correctly.
1950 week
= (nDayInYear
- wdTarget
+ 7) / 7;
1951 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1954 else // week starts with monday
1956 // adjust the weekdays to non-US style.
1957 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
1958 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
1960 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
1962 // Week 01 of a year is per definition the first week that has the
1963 // Thursday in this year, which is equivalent to the week that
1964 // contains the fourth day of January. In other words, the first
1965 // week of a new year is the week that has the majority of its
1966 // days in the new year. Week 01 might also contain days from the
1967 // previous year and the week before week 01 of a year is the last
1968 // week (52 or 53) of the previous year even if it contains days
1969 // from the new year. A week starts with Monday (day 1) and ends
1970 // with Sunday (day 7).
1973 // if Jan 1 is Thursday or less, it is in the first week of this year
1974 if ( wdYearStart
< 4 )
1976 // count the number of entire weeks between Jan 1 and this date
1977 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
1979 // be careful to check for overflow in the next year
1980 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
1983 else // Jan 1 is in the last week of the previous year
1985 // check if we happen to be at the last week of previous year:
1986 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
1987 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
1989 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
1993 return (wxDateTime::wxDateTime_t
)week
;
1996 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1997 const TimeZone
& tz
) const
2000 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
2001 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
2003 if ( flags
== Default_First
)
2005 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2008 // compute offset of dateFirst from the beginning of the week
2010 if ( flags
== Sunday_First
)
2011 firstOffset
= wdFirst
- Sun
;
2013 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
2015 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
2018 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2020 int year
= GetYear();
2021 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2022 wxT("invalid year day") );
2024 bool isLeap
= IsLeapYear(year
);
2025 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2027 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2028 // don't need it neither - because of the CHECK above we know that
2029 // yday lies in December then
2030 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2032 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2041 // ----------------------------------------------------------------------------
2042 // Julian day number conversion and related stuff
2043 // ----------------------------------------------------------------------------
2045 double wxDateTime::GetJulianDayNumber() const
2047 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2050 double wxDateTime::GetRataDie() const
2052 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2053 return GetJulianDayNumber() - 1721119.5 - 306;
2056 // ----------------------------------------------------------------------------
2057 // timezone and DST stuff
2058 // ----------------------------------------------------------------------------
2060 int wxDateTime::IsDST(wxDateTime::Country country
) const
2062 wxCHECK_MSG( country
== Country_Default
, -1,
2063 wxT("country support not implemented") );
2065 // use the C RTL for the dates in the standard range
2066 time_t timet
= GetTicks();
2067 if ( timet
!= (time_t)-1 )
2070 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2072 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2074 return tm
->tm_isdst
;
2078 int year
= GetYear();
2080 if ( !IsDSTApplicable(year
, country
) )
2082 // no DST time in this year in this country
2086 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2090 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2092 long secDiff
= wxGetTimeZone() + tz
.GetOffset();
2094 // we need to know whether DST is or not in effect for this date unless
2095 // the test disabled by the caller
2096 if ( !noDST
&& (IsDST() == 1) )
2098 // FIXME we assume that the DST is always shifted by 1 hour
2102 return Add(wxTimeSpan::Seconds(secDiff
));
2105 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2107 long secDiff
= wxGetTimeZone() + tz
.GetOffset();
2109 // we need to know whether DST is or not in effect for this date unless
2110 // the test disabled by the caller
2111 if ( !noDST
&& (IsDST() == 1) )
2113 // FIXME we assume that the DST is always shifted by 1 hour
2117 return Subtract(wxTimeSpan::Seconds(secDiff
));
2120 // ============================================================================
2121 // wxDateTimeHolidayAuthority and related classes
2122 // ============================================================================
2124 #include "wx/arrimpl.cpp"
2126 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2128 static int wxCMPFUNC_CONV
2129 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2131 wxDateTime dt1
= **first
,
2134 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2137 // ----------------------------------------------------------------------------
2138 // wxDateTimeHolidayAuthority
2139 // ----------------------------------------------------------------------------
2141 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2144 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2146 size_t count
= ms_authorities
.size();
2147 for ( size_t n
= 0; n
< count
; n
++ )
2149 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2160 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2161 const wxDateTime
& dtEnd
,
2162 wxDateTimeArray
& holidays
)
2164 wxDateTimeArray hol
;
2168 const size_t countAuth
= ms_authorities
.size();
2169 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2171 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2173 WX_APPEND_ARRAY(holidays
, hol
);
2176 holidays
.Sort(wxDateTimeCompareFunc
);
2178 return holidays
.size();
2182 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2184 WX_CLEAR_ARRAY(ms_authorities
);
2188 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2190 ms_authorities
.push_back(auth
);
2193 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2195 // required here for Darwin
2198 // ----------------------------------------------------------------------------
2199 // wxDateTimeWorkDays
2200 // ----------------------------------------------------------------------------
2202 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2204 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2206 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2209 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2210 const wxDateTime
& dtEnd
,
2211 wxDateTimeArray
& holidays
) const
2213 if ( dtStart
> dtEnd
)
2215 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2222 // instead of checking all days, start with the first Sat after dtStart and
2223 // end with the last Sun before dtEnd
2224 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2225 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2226 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2227 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2230 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2235 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2240 return holidays
.GetCount();
2243 // ============================================================================
2244 // other helper functions
2245 // ============================================================================
2247 // ----------------------------------------------------------------------------
2248 // iteration helpers: can be used to write a for loop over enum variable like
2250 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2251 // ----------------------------------------------------------------------------
2253 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2255 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2257 // no wrapping or the for loop above would never end!
2258 m
= (wxDateTime::Month
)(m
+ 1);
2261 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2263 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2265 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2266 : (wxDateTime::Month
)(m
- 1);
2269 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2271 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2273 // no wrapping or the for loop above would never end!
2274 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2277 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2279 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2281 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2282 : (wxDateTime::WeekDay
)(wd
- 1);
2287 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2290 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2292 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2295 wxDateTime
& wxDateTime::SetFromMSWSysDate(const SYSTEMTIME
& st
)
2298 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2303 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2305 const wxDateTime::Tm
tm(GetTm());
2307 st
->wYear
= (WXWORD
)tm
.year
;
2308 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2312 st
->wHour
= tm
.hour
;
2313 st
->wMinute
= tm
.min
;
2314 st
->wSecond
= tm
.sec
;
2315 st
->wMilliseconds
= tm
.msec
;
2318 void wxDateTime::GetAsMSWSysDate(SYSTEMTIME
* st
) const
2320 const wxDateTime::Tm
tm(GetTm());
2322 st
->wYear
= (WXWORD
)tm
.year
;
2323 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2330 st
->wMilliseconds
= 0;
2335 #endif // wxUSE_DATETIME