1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/datetime.cpp
3 // Purpose: implementation of time/date related classes
4 // (for formatting&parsing see datetimefmt.cpp)
5 // Author: Vadim Zeitlin
9 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // parts of code taken from sndcal library by Scott E. Lee:
12 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
13 // Permission granted to use, copy, modify, distribute and sell
14 // so long as the above copyright and this permission statement
15 // are retained in all copies.
17 // Licence: wxWindows licence
18 ///////////////////////////////////////////////////////////////////////////////
21 * Implementation notes:
23 * 1. the time is stored as a 64bit integer containing the signed number of
24 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
27 * 2. the range is thus something about 580 million years, but due to current
28 * algorithms limitations, only dates from Nov 24, 4714BC are handled
30 * 3. standard ANSI C functions are used to do time calculations whenever
31 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
33 * 4. otherwise, the calculations are done by converting the date to/from JDN
34 * first (the range limitation mentioned above comes from here: the
35 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
38 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
39 * this moment in local time and may be converted to the object
40 * corresponding to the same date/time in another time zone by using
43 * 6. the conversions to the current (or any other) timezone are done when the
44 * internal time representation is converted to the broken-down one in
48 // ============================================================================
50 // ============================================================================
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // For compilers that support precompilation, includes "wx.h".
57 #include "wx/wxprec.h"
63 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
67 #include "wx/msw/wrapwin.h"
69 #include "wx/string.h"
72 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
73 #include "wx/module.h"
77 #include "wx/thread.h"
78 #include "wx/tokenzr.h"
89 #include "wx/datetime.h"
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 #if wxUSE_EXTENDED_RTTI
97 template<> void wxStringReadValue(const wxString
&s
, wxDateTime
&data
)
99 data
.ParseFormat(s
,"%Y-%m-%d %H:%M:%S", NULL
);
102 template<> void wxStringWriteValue(wxString
&s
, const wxDateTime
&data
)
104 s
= data
.Format("%Y-%m-%d %H:%M:%S");
107 wxCUSTOM_TYPE_INFO(wxDateTime
, wxToStringConverter
<wxDateTime
> , wxFromStringConverter
<wxDateTime
>)
109 #endif // wxUSE_EXTENDED_RTTI
112 // ----------------------------------------------------------------------------
113 // conditional compilation
114 // ----------------------------------------------------------------------------
116 #if defined(__MWERKS__) && wxUSE_UNICODE
120 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
121 #if defined(__WXPALMOS__)
122 #define WX_GMTOFF_IN_TM
123 #elif defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
124 #define WX_TIMEZONE _timezone
125 #elif defined(__MWERKS__)
126 long wxmw_timezone
= 28800;
127 #define WX_TIMEZONE wxmw_timezone
128 #elif defined(__DJGPP__) || defined(__WINE__)
129 #include <sys/timeb.h>
131 static long wxGetTimeZone()
137 #define WX_TIMEZONE wxGetTimeZone()
138 #elif defined(__DARWIN__)
139 #define WX_GMTOFF_IN_TM
140 #elif wxCHECK_VISUALC_VERSION(8)
141 // While _timezone is still present in (some versions of) VC CRT, it's
142 // deprecated and _get_timezone() should be used instead.
143 static long wxGetTimeZone()
149 #define WX_TIMEZONE wxGetTimeZone()
150 #else // unknown platform - try timezone
151 #define WX_TIMEZONE timezone
153 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
155 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
156 #if defined(__WXWINCE__) && defined(__VISUALC8__)
158 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
161 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
164 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
167 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
170 #else // !wxWinCE with VC8
172 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
173 static wxMutex timeLock
;
176 #ifndef HAVE_LOCALTIME_R
177 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
179 #if wxUSE_THREADS && !defined(__WINDOWS__)
180 // No need to waste time with a mutex on windows since it's using
181 // thread local storage for localtime anyway.
182 wxMutexLocker
locker(timeLock
);
185 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
191 const tm
* const t
= localtime(ticks
);
195 memcpy(temp
, t
, sizeof(struct tm
));
198 #endif // !HAVE_LOCALTIME_R
200 #ifndef HAVE_GMTIME_R
201 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
203 #if wxUSE_THREADS && !defined(__WINDOWS__)
204 // No need to waste time with a mutex on windows since it's
205 // using thread local storage for gmtime anyway.
206 wxMutexLocker
locker(timeLock
);
214 const tm
* const t
= gmtime(ticks
);
218 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
221 #endif // !HAVE_GMTIME_R
223 #endif // wxWinCE with VC8/other platforms
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 // debugging helper: just a convenient replacement of wxCHECK()
230 #define wxDATETIME_CHECK(expr, msg) \
231 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
233 // ----------------------------------------------------------------------------
235 // ----------------------------------------------------------------------------
237 class wxDateTimeHolidaysModule
: public wxModule
240 virtual bool OnInit()
242 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
247 virtual void OnExit()
249 wxDateTimeHolidayAuthority::ClearAllAuthorities();
250 wxDateTimeHolidayAuthority::ms_authorities
.clear();
254 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
257 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
264 static const int MONTHS_IN_YEAR
= 12;
266 static const int SEC_PER_MIN
= 60;
268 static const int MIN_PER_HOUR
= 60;
270 static const long SECONDS_PER_DAY
= 86400l;
272 static const int DAYS_PER_WEEK
= 7;
274 static const long MILLISECONDS_PER_DAY
= 86400000l;
276 // this is the integral part of JDN of the midnight of Jan 1, 1970
277 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
278 static const long EPOCH_JDN
= 2440587l;
280 // these values are only used in asserts so don't define them if asserts are
281 // disabled to avoid warnings about unused static variables
283 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
284 // reference date for us) is Nov 24, 4714BC
285 static const int JDN_0_YEAR
= -4713;
286 static const int JDN_0_MONTH
= wxDateTime::Nov
;
287 static const int JDN_0_DAY
= 24;
288 #endif // wxDEBUG_LEVEL
290 // the constants used for JDN calculations
291 static const long JDN_OFFSET
= 32046l;
292 static const long DAYS_PER_5_MONTHS
= 153l;
293 static const long DAYS_PER_4_YEARS
= 1461l;
294 static const long DAYS_PER_400_YEARS
= 146097l;
296 // this array contains the cumulated number of days in all previous months for
297 // normal and leap years
298 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
300 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
301 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
304 const long wxDateTime::TIME_T_FACTOR
= 1000l;
306 // ----------------------------------------------------------------------------
308 // ----------------------------------------------------------------------------
310 const char wxDefaultDateTimeFormat
[] = "%c";
311 const char wxDefaultTimeSpanFormat
[] = "%H:%M:%S";
313 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
314 // indicate an invalid wxDateTime object
315 const wxDateTime wxDefaultDateTime
;
317 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
319 // ----------------------------------------------------------------------------
321 // ----------------------------------------------------------------------------
323 // debugger helper: this function can be called from a debugger to show what
324 // the date really is
325 extern const char *wxDumpDate(const wxDateTime
* dt
)
327 static char buf
[128];
329 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
331 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
337 // get the number of days in the given month of the given year
339 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
341 // the number of days in month in Julian/Gregorian calendar: the first line
342 // is for normal years, the second one is for the leap ones
343 static const wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
345 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
346 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
349 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
352 // returns the time zone in the C sense, i.e. the difference UTC - local
354 // NOTE: not static because used by datetimefmt.cpp
357 #ifdef WX_GMTOFF_IN_TM
358 // set to true when the timezone is set
359 static bool s_timezoneSet
= false;
360 static long gmtoffset
= LONG_MAX
; // invalid timezone
362 // ensure that the timezone variable is set by calling wxLocaltime_r
363 if ( !s_timezoneSet
)
365 // just call wxLocaltime_r() instead of figuring out whether this
366 // system supports tzset(), _tzset() or something else
370 wxLocaltime_r(&t
, &tm
);
371 s_timezoneSet
= true;
373 // note that GMT offset is the opposite of time zone and so to return
374 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
375 // cases we have to negate it
376 gmtoffset
= -tm
.tm_gmtoff
;
378 return (int)gmtoffset
;
379 #else // !WX_GMTOFF_IN_TM
381 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
384 // return the integral part of the JDN for the midnight of the given date (to
385 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
386 // noon of the previous day)
387 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
388 wxDateTime::Month mon
,
391 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
393 // check the date validity
395 (year
> JDN_0_YEAR
) ||
396 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
397 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
398 wxT("date out of range - can't convert to JDN")
401 // make the year positive to avoid problems with negative numbers division
404 // months are counted from March here
406 if ( mon
>= wxDateTime::Mar
)
416 // now we can simply add all the contributions together
417 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
418 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
419 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
424 #ifdef wxHAS_STRFTIME
426 // this function is a wrapper around strftime(3) adding error checking
427 // NOTE: not static because used by datetimefmt.cpp
428 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
431 // Create temp wxString here to work around mingw/cygwin bug 1046059
432 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
435 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
437 // if the format is valid, buffer must be too small?
438 wxFAIL_MSG(wxT("strftime() failed"));
447 #endif // wxHAS_STRFTIME
449 // if year and/or month have invalid values, replace them with the current ones
450 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
451 wxDateTime::Month
*month
)
453 struct tm
*tmNow
= NULL
;
456 if ( *year
== wxDateTime::Inv_Year
)
458 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
460 *year
= 1900 + tmNow
->tm_year
;
463 if ( *month
== wxDateTime::Inv_Month
)
466 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
468 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
472 // fill the struct tm with default values
473 // NOTE: not static because used by datetimefmt.cpp
474 void InitTm(struct tm
& tm
)
476 // struct tm may have etxra fields (undocumented and with unportable
477 // names) which, nevertheless, must be set to 0
478 memset(&tm
, 0, sizeof(struct tm
));
480 tm
.tm_mday
= 1; // mday 0 is invalid
481 tm
.tm_year
= 76; // any valid year
482 tm
.tm_isdst
= -1; // auto determine
485 // ============================================================================
486 // implementation of wxDateTime
487 // ============================================================================
489 // ----------------------------------------------------------------------------
491 // ----------------------------------------------------------------------------
495 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
496 mon
= wxDateTime::Inv_Month
;
503 wday
= wxDateTime::Inv_WeekDay
;
506 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
510 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
511 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
512 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
513 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
514 mon
= (wxDateTime::Month
)tm
.tm_mon
;
515 year
= 1900 + tm
.tm_year
;
516 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
517 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
520 bool wxDateTime::Tm::IsValid() const
522 if ( mon
== wxDateTime::Inv_Month
)
525 // We need to check this here to avoid crashing in GetNumOfDaysInMonth() if
526 // somebody passed us "(wxDateTime::Month)1000".
527 wxCHECK_MSG( mon
>= wxDateTime::Jan
&& mon
< wxDateTime::Inv_Month
, false,
528 wxS("Invalid month value") );
530 // we allow for the leap seconds, although we don't use them (yet)
531 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
532 (mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
533 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
536 void wxDateTime::Tm::ComputeWeekDay()
538 // compute the week day from day/month/year: we use the dumbest algorithm
539 // possible: just compute our JDN and then use the (simple to derive)
540 // formula: weekday = (JDN + 1.5) % 7
541 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
544 void wxDateTime::Tm::AddMonths(int monDiff
)
546 // normalize the months field
547 while ( monDiff
< -mon
)
551 monDiff
+= MONTHS_IN_YEAR
;
554 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
558 monDiff
-= MONTHS_IN_YEAR
;
561 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
563 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
565 // NB: we don't check here that the resulting date is valid, this function
566 // is private and the caller must check it if needed
569 void wxDateTime::Tm::AddDays(int dayDiff
)
571 // normalize the days field
572 while ( dayDiff
+ mday
< 1 )
576 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
579 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
580 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
582 mday
-= GetNumOfDaysInMonth(year
, mon
);
587 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
588 wxT("logic error") );
591 // ----------------------------------------------------------------------------
593 // ----------------------------------------------------------------------------
595 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
599 case wxDateTime::Local
:
600 // get the offset from C RTL: it returns the difference GMT-local
601 // while we want to have the offset _from_ GMT, hence the '-'
602 m_offset
= -GetTimeZone();
605 case wxDateTime::GMT_12
:
606 case wxDateTime::GMT_11
:
607 case wxDateTime::GMT_10
:
608 case wxDateTime::GMT_9
:
609 case wxDateTime::GMT_8
:
610 case wxDateTime::GMT_7
:
611 case wxDateTime::GMT_6
:
612 case wxDateTime::GMT_5
:
613 case wxDateTime::GMT_4
:
614 case wxDateTime::GMT_3
:
615 case wxDateTime::GMT_2
:
616 case wxDateTime::GMT_1
:
617 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
620 case wxDateTime::GMT0
:
621 case wxDateTime::GMT1
:
622 case wxDateTime::GMT2
:
623 case wxDateTime::GMT3
:
624 case wxDateTime::GMT4
:
625 case wxDateTime::GMT5
:
626 case wxDateTime::GMT6
:
627 case wxDateTime::GMT7
:
628 case wxDateTime::GMT8
:
629 case wxDateTime::GMT9
:
630 case wxDateTime::GMT10
:
631 case wxDateTime::GMT11
:
632 case wxDateTime::GMT12
:
633 case wxDateTime::GMT13
:
634 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
637 case wxDateTime::A_CST
:
638 // Central Standard Time in use in Australia = UTC + 9.5
639 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
643 wxFAIL_MSG( wxT("unknown time zone") );
647 // ----------------------------------------------------------------------------
649 // ----------------------------------------------------------------------------
652 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
654 time_t t
= GetTimeNow();
655 return wxLocaltime_r(&t
, tmstruct
);
659 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
661 if ( year
== Inv_Year
)
662 year
= GetCurrentYear();
664 if ( cal
== Gregorian
)
666 // in Gregorian calendar leap years are those divisible by 4 except
667 // those divisible by 100 unless they're also divisible by 400
668 // (in some countries, like Russia and Greece, additional corrections
669 // exist, but they won't manifest themselves until 2700)
670 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
672 else if ( cal
== Julian
)
674 // in Julian calendar the rule is simpler
675 return year
% 4 == 0;
679 wxFAIL_MSG(wxT("unknown calendar"));
686 int wxDateTime::GetCentury(int year
)
688 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
692 int wxDateTime::ConvertYearToBC(int year
)
695 return year
> 0 ? year
: year
- 1;
699 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
704 return Now().GetYear();
707 wxFAIL_MSG(wxT("TODO"));
711 wxFAIL_MSG(wxT("unsupported calendar"));
719 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
724 return Now().GetMonth();
727 wxFAIL_MSG(wxT("TODO"));
731 wxFAIL_MSG(wxT("unsupported calendar"));
739 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
741 if ( year
== Inv_Year
)
743 // take the current year if none given
744 year
= GetCurrentYear();
751 return IsLeapYear(year
) ? 366 : 365;
754 wxFAIL_MSG(wxT("unsupported calendar"));
762 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
764 wxDateTime::Calendar cal
)
766 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
768 if ( cal
== Gregorian
|| cal
== Julian
)
770 if ( year
== Inv_Year
)
772 // take the current year if none given
773 year
= GetCurrentYear();
776 return GetNumOfDaysInMonth(year
, month
);
780 wxFAIL_MSG(wxT("unsupported calendar"));
789 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
790 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
791 // asserts in this case)
793 // the return value of this function is used as an index into 2D array
794 // containing full names in its first row and abbreviated ones in the 2nd one
795 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
799 case wxDateTime::Name_Full
:
802 case wxDateTime::Name_Abbr
:
806 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
812 } // anonymous namespace
815 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
817 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
819 static const char *const monthNames
[2][MONTHS_IN_YEAR
] =
821 { "January", "February", "March", "April", "May", "June",
822 "July", "August", "September", "October", "November", "December" },
823 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
824 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
827 const int idx
= NameArrayIndexFromFlag(flags
);
831 return monthNames
[idx
][month
];
835 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
836 wxDateTime::NameFlags flags
)
838 #ifdef wxHAS_STRFTIME
839 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
841 // notice that we must set all the fields to avoid confusing libc (GNU one
842 // gets confused to a crash if we don't do this)
847 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
848 #else // !wxHAS_STRFTIME
849 return GetEnglishMonthName(month
, flags
);
850 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
854 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
856 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
858 static const char *const weekdayNames
[2][DAYS_PER_WEEK
] =
860 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
862 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
865 const int idx
= NameArrayIndexFromFlag(flags
);
869 return weekdayNames
[idx
][wday
];
873 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
874 wxDateTime::NameFlags flags
)
876 #ifdef wxHAS_STRFTIME
877 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
879 // take some arbitrary Sunday (but notice that the day should be such that
880 // after adding wday to it below we still have a valid date, e.g. don't
888 // and offset it by the number of days needed to get the correct wday
891 // call mktime() to normalize it...
894 // ... and call strftime()
895 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
896 #else // !wxHAS_STRFTIME
897 return GetEnglishWeekDayName(wday
, flags
);
898 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
902 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
907 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
908 // and causes an assertion failed if the buffer is to small (which is good) - OR -
909 // if strftime does not return anything because the format string is invalid - OR -
910 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
911 // wxDateTime::ParseTime will try several different formats to parse the time.
912 // As a result, GetAmPmStrings might get called, even if the current locale
913 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
914 // assert, even though it is a perfectly legal use.
917 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
918 *am
= wxString(buffer
);
925 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
926 *pm
= wxString(buffer
);
933 // ----------------------------------------------------------------------------
934 // Country stuff: date calculations depend on the country (DST, work days,
935 // ...), so we need to know which rules to follow.
936 // ----------------------------------------------------------------------------
939 wxDateTime::Country
wxDateTime::GetCountry()
941 // TODO use LOCALE_ICOUNTRY setting under Win32
943 if ( ms_country
== Country_Unknown
)
945 // try to guess from the time zone name
946 time_t t
= time(NULL
);
948 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
950 wxString tz
= CallStrftime(wxT("%Z"), tm
);
951 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
955 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
957 ms_country
= Country_EEC
;
959 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
963 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
964 tz
== wxT("EST") || tz
== wxT("EDT") ||
965 tz
== wxT("CST") || tz
== wxT("CDT") ||
966 tz
== wxT("MST") || tz
== wxT("MDT") ||
967 tz
== wxT("PST") || tz
== wxT("PDT") )
973 // well, choose a default one
979 #endif // !__WXWINCE__/__WXWINCE__
985 void wxDateTime::SetCountry(wxDateTime::Country country
)
987 ms_country
= country
;
991 bool wxDateTime::IsWestEuropeanCountry(Country country
)
993 if ( country
== Country_Default
)
995 country
= GetCountry();
998 return (Country_WesternEurope_Start
<= country
) &&
999 (country
<= Country_WesternEurope_End
);
1002 // ----------------------------------------------------------------------------
1003 // DST calculations: we use 3 different rules for the West European countries,
1004 // USA and for the rest of the world. This is undoubtedly false for many
1005 // countries, but I lack the necessary info (and the time to gather it),
1006 // please add the other rules here!
1007 // ----------------------------------------------------------------------------
1010 bool wxDateTime::IsDSTApplicable(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();
1027 // DST was first observed in the US and UK during WWI, reused
1028 // during WWII and used again since 1966
1029 return year
>= 1966 ||
1030 (year
>= 1942 && year
<= 1945) ||
1031 (year
== 1918 || year
== 1919);
1034 // assume that it started after WWII
1040 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1042 if ( year
== Inv_Year
)
1044 // take the current year if none given
1045 year
= GetCurrentYear();
1048 if ( country
== Country_Default
)
1050 country
= GetCountry();
1053 if ( !IsDSTApplicable(year
, country
) )
1055 return wxInvalidDateTime
;
1060 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1062 // DST begins at 1 a.m. GMT on the last Sunday of March
1063 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1066 wxFAIL_MSG( wxT("no last Sunday in March?") );
1069 dt
+= wxTimeSpan::Hours(1);
1071 else switch ( country
)
1078 // don't know for sure - assume it was in effect all year
1083 dt
.Set(1, Jan
, year
);
1087 // DST was installed Feb 2, 1942 by the Congress
1088 dt
.Set(2, Feb
, year
);
1091 // Oil embargo changed the DST period in the US
1093 dt
.Set(6, Jan
, 1974);
1097 dt
.Set(23, Feb
, 1975);
1101 // before 1986, DST begun on the last Sunday of April, but
1102 // in 1986 Reagan changed it to begin at 2 a.m. of the
1103 // first Sunday in April
1106 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1109 wxFAIL_MSG( wxT("no first Sunday in April?") );
1112 else if ( year
> 2006 )
1113 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1114 // Starting in 2007, daylight time begins in the United States on the
1115 // second Sunday in March and ends on the first Sunday in November
1117 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1120 wxFAIL_MSG( wxT("no second Sunday in March?") );
1125 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1128 wxFAIL_MSG( wxT("no first Sunday in April?") );
1132 dt
+= wxTimeSpan::Hours(2);
1134 // TODO what about timezone??
1140 // assume Mar 30 as the start of the DST for the rest of the world
1141 // - totally bogus, of course
1142 dt
.Set(30, Mar
, year
);
1149 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1151 if ( year
== Inv_Year
)
1153 // take the current year if none given
1154 year
= GetCurrentYear();
1157 if ( country
== Country_Default
)
1159 country
= GetCountry();
1162 if ( !IsDSTApplicable(year
, country
) )
1164 return wxInvalidDateTime
;
1169 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1171 // DST ends at 1 a.m. GMT on the last Sunday of October
1172 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1174 // weirder and weirder...
1175 wxFAIL_MSG( wxT("no last Sunday in October?") );
1178 dt
+= wxTimeSpan::Hours(1);
1180 else switch ( country
)
1187 // don't know for sure - assume it was in effect all year
1191 dt
.Set(31, Dec
, year
);
1195 // the time was reset after the end of the WWII
1196 dt
.Set(30, Sep
, year
);
1199 default: // default for switch (year)
1201 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1202 // Starting in 2007, daylight time begins in the United States on the
1203 // second Sunday in March and ends on the first Sunday in November
1205 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1208 wxFAIL_MSG( wxT("no first Sunday in November?") );
1213 // DST ends at 2 a.m. on the last Sunday of October
1215 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1217 // weirder and weirder...
1218 wxFAIL_MSG( wxT("no last Sunday in October?") );
1222 dt
+= wxTimeSpan::Hours(2);
1224 // TODO: what about timezone??
1228 default: // default for switch (country)
1229 // assume October 26th as the end of the DST - totally bogus too
1230 dt
.Set(26, Oct
, year
);
1236 // ----------------------------------------------------------------------------
1237 // constructors and assignment operators
1238 // ----------------------------------------------------------------------------
1240 // return the current time with ms precision
1241 /* static */ wxDateTime
wxDateTime::UNow()
1243 return wxDateTime(wxGetLocalTimeMillis());
1246 // the values in the tm structure contain the local time
1247 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1250 time_t timet
= mktime(&tm2
);
1252 if ( timet
== (time_t)-1 )
1254 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1255 // less than timezone - try to make it work for this case
1256 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1258 return Set((time_t)(
1260 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1261 tm2
.tm_min
* SEC_PER_MIN
+
1265 wxFAIL_MSG( wxT("mktime() failed") );
1267 *this = wxInvalidDateTime
;
1277 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1278 wxDateTime_t minute
,
1279 wxDateTime_t second
,
1280 wxDateTime_t millisec
)
1282 // we allow seconds to be 61 to account for the leap seconds, even if we
1283 // don't use them really
1284 wxDATETIME_CHECK( hour
< 24 &&
1288 wxT("Invalid time in wxDateTime::Set()") );
1290 // get the current date from system
1292 struct tm
*tm
= GetTmNow(&tmstruct
);
1294 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1296 // make a copy so it isn't clobbered by the call to mktime() below
1301 tm1
.tm_min
= minute
;
1302 tm1
.tm_sec
= second
;
1304 // and the DST in case it changes on this date
1307 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1308 tm1
.tm_isdst
= tm2
.tm_isdst
;
1312 // and finally adjust milliseconds
1313 return SetMillisecond(millisec
);
1316 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1320 wxDateTime_t minute
,
1321 wxDateTime_t second
,
1322 wxDateTime_t millisec
)
1324 wxDATETIME_CHECK( hour
< 24 &&
1328 wxT("Invalid time in wxDateTime::Set()") );
1330 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1332 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1333 wxT("Invalid date in wxDateTime::Set()") );
1335 // the range of time_t type (inclusive)
1336 static const int yearMinInRange
= 1970;
1337 static const int yearMaxInRange
= 2037;
1339 // test only the year instead of testing for the exact end of the Unix
1340 // time_t range - it doesn't bring anything to do more precise checks
1341 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1343 // use the standard library version if the date is in range - this is
1344 // probably more efficient than our code
1346 tm
.tm_year
= year
- 1900;
1352 tm
.tm_isdst
= -1; // mktime() will guess it
1356 // and finally adjust milliseconds
1358 SetMillisecond(millisec
);
1364 // do time calculations ourselves: we want to calculate the number of
1365 // milliseconds between the given date and the epoch
1367 // get the JDN for the midnight of this day
1368 m_time
= GetTruncatedJDN(day
, month
, year
);
1369 m_time
-= EPOCH_JDN
;
1370 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1372 // JDN corresponds to GMT, we take localtime
1373 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1379 wxDateTime
& wxDateTime::Set(double jdn
)
1381 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1383 jdn
-= EPOCH_JDN
+ 0.5;
1385 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1387 // JDNs always are in UTC, so we don't need any adjustments for time zone
1392 wxDateTime
& wxDateTime::ResetTime()
1396 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1409 wxDateTime
wxDateTime::GetDateOnly() const
1416 return wxDateTime(tm
);
1419 // ----------------------------------------------------------------------------
1420 // DOS Date and Time Format functions
1421 // ----------------------------------------------------------------------------
1422 // the dos date and time value is an unsigned 32 bit value in the format:
1423 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1425 // Y = year offset from 1980 (0-127)
1427 // D = day of month (1-31)
1429 // m = minute (0-59)
1430 // s = bisecond (0-29) each bisecond indicates two seconds
1431 // ----------------------------------------------------------------------------
1433 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1438 long year
= ddt
& 0xFE000000;
1443 long month
= ddt
& 0x1E00000;
1448 long day
= ddt
& 0x1F0000;
1452 long hour
= ddt
& 0xF800;
1456 long minute
= ddt
& 0x7E0;
1460 long second
= ddt
& 0x1F;
1461 tm
.tm_sec
= second
* 2;
1463 return Set(mktime(&tm
));
1466 unsigned long wxDateTime::GetAsDOS() const
1469 time_t ticks
= GetTicks();
1471 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1472 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1474 long year
= tm
->tm_year
;
1478 long month
= tm
->tm_mon
;
1482 long day
= tm
->tm_mday
;
1485 long hour
= tm
->tm_hour
;
1488 long minute
= tm
->tm_min
;
1491 long second
= tm
->tm_sec
;
1494 ddt
= year
| month
| day
| hour
| minute
| second
;
1498 // ----------------------------------------------------------------------------
1499 // time_t <-> broken down time conversions
1500 // ----------------------------------------------------------------------------
1502 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1504 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1506 time_t time
= GetTicks();
1507 if ( time
!= (time_t)-1 )
1509 // use C RTL functions
1512 if ( tz
.GetOffset() == -GetTimeZone() )
1514 // we are working with local time
1515 tm
= wxLocaltime_r(&time
, &tmstruct
);
1517 // should never happen
1518 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1522 time
+= (time_t)tz
.GetOffset();
1523 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1524 int time2
= (int) time
;
1530 tm
= wxGmtime_r(&time
, &tmstruct
);
1532 // should never happen
1533 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1537 tm
= (struct tm
*)NULL
;
1543 // adjust the milliseconds
1545 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1546 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1549 //else: use generic code below
1552 // remember the time and do the calculations with the date only - this
1553 // eliminates rounding errors of the floating point arithmetics
1555 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1557 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1559 // we want to always have positive time and timeMidnight to be really
1560 // the midnight before it
1563 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1566 timeMidnight
-= timeOnly
;
1568 // calculate the Gregorian date from JDN for the midnight of our date:
1569 // this will yield day, month (in 1..12 range) and year
1571 // actually, this is the JDN for the noon of the previous day
1572 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1574 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1576 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1578 // calculate the century
1579 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1580 long century
= temp
/ DAYS_PER_400_YEARS
;
1582 // then the year and day of year (1 <= dayOfYear <= 366)
1583 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1584 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1585 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1587 // and finally the month and day of the month
1588 temp
= dayOfYear
* 5 - 3;
1589 long month
= temp
/ DAYS_PER_5_MONTHS
;
1590 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1592 // month is counted from March - convert to normal
1603 // year is offset by 4800
1606 // check that the algorithm gave us something reasonable
1607 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1608 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1610 // construct Tm from these values
1612 tm
.year
= (int)year
;
1613 tm
.yday
= (wxDateTime_t
)(dayOfYear
- 1); // use C convention for day number
1614 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1615 tm
.mday
= (wxDateTime_t
)day
;
1616 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1617 timeOnly
-= tm
.msec
;
1618 timeOnly
/= 1000; // now we have time in seconds
1620 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1622 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1624 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1627 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1632 wxDateTime
& wxDateTime::SetYear(int year
)
1634 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1643 wxDateTime
& wxDateTime::SetMonth(Month month
)
1645 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1654 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1656 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1665 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1667 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1676 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1678 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1687 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1689 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1698 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1700 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1702 // we don't need to use GetTm() for this one
1703 m_time
-= m_time
% 1000l;
1704 m_time
+= millisecond
;
1709 // ----------------------------------------------------------------------------
1710 // wxDateTime arithmetics
1711 // ----------------------------------------------------------------------------
1713 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1717 tm
.year
+= diff
.GetYears();
1718 tm
.AddMonths(diff
.GetMonths());
1720 // check that the resulting date is valid
1721 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1723 // We suppose that when adding one month to Jan 31 we want to get Feb
1724 // 28 (or 29), i.e. adding a month to the last day of the month should
1725 // give the last day of the next month which is quite logical.
1727 // Unfortunately, there is no logic way to understand what should
1728 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1729 // We make it Feb 28 (last day too), but it is highly questionable.
1730 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1733 tm
.AddDays(diff
.GetTotalDays());
1737 wxASSERT_MSG( IsSameTime(tm
),
1738 wxT("Add(wxDateSpan) shouldn't modify time") );
1743 // ----------------------------------------------------------------------------
1744 // Weekday and monthday stuff
1745 // ----------------------------------------------------------------------------
1747 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1748 static inline int ConvertWeekDayToMondayBase(int wd
)
1750 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1755 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1757 wxASSERT_MSG( numWeek
> 0,
1758 wxT("invalid week number: weeks are counted from 1") );
1760 // Jan 4 always lies in the 1st week of the year
1761 wxDateTime
dt(4, Jan
, year
);
1762 dt
.SetToWeekDayInSameWeek(wd
);
1763 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1768 #if WXWIN_COMPATIBILITY_2_6
1769 // use a separate function to avoid warnings about using deprecated
1770 // SetToTheWeek in GetWeek below
1772 SetToTheWeek(int year
,
1773 wxDateTime::wxDateTime_t numWeek
,
1774 wxDateTime::WeekDay weekday
,
1775 wxDateTime::WeekFlags flags
)
1777 // Jan 4 always lies in the 1st week of the year
1778 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1779 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1780 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1785 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1789 int year
= GetYear();
1790 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1791 if ( GetYear() != year
)
1793 // oops... numWeek was too big
1800 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1802 WeekFlags flags
) const
1804 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1806 #endif // WXWIN_COMPATIBILITY_2_6
1808 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1811 // take the current month/year if none specified
1812 if ( year
== Inv_Year
)
1814 if ( month
== Inv_Month
)
1817 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1820 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1822 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1824 int wdayDst
= weekday
,
1825 wdayThis
= GetWeekDay();
1826 if ( wdayDst
== wdayThis
)
1832 if ( flags
== Default_First
)
1834 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1837 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1838 // is the first day in the week, but breaks down for Monday_First case so
1839 // we adjust the week days in this case
1840 if ( flags
== Monday_First
)
1842 if ( wdayThis
== Sun
)
1844 if ( wdayDst
== Sun
)
1847 //else: Sunday_First, nothing to do
1849 // go forward or back in time to the day we want
1850 if ( wdayDst
< wdayThis
)
1852 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1854 else // weekday > wdayThis
1856 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1860 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1862 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1865 WeekDay wdayThis
= GetWeekDay();
1866 if ( weekday
== wdayThis
)
1871 else if ( weekday
< wdayThis
)
1873 // need to advance a week
1874 diff
= 7 - (wdayThis
- weekday
);
1876 else // weekday > wdayThis
1878 diff
= weekday
- wdayThis
;
1881 return Add(wxDateSpan::Days(diff
));
1884 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1886 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1889 WeekDay wdayThis
= GetWeekDay();
1890 if ( weekday
== wdayThis
)
1895 else if ( weekday
> wdayThis
)
1897 // need to go to previous week
1898 diff
= 7 - (weekday
- wdayThis
);
1900 else // weekday < wdayThis
1902 diff
= wdayThis
- weekday
;
1905 return Subtract(wxDateSpan::Days(diff
));
1908 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1913 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1915 // we don't check explicitly that -5 <= n <= 5 because we will return false
1916 // anyhow in such case - but may be should still give an assert for it?
1918 // take the current month/year if none specified
1919 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1923 // TODO this probably could be optimised somehow...
1927 // get the first day of the month
1928 dt
.Set(1, month
, year
);
1931 WeekDay wdayFirst
= dt
.GetWeekDay();
1933 // go to the first weekday of the month
1934 int diff
= weekday
- wdayFirst
;
1938 // add advance n-1 weeks more
1941 dt
+= wxDateSpan::Days(diff
);
1943 else // count from the end of the month
1945 // get the last day of the month
1946 dt
.SetToLastMonthDay(month
, year
);
1949 WeekDay wdayLast
= dt
.GetWeekDay();
1951 // go to the last weekday of the month
1952 int diff
= wdayLast
- weekday
;
1956 // and rewind n-1 weeks from there
1959 dt
-= wxDateSpan::Days(diff
);
1962 // check that it is still in the same month
1963 if ( dt
.GetMonth() == month
)
1971 // no such day in this month
1977 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1979 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1982 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1984 return GetDayOfYearFromTm(GetTm(tz
));
1987 wxDateTime::wxDateTime_t
1988 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1990 if ( flags
== Default_First
)
1992 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1996 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1998 int wdTarget
= GetWeekDay(tz
);
1999 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
2001 if ( flags
== Sunday_First
)
2003 // FIXME: First week is not calculated correctly.
2004 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2005 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2008 else // week starts with monday
2010 // adjust the weekdays to non-US style.
2011 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2012 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2014 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2016 // Week 01 of a year is per definition the first week that has the
2017 // Thursday in this year, which is equivalent to the week that
2018 // contains the fourth day of January. In other words, the first
2019 // week of a new year is the week that has the majority of its
2020 // days in the new year. Week 01 might also contain days from the
2021 // previous year and the week before week 01 of a year is the last
2022 // week (52 or 53) of the previous year even if it contains days
2023 // from the new year. A week starts with Monday (day 1) and ends
2024 // with Sunday (day 7).
2027 // if Jan 1 is Thursday or less, it is in the first week of this year
2028 if ( wdYearStart
< 4 )
2030 // count the number of entire weeks between Jan 1 and this date
2031 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2033 // be careful to check for overflow in the next year
2034 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2037 else // Jan 1 is in the last week of the previous year
2039 // check if we happen to be at the last week of previous year:
2040 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2041 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2043 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2047 return (wxDateTime::wxDateTime_t
)week
;
2050 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2051 const TimeZone
& tz
) const
2054 const wxDateTime dateFirst
= wxDateTime(1, tm
.mon
, tm
.year
);
2055 const wxDateTime::WeekDay wdFirst
= dateFirst
.GetWeekDay();
2057 if ( flags
== Default_First
)
2059 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2062 // compute offset of dateFirst from the beginning of the week
2064 if ( flags
== Sunday_First
)
2065 firstOffset
= wdFirst
- Sun
;
2067 firstOffset
= wdFirst
== Sun
? DAYS_PER_WEEK
- 1 : wdFirst
- Mon
;
2069 return (wxDateTime::wxDateTime_t
)((tm
.mday
- 1 + firstOffset
)/7 + 1);
2072 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2074 int year
= GetYear();
2075 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2076 wxT("invalid year day") );
2078 bool isLeap
= IsLeapYear(year
);
2079 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2081 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2082 // don't need it neither - because of the CHECK above we know that
2083 // yday lies in December then
2084 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2086 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2095 // ----------------------------------------------------------------------------
2096 // Julian day number conversion and related stuff
2097 // ----------------------------------------------------------------------------
2099 double wxDateTime::GetJulianDayNumber() const
2101 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2104 double wxDateTime::GetRataDie() const
2106 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2107 return GetJulianDayNumber() - 1721119.5 - 306;
2110 // ----------------------------------------------------------------------------
2111 // timezone and DST stuff
2112 // ----------------------------------------------------------------------------
2114 int wxDateTime::IsDST(wxDateTime::Country country
) const
2116 wxCHECK_MSG( country
== Country_Default
, -1,
2117 wxT("country support not implemented") );
2119 // use the C RTL for the dates in the standard range
2120 time_t timet
= GetTicks();
2121 if ( timet
!= (time_t)-1 )
2124 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2126 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2128 return tm
->tm_isdst
;
2132 int year
= GetYear();
2134 if ( !IsDSTApplicable(year
, country
) )
2136 // no DST time in this year in this country
2140 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2144 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2146 long secDiff
= GetTimeZone() + tz
.GetOffset();
2148 // we need to know whether DST is or not in effect for this date unless
2149 // the test disabled by the caller
2150 if ( !noDST
&& (IsDST() == 1) )
2152 // FIXME we assume that the DST is always shifted by 1 hour
2156 return Add(wxTimeSpan::Seconds(secDiff
));
2159 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2161 long secDiff
= GetTimeZone() + tz
.GetOffset();
2163 // we need to know whether DST is or not in effect for this date unless
2164 // the test disabled by the caller
2165 if ( !noDST
&& (IsDST() == 1) )
2167 // FIXME we assume that the DST is always shifted by 1 hour
2171 return Subtract(wxTimeSpan::Seconds(secDiff
));
2174 // ============================================================================
2175 // wxDateTimeHolidayAuthority and related classes
2176 // ============================================================================
2178 #include "wx/arrimpl.cpp"
2180 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2182 static int wxCMPFUNC_CONV
2183 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2185 wxDateTime dt1
= **first
,
2188 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2191 // ----------------------------------------------------------------------------
2192 // wxDateTimeHolidayAuthority
2193 // ----------------------------------------------------------------------------
2195 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2198 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2200 size_t count
= ms_authorities
.size();
2201 for ( size_t n
= 0; n
< count
; n
++ )
2203 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2214 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2215 const wxDateTime
& dtEnd
,
2216 wxDateTimeArray
& holidays
)
2218 wxDateTimeArray hol
;
2222 const size_t countAuth
= ms_authorities
.size();
2223 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2225 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2227 WX_APPEND_ARRAY(holidays
, hol
);
2230 holidays
.Sort(wxDateTimeCompareFunc
);
2232 return holidays
.size();
2236 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2238 WX_CLEAR_ARRAY(ms_authorities
);
2242 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2244 ms_authorities
.push_back(auth
);
2247 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2249 // required here for Darwin
2252 // ----------------------------------------------------------------------------
2253 // wxDateTimeWorkDays
2254 // ----------------------------------------------------------------------------
2256 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2258 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2260 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2263 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2264 const wxDateTime
& dtEnd
,
2265 wxDateTimeArray
& holidays
) const
2267 if ( dtStart
> dtEnd
)
2269 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2276 // instead of checking all days, start with the first Sat after dtStart and
2277 // end with the last Sun before dtEnd
2278 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2279 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2280 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2281 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2284 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2289 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2294 return holidays
.GetCount();
2297 // ============================================================================
2298 // other helper functions
2299 // ============================================================================
2301 // ----------------------------------------------------------------------------
2302 // iteration helpers: can be used to write a for loop over enum variable like
2304 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2305 // ----------------------------------------------------------------------------
2307 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2309 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2311 // no wrapping or the for loop above would never end!
2312 m
= (wxDateTime::Month
)(m
+ 1);
2315 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2317 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2319 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2320 : (wxDateTime::Month
)(m
- 1);
2323 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2325 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2327 // no wrapping or the for loop above would never end!
2328 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2331 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2333 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2335 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2336 : (wxDateTime::WeekDay
)(wd
- 1);
2341 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2344 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2346 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
2349 wxDateTime
& wxDateTime::SetFromMSWSysDate(const SYSTEMTIME
& st
)
2352 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2357 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2359 const wxDateTime::Tm
tm(GetTm());
2361 st
->wYear
= (WXWORD
)tm
.year
;
2362 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2366 st
->wHour
= tm
.hour
;
2367 st
->wMinute
= tm
.min
;
2368 st
->wSecond
= tm
.sec
;
2369 st
->wMilliseconds
= tm
.msec
;
2372 void wxDateTime::GetAsMSWSysDate(SYSTEMTIME
* st
) const
2374 const wxDateTime::Tm
tm(GetTm());
2376 st
->wYear
= (WXWORD
)tm
.year
;
2377 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2384 st
->wMilliseconds
= 0;
2389 #endif // wxUSE_DATETIME