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()
133 static long timezone
= MAXLONG
; // invalid timezone
134 if (timezone
== MAXLONG
)
138 timezone
= tb
.timezone
;
142 #define WX_TIMEZONE wxGetTimeZone()
143 #elif defined(__DARWIN__)
144 #define WX_GMTOFF_IN_TM
145 #elif defined(__WXWINCE__) && defined(__VISUALC8__)
146 // _timezone is not present in dynamic run-time library
148 // Solution (1): use the function equivalent of _timezone
149 static long wxGetTimeZone()
151 static long s_Timezone
= MAXLONG
; // invalid timezone
152 if (s_Timezone
== MAXLONG
)
156 s_Timezone
= (long) t
;
160 #define WX_TIMEZONE wxGetTimeZone()
162 // Solution (2): using GetTimeZoneInformation
163 static long wxGetTimeZone()
165 static long timezone
= MAXLONG
; // invalid timezone
166 if (timezone
== MAXLONG
)
168 TIME_ZONE_INFORMATION tzi
;
169 ::GetTimeZoneInformation(&tzi
);
174 #define WX_TIMEZONE wxGetTimeZone()
176 // Old method using _timezone: this symbol doesn't exist in the dynamic run-time library (i.e. using /MD)
177 #define WX_TIMEZONE _timezone
179 #else // unknown platform - try timezone
180 #define WX_TIMEZONE timezone
182 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
184 // NB: VC8 safe time functions could/should be used for wxMSW as well probably
185 #if defined(__WXWINCE__) && defined(__VISUALC8__)
187 struct tm
*wxLocaltime_r(const time_t *t
, struct tm
* tm
)
190 return _localtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
193 struct tm
*wxGmtime_r(const time_t* t
, struct tm
* tm
)
196 return _gmtime64_s(tm
, &t64
) == 0 ? tm
: NULL
;
199 #else // !wxWinCE with VC8
201 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
202 static wxMutex timeLock
;
205 #ifndef HAVE_LOCALTIME_R
206 struct tm
*wxLocaltime_r(const time_t* ticks
, struct tm
* temp
)
208 #if wxUSE_THREADS && !defined(__WINDOWS__)
209 // No need to waste time with a mutex on windows since it's using
210 // thread local storage for localtime anyway.
211 wxMutexLocker
locker(timeLock
);
214 // Borland CRT crashes when passed 0 ticks for some reason, see SF bug 1704438
220 const tm
* const t
= localtime(ticks
);
224 memcpy(temp
, t
, sizeof(struct tm
));
227 #endif // !HAVE_LOCALTIME_R
229 #ifndef HAVE_GMTIME_R
230 struct tm
*wxGmtime_r(const time_t* ticks
, struct tm
* temp
)
232 #if wxUSE_THREADS && !defined(__WINDOWS__)
233 // No need to waste time with a mutex on windows since it's
234 // using thread local storage for gmtime anyway.
235 wxMutexLocker
locker(timeLock
);
243 const tm
* const t
= gmtime(ticks
);
247 memcpy(temp
, gmtime(ticks
), sizeof(struct tm
));
250 #endif // !HAVE_GMTIME_R
252 #endif // wxWinCE with VC8/other platforms
254 // ----------------------------------------------------------------------------
256 // ----------------------------------------------------------------------------
258 // debugging helper: just a convenient replacement of wxCHECK()
259 #define wxDATETIME_CHECK(expr, msg) \
260 wxCHECK2_MSG(expr, *this = wxInvalidDateTime; return *this, msg)
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 class wxDateTimeHolidaysModule
: public wxModule
269 virtual bool OnInit()
271 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
276 virtual void OnExit()
278 wxDateTimeHolidayAuthority::ClearAllAuthorities();
279 wxDateTimeHolidayAuthority::ms_authorities
.clear();
283 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
286 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
288 // ----------------------------------------------------------------------------
290 // ----------------------------------------------------------------------------
293 static const int MONTHS_IN_YEAR
= 12;
295 static const int SEC_PER_MIN
= 60;
297 static const int MIN_PER_HOUR
= 60;
299 static const int HOURS_PER_DAY
= 24;
301 static const long SECONDS_PER_DAY
= 86400l;
303 static const int DAYS_PER_WEEK
= 7;
305 static const long MILLISECONDS_PER_DAY
= 86400000l;
307 // this is the integral part of JDN of the midnight of Jan 1, 1970
308 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
309 static const long EPOCH_JDN
= 2440587l;
311 // these values are only used in asserts so don't define them if asserts are
312 // disabled to avoid warnings about unused static variables
314 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
315 // reference date for us) is Nov 24, 4714BC
316 static const int JDN_0_YEAR
= -4713;
317 static const int JDN_0_MONTH
= wxDateTime::Nov
;
318 static const int JDN_0_DAY
= 24;
319 #endif // wxDEBUG_LEVEL
321 // the constants used for JDN calculations
322 static const long JDN_OFFSET
= 32046l;
323 static const long DAYS_PER_5_MONTHS
= 153l;
324 static const long DAYS_PER_4_YEARS
= 1461l;
325 static const long DAYS_PER_400_YEARS
= 146097l;
327 // this array contains the cumulated number of days in all previous months for
328 // normal and leap years
329 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
331 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
332 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
335 const long wxDateTime::TIME_T_FACTOR
= 1000l;
337 // ----------------------------------------------------------------------------
339 // ----------------------------------------------------------------------------
341 const char *wxDefaultDateTimeFormat
= "%c";
342 const char *wxDefaultTimeSpanFormat
= "%H:%M:%S";
344 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
345 // indicate an invalid wxDateTime object
346 const wxDateTime wxDefaultDateTime
;
348 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
350 // ----------------------------------------------------------------------------
352 // ----------------------------------------------------------------------------
354 // debugger helper: this function can be called from a debugger to show what
355 // the date really is
356 extern const char *wxDumpDate(const wxDateTime
* dt
)
358 static char buf
[128];
360 wxString
fmt(dt
->Format("%Y-%m-%d (%a) %H:%M:%S"));
362 (fmt
+ " (" + dt
->GetValue().ToString() + " ticks)").ToAscii(),
368 // get the number of days in the given month of the given year
370 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
372 // the number of days in month in Julian/Gregorian calendar: the first line
373 // is for normal years, the second one is for the leap ones
374 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
376 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
377 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
380 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
383 // returns the time zone in the C sense, i.e. the difference UTC - local
385 // NOTE: not static because used by datetimefmt.cpp
388 // set to true when the timezone is set
389 static bool s_timezoneSet
= false;
390 static long gmtoffset
= LONG_MAX
; // invalid timezone
392 // ensure that the timezone variable is set by calling wxLocaltime_r
393 if ( !s_timezoneSet
)
395 // just call wxLocaltime_r() instead of figuring out whether this
396 // system supports tzset(), _tzset() or something else
400 wxLocaltime_r(&t
, &tm
);
401 s_timezoneSet
= true;
403 #ifdef WX_GMTOFF_IN_TM
404 // note that GMT offset is the opposite of time zone and so to return
405 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
406 // cases we have to negate it
407 gmtoffset
= -tm
.tm_gmtoff
;
408 #else // !WX_GMTOFF_IN_TM
409 gmtoffset
= WX_TIMEZONE
;
410 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
413 return (int)gmtoffset
;
416 // return the integral part of the JDN for the midnight of the given date (to
417 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
418 // noon of the previous day)
419 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
420 wxDateTime::Month mon
,
423 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
425 // check the date validity
427 (year
> JDN_0_YEAR
) ||
428 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
429 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
430 wxT("date out of range - can't convert to JDN")
433 // make the year positive to avoid problems with negative numbers division
436 // months are counted from March here
438 if ( mon
>= wxDateTime::Mar
)
448 // now we can simply add all the contributions together
449 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
450 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
451 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
456 #ifdef wxHAS_STRFTIME
458 // this function is a wrapper around strftime(3) adding error checking
459 // NOTE: not static because used by datetimefmt.cpp
460 wxString
CallStrftime(const wxString
& format
, const tm
* tm
)
463 // Create temp wxString here to work around mingw/cygwin bug 1046059
464 // http://sourceforge.net/tracker/?func=detail&atid=102435&aid=1046059&group_id=2435
467 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
469 // if the format is valid, buffer must be too small?
470 wxFAIL_MSG(wxT("strftime() failed"));
479 #endif // wxHAS_STRFTIME
481 // if year and/or month have invalid values, replace them with the current ones
482 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
483 wxDateTime::Month
*month
)
485 struct tm
*tmNow
= NULL
;
488 if ( *year
== wxDateTime::Inv_Year
)
490 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
492 *year
= 1900 + tmNow
->tm_year
;
495 if ( *month
== wxDateTime::Inv_Month
)
498 tmNow
= wxDateTime::GetTmNow(&tmstruct
);
500 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
504 // fill the struct tm with default values
505 // NOTE: not static because used by datetimefmt.cpp
506 void InitTm(struct tm
& tm
)
508 // struct tm may have etxra fields (undocumented and with unportable
509 // names) which, nevertheless, must be set to 0
510 memset(&tm
, 0, sizeof(struct tm
));
512 tm
.tm_mday
= 1; // mday 0 is invalid
513 tm
.tm_year
= 76; // any valid year
514 tm
.tm_isdst
= -1; // auto determine
517 // ============================================================================
518 // implementation of wxDateTime
519 // ============================================================================
521 // ----------------------------------------------------------------------------
523 // ----------------------------------------------------------------------------
527 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
528 mon
= wxDateTime::Inv_Month
;
530 hour
= min
= sec
= msec
= 0;
531 wday
= wxDateTime::Inv_WeekDay
;
534 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
538 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
539 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
540 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
541 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
542 mon
= (wxDateTime::Month
)tm
.tm_mon
;
543 year
= 1900 + tm
.tm_year
;
544 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
545 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
548 bool wxDateTime::Tm::IsValid() const
550 // we allow for the leap seconds, although we don't use them (yet)
551 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
552 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
553 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
556 void wxDateTime::Tm::ComputeWeekDay()
558 // compute the week day from day/month/year: we use the dumbest algorithm
559 // possible: just compute our JDN and then use the (simple to derive)
560 // formula: weekday = (JDN + 1.5) % 7
561 wday
= (wxDateTime::wxDateTime_t
)((GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
564 void wxDateTime::Tm::AddMonths(int monDiff
)
566 // normalize the months field
567 while ( monDiff
< -mon
)
571 monDiff
+= MONTHS_IN_YEAR
;
574 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
578 monDiff
-= MONTHS_IN_YEAR
;
581 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
583 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, wxT("logic error") );
585 // NB: we don't check here that the resulting date is valid, this function
586 // is private and the caller must check it if needed
589 void wxDateTime::Tm::AddDays(int dayDiff
)
591 // normalize the days field
592 while ( dayDiff
+ mday
< 1 )
596 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
599 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
600 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
602 mday
-= GetNumOfDaysInMonth(year
, mon
);
607 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
608 wxT("logic error") );
611 // ----------------------------------------------------------------------------
613 // ----------------------------------------------------------------------------
615 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
619 case wxDateTime::Local
:
620 // get the offset from C RTL: it returns the difference GMT-local
621 // while we want to have the offset _from_ GMT, hence the '-'
622 m_offset
= -GetTimeZone();
625 case wxDateTime::GMT_12
:
626 case wxDateTime::GMT_11
:
627 case wxDateTime::GMT_10
:
628 case wxDateTime::GMT_9
:
629 case wxDateTime::GMT_8
:
630 case wxDateTime::GMT_7
:
631 case wxDateTime::GMT_6
:
632 case wxDateTime::GMT_5
:
633 case wxDateTime::GMT_4
:
634 case wxDateTime::GMT_3
:
635 case wxDateTime::GMT_2
:
636 case wxDateTime::GMT_1
:
637 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
640 case wxDateTime::GMT0
:
641 case wxDateTime::GMT1
:
642 case wxDateTime::GMT2
:
643 case wxDateTime::GMT3
:
644 case wxDateTime::GMT4
:
645 case wxDateTime::GMT5
:
646 case wxDateTime::GMT6
:
647 case wxDateTime::GMT7
:
648 case wxDateTime::GMT8
:
649 case wxDateTime::GMT9
:
650 case wxDateTime::GMT10
:
651 case wxDateTime::GMT11
:
652 case wxDateTime::GMT12
:
653 case wxDateTime::GMT13
:
654 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
657 case wxDateTime::A_CST
:
658 // Central Standard Time in use in Australia = UTC + 9.5
659 m_offset
= 60l*(9*MIN_PER_HOUR
+ MIN_PER_HOUR
/2);
663 wxFAIL_MSG( wxT("unknown time zone") );
667 // ----------------------------------------------------------------------------
669 // ----------------------------------------------------------------------------
672 struct tm
*wxDateTime::GetTmNow(struct tm
*tmstruct
)
674 time_t t
= GetTimeNow();
675 return wxLocaltime_r(&t
, tmstruct
);
679 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
681 if ( year
== Inv_Year
)
682 year
= GetCurrentYear();
684 if ( cal
== Gregorian
)
686 // in Gregorian calendar leap years are those divisible by 4 except
687 // those divisible by 100 unless they're also divisible by 400
688 // (in some countries, like Russia and Greece, additional corrections
689 // exist, but they won't manifest themselves until 2700)
690 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
692 else if ( cal
== Julian
)
694 // in Julian calendar the rule is simpler
695 return year
% 4 == 0;
699 wxFAIL_MSG(wxT("unknown calendar"));
706 int wxDateTime::GetCentury(int year
)
708 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
712 int wxDateTime::ConvertYearToBC(int year
)
715 return year
> 0 ? year
: year
- 1;
719 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
724 return Now().GetYear();
727 wxFAIL_MSG(wxT("TODO"));
731 wxFAIL_MSG(wxT("unsupported calendar"));
739 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
744 return Now().GetMonth();
747 wxFAIL_MSG(wxT("TODO"));
751 wxFAIL_MSG(wxT("unsupported calendar"));
759 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
761 if ( year
== Inv_Year
)
763 // take the current year if none given
764 year
= GetCurrentYear();
771 return IsLeapYear(year
) ? 366 : 365;
774 wxFAIL_MSG(wxT("unsupported calendar"));
782 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
784 wxDateTime::Calendar cal
)
786 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, wxT("invalid month") );
788 if ( cal
== Gregorian
|| cal
== Julian
)
790 if ( year
== Inv_Year
)
792 // take the current year if none given
793 year
= GetCurrentYear();
796 return GetNumOfDaysInMonth(year
, month
);
800 wxFAIL_MSG(wxT("unsupported calendar"));
809 // helper function used by GetEnglish/WeekDayName(): returns 0 if flags is
810 // Name_Full and 1 if it is Name_Abbr or -1 if the flags is incorrect (and
811 // asserts in this case)
813 // the return value of this function is used as an index into 2D array
814 // containing full names in its first row and abbreviated ones in the 2nd one
815 int NameArrayIndexFromFlag(wxDateTime::NameFlags flags
)
819 case wxDateTime::Name_Full
:
822 case wxDateTime::Name_Abbr
:
826 wxFAIL_MSG( "unknown wxDateTime::NameFlags value" );
832 } // anonymous namespace
835 wxString
wxDateTime::GetEnglishMonthName(Month month
, NameFlags flags
)
837 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, "invalid month" );
839 static const char *monthNames
[2][MONTHS_IN_YEAR
] =
841 { "January", "February", "March", "April", "May", "June",
842 "July", "August", "September", "October", "November", "December" },
843 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
844 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
847 const int idx
= NameArrayIndexFromFlag(flags
);
851 return monthNames
[idx
][month
];
855 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
856 wxDateTime::NameFlags flags
)
858 #ifdef wxHAS_STRFTIME
859 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, wxT("invalid month") );
861 // notice that we must set all the fields to avoid confusing libc (GNU one
862 // gets confused to a crash if we don't do this)
867 return CallStrftime(flags
== Name_Abbr
? wxT("%b") : wxT("%B"), &tm
);
868 #else // !wxHAS_STRFTIME
869 return GetEnglishMonthName(month
, flags
);
870 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
874 wxString
wxDateTime::GetEnglishWeekDayName(WeekDay wday
, NameFlags flags
)
876 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
878 static const char *weekdayNames
[2][DAYS_PER_400_YEARS
] =
880 { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
882 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
885 const int idx
= NameArrayIndexFromFlag(flags
);
889 return weekdayNames
[idx
][wday
];
893 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
894 wxDateTime::NameFlags flags
)
896 #ifdef wxHAS_STRFTIME
897 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, wxT("invalid weekday") );
899 // take some arbitrary Sunday (but notice that the day should be such that
900 // after adding wday to it below we still have a valid date, e.g. don't
908 // and offset it by the number of days needed to get the correct wday
911 // call mktime() to normalize it...
914 // ... and call strftime()
915 return CallStrftime(flags
== Name_Abbr
? wxT("%a") : wxT("%A"), &tm
);
916 #else // !wxHAS_STRFTIME
917 return GetEnglishWeekDayName(wday
, flags
);
918 #endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
922 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
927 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
928 // and causes an assertion failed if the buffer is to small (which is good) - OR -
929 // if strftime does not return anything because the format string is invalid - OR -
930 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
931 // wxDateTime::ParseTime will try several different formats to parse the time.
932 // As a result, GetAmPmStrings might get called, even if the current locale
933 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
934 // assert, even though it is a perfectly legal use.
937 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
938 *am
= wxString(buffer
);
945 if (wxStrftime(buffer
, WXSIZEOF(buffer
), wxT("%p"), &tm
) > 0)
946 *pm
= wxString(buffer
);
953 // ----------------------------------------------------------------------------
954 // Country stuff: date calculations depend on the country (DST, work days,
955 // ...), so we need to know which rules to follow.
956 // ----------------------------------------------------------------------------
959 wxDateTime::Country
wxDateTime::GetCountry()
961 // TODO use LOCALE_ICOUNTRY setting under Win32
963 if ( ms_country
== Country_Unknown
)
965 // try to guess from the time zone name
966 time_t t
= time(NULL
);
968 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
970 wxString tz
= CallStrftime(wxT("%Z"), tm
);
971 if ( tz
== wxT("WET") || tz
== wxT("WEST") )
975 else if ( tz
== wxT("CET") || tz
== wxT("CEST") )
977 ms_country
= Country_EEC
;
979 else if ( tz
== wxT("MSK") || tz
== wxT("MSD") )
983 else if ( tz
== wxT("AST") || tz
== wxT("ADT") ||
984 tz
== wxT("EST") || tz
== wxT("EDT") ||
985 tz
== wxT("CST") || tz
== wxT("CDT") ||
986 tz
== wxT("MST") || tz
== wxT("MDT") ||
987 tz
== wxT("PST") || tz
== wxT("PDT") )
993 // well, choose a default one
999 #endif // !__WXWINCE__/__WXWINCE__
1005 void wxDateTime::SetCountry(wxDateTime::Country country
)
1007 ms_country
= country
;
1011 bool wxDateTime::IsWestEuropeanCountry(Country country
)
1013 if ( country
== Country_Default
)
1015 country
= GetCountry();
1018 return (Country_WesternEurope_Start
<= country
) &&
1019 (country
<= Country_WesternEurope_End
);
1022 // ----------------------------------------------------------------------------
1023 // DST calculations: we use 3 different rules for the West European countries,
1024 // USA and for the rest of the world. This is undoubtedly false for many
1025 // countries, but I lack the necessary info (and the time to gather it),
1026 // please add the other rules here!
1027 // ----------------------------------------------------------------------------
1030 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1032 if ( year
== Inv_Year
)
1034 // take the current year if none given
1035 year
= GetCurrentYear();
1038 if ( country
== Country_Default
)
1040 country
= GetCountry();
1047 // DST was first observed in the US and UK during WWI, reused
1048 // during WWII and used again since 1966
1049 return year
>= 1966 ||
1050 (year
>= 1942 && year
<= 1945) ||
1051 (year
== 1918 || year
== 1919);
1054 // assume that it started after WWII
1060 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1062 if ( year
== Inv_Year
)
1064 // take the current year if none given
1065 year
= GetCurrentYear();
1068 if ( country
== Country_Default
)
1070 country
= GetCountry();
1073 if ( !IsDSTApplicable(year
, country
) )
1075 return wxInvalidDateTime
;
1080 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1082 // DST begins at 1 a.m. GMT on the last Sunday of March
1083 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1086 wxFAIL_MSG( wxT("no last Sunday in March?") );
1089 dt
+= wxTimeSpan::Hours(1);
1091 else switch ( country
)
1098 // don't know for sure - assume it was in effect all year
1103 dt
.Set(1, Jan
, year
);
1107 // DST was installed Feb 2, 1942 by the Congress
1108 dt
.Set(2, Feb
, year
);
1111 // Oil embargo changed the DST period in the US
1113 dt
.Set(6, Jan
, 1974);
1117 dt
.Set(23, Feb
, 1975);
1121 // before 1986, DST begun on the last Sunday of April, but
1122 // in 1986 Reagan changed it to begin at 2 a.m. of the
1123 // first Sunday in April
1126 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1129 wxFAIL_MSG( wxT("no first Sunday in April?") );
1132 else if ( year
> 2006 )
1133 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1134 // Starting in 2007, daylight time begins in the United States on the
1135 // second Sunday in March and ends on the first Sunday in November
1137 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1140 wxFAIL_MSG( wxT("no second Sunday in March?") );
1145 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1148 wxFAIL_MSG( wxT("no first Sunday in April?") );
1152 dt
+= wxTimeSpan::Hours(2);
1154 // TODO what about timezone??
1160 // assume Mar 30 as the start of the DST for the rest of the world
1161 // - totally bogus, of course
1162 dt
.Set(30, Mar
, year
);
1169 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1171 if ( year
== Inv_Year
)
1173 // take the current year if none given
1174 year
= GetCurrentYear();
1177 if ( country
== Country_Default
)
1179 country
= GetCountry();
1182 if ( !IsDSTApplicable(year
, country
) )
1184 return wxInvalidDateTime
;
1189 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1191 // DST ends at 1 a.m. GMT on the last Sunday of October
1192 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1194 // weirder and weirder...
1195 wxFAIL_MSG( wxT("no last Sunday in October?") );
1198 dt
+= wxTimeSpan::Hours(1);
1200 else switch ( country
)
1207 // don't know for sure - assume it was in effect all year
1211 dt
.Set(31, Dec
, year
);
1215 // the time was reset after the end of the WWII
1216 dt
.Set(30, Sep
, year
);
1219 default: // default for switch (year)
1221 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1222 // Starting in 2007, daylight time begins in the United States on the
1223 // second Sunday in March and ends on the first Sunday in November
1225 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1228 wxFAIL_MSG( wxT("no first Sunday in November?") );
1233 // DST ends at 2 a.m. on the last Sunday of October
1235 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1237 // weirder and weirder...
1238 wxFAIL_MSG( wxT("no last Sunday in October?") );
1242 dt
+= wxTimeSpan::Hours(2);
1244 // TODO: what about timezone??
1248 default: // default for switch (country)
1249 // assume October 26th as the end of the DST - totally bogus too
1250 dt
.Set(26, Oct
, year
);
1256 // ----------------------------------------------------------------------------
1257 // constructors and assignment operators
1258 // ----------------------------------------------------------------------------
1260 // return the current time with ms precision
1261 /* static */ wxDateTime
wxDateTime::UNow()
1263 return wxDateTime(wxGetLocalTimeMillis());
1266 // the values in the tm structure contain the local time
1267 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1270 time_t timet
= mktime(&tm2
);
1272 if ( timet
== (time_t)-1 )
1274 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1275 // less than timezone - try to make it work for this case
1276 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1278 return Set((time_t)(
1280 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1281 tm2
.tm_min
* SEC_PER_MIN
+
1285 wxFAIL_MSG( wxT("mktime() failed") );
1287 *this = wxInvalidDateTime
;
1297 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1298 wxDateTime_t minute
,
1299 wxDateTime_t second
,
1300 wxDateTime_t millisec
)
1302 // we allow seconds to be 61 to account for the leap seconds, even if we
1303 // don't use them really
1304 wxDATETIME_CHECK( hour
< 24 &&
1308 wxT("Invalid time in wxDateTime::Set()") );
1310 // get the current date from system
1312 struct tm
*tm
= GetTmNow(&tmstruct
);
1314 wxDATETIME_CHECK( tm
, wxT("wxLocaltime_r() failed") );
1316 // make a copy so it isn't clobbered by the call to mktime() below
1321 tm1
.tm_min
= minute
;
1322 tm1
.tm_sec
= second
;
1324 // and the DST in case it changes on this date
1327 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1328 tm1
.tm_isdst
= tm2
.tm_isdst
;
1332 // and finally adjust milliseconds
1333 return SetMillisecond(millisec
);
1336 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1340 wxDateTime_t minute
,
1341 wxDateTime_t second
,
1342 wxDateTime_t millisec
)
1344 wxDATETIME_CHECK( hour
< 24 &&
1348 wxT("Invalid time in wxDateTime::Set()") );
1350 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1352 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1353 wxT("Invalid date in wxDateTime::Set()") );
1355 // the range of time_t type (inclusive)
1356 static const int yearMinInRange
= 1970;
1357 static const int yearMaxInRange
= 2037;
1359 // test only the year instead of testing for the exact end of the Unix
1360 // time_t range - it doesn't bring anything to do more precise checks
1361 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1363 // use the standard library version if the date is in range - this is
1364 // probably more efficient than our code
1366 tm
.tm_year
= year
- 1900;
1372 tm
.tm_isdst
= -1; // mktime() will guess it
1376 // and finally adjust milliseconds
1378 SetMillisecond(millisec
);
1384 // do time calculations ourselves: we want to calculate the number of
1385 // milliseconds between the given date and the epoch
1387 // get the JDN for the midnight of this day
1388 m_time
= GetTruncatedJDN(day
, month
, year
);
1389 m_time
-= EPOCH_JDN
;
1390 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1392 // JDN corresponds to GMT, we take localtime
1393 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1399 wxDateTime
& wxDateTime::Set(double jdn
)
1401 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1403 jdn
-= EPOCH_JDN
+ 0.5;
1405 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1407 // JDNs always are in UTC, so we don't need any adjustments for time zone
1412 wxDateTime
& wxDateTime::ResetTime()
1416 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1429 wxDateTime
wxDateTime::GetDateOnly() const
1436 return wxDateTime(tm
);
1439 // ----------------------------------------------------------------------------
1440 // DOS Date and Time Format functions
1441 // ----------------------------------------------------------------------------
1442 // the dos date and time value is an unsigned 32 bit value in the format:
1443 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1445 // Y = year offset from 1980 (0-127)
1447 // D = day of month (1-31)
1449 // m = minute (0-59)
1450 // s = bisecond (0-29) each bisecond indicates two seconds
1451 // ----------------------------------------------------------------------------
1453 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1458 long year
= ddt
& 0xFE000000;
1463 long month
= ddt
& 0x1E00000;
1468 long day
= ddt
& 0x1F0000;
1472 long hour
= ddt
& 0xF800;
1476 long minute
= ddt
& 0x7E0;
1480 long second
= ddt
& 0x1F;
1481 tm
.tm_sec
= second
* 2;
1483 return Set(mktime(&tm
));
1486 unsigned long wxDateTime::GetAsDOS() const
1489 time_t ticks
= GetTicks();
1491 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1492 wxCHECK_MSG( tm
, ULONG_MAX
, wxT("time can't be represented in DOS format") );
1494 long year
= tm
->tm_year
;
1498 long month
= tm
->tm_mon
;
1502 long day
= tm
->tm_mday
;
1505 long hour
= tm
->tm_hour
;
1508 long minute
= tm
->tm_min
;
1511 long second
= tm
->tm_sec
;
1514 ddt
= year
| month
| day
| hour
| minute
| second
;
1518 // ----------------------------------------------------------------------------
1519 // time_t <-> broken down time conversions
1520 // ----------------------------------------------------------------------------
1522 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1524 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1526 time_t time
= GetTicks();
1527 if ( time
!= (time_t)-1 )
1529 // use C RTL functions
1532 if ( tz
.GetOffset() == -GetTimeZone() )
1534 // we are working with local time
1535 tm
= wxLocaltime_r(&time
, &tmstruct
);
1537 // should never happen
1538 wxCHECK_MSG( tm
, Tm(), wxT("wxLocaltime_r() failed") );
1542 time
+= (time_t)tz
.GetOffset();
1543 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1544 int time2
= (int) time
;
1550 tm
= wxGmtime_r(&time
, &tmstruct
);
1552 // should never happen
1553 wxCHECK_MSG( tm
, Tm(), wxT("wxGmtime_r() failed") );
1557 tm
= (struct tm
*)NULL
;
1563 // adjust the milliseconds
1565 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1566 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1569 //else: use generic code below
1572 // remember the time and do the calculations with the date only - this
1573 // eliminates rounding errors of the floating point arithmetics
1575 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1577 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1579 // we want to always have positive time and timeMidnight to be really
1580 // the midnight before it
1583 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1586 timeMidnight
-= timeOnly
;
1588 // calculate the Gregorian date from JDN for the midnight of our date:
1589 // this will yield day, month (in 1..12 range) and year
1591 // actually, this is the JDN for the noon of the previous day
1592 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1594 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1596 wxASSERT_MSG( jdn
> -2, wxT("JDN out of range") );
1598 // calculate the century
1599 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1600 long century
= temp
/ DAYS_PER_400_YEARS
;
1602 // then the year and day of year (1 <= dayOfYear <= 366)
1603 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1604 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1605 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1607 // and finally the month and day of the month
1608 temp
= dayOfYear
* 5 - 3;
1609 long month
= temp
/ DAYS_PER_5_MONTHS
;
1610 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1612 // month is counted from March - convert to normal
1623 // year is offset by 4800
1626 // check that the algorithm gave us something reasonable
1627 wxASSERT_MSG( (0 < month
) && (month
<= 12), wxT("invalid month") );
1628 wxASSERT_MSG( (1 <= day
) && (day
< 32), wxT("invalid day") );
1630 // construct Tm from these values
1632 tm
.year
= (int)year
;
1633 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1634 tm
.mday
= (wxDateTime_t
)day
;
1635 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1636 timeOnly
-= tm
.msec
;
1637 timeOnly
/= 1000; // now we have time in seconds
1639 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1641 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1643 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1646 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1651 wxDateTime
& wxDateTime::SetYear(int year
)
1653 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1662 wxDateTime
& wxDateTime::SetMonth(Month month
)
1664 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1673 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1675 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1684 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1686 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1695 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1697 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1706 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1708 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1717 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1719 wxASSERT_MSG( IsValid(), wxT("invalid wxDateTime") );
1721 // we don't need to use GetTm() for this one
1722 m_time
-= m_time
% 1000l;
1723 m_time
+= millisecond
;
1728 // ----------------------------------------------------------------------------
1729 // wxDateTime arithmetics
1730 // ----------------------------------------------------------------------------
1732 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1736 tm
.year
+= diff
.GetYears();
1737 tm
.AddMonths(diff
.GetMonths());
1739 // check that the resulting date is valid
1740 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1742 // We suppose that when adding one month to Jan 31 we want to get Feb
1743 // 28 (or 29), i.e. adding a month to the last day of the month should
1744 // give the last day of the next month which is quite logical.
1746 // Unfortunately, there is no logic way to understand what should
1747 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1748 // We make it Feb 28 (last day too), but it is highly questionable.
1749 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1752 tm
.AddDays(diff
.GetTotalDays());
1756 wxASSERT_MSG( IsSameTime(tm
),
1757 wxT("Add(wxDateSpan) shouldn't modify time") );
1762 // ----------------------------------------------------------------------------
1763 // Weekday and monthday stuff
1764 // ----------------------------------------------------------------------------
1766 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1767 static inline int ConvertWeekDayToMondayBase(int wd
)
1769 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1774 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1776 wxASSERT_MSG( numWeek
> 0,
1777 wxT("invalid week number: weeks are counted from 1") );
1779 // Jan 4 always lies in the 1st week of the year
1780 wxDateTime
dt(4, Jan
, year
);
1781 dt
.SetToWeekDayInSameWeek(wd
);
1782 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1787 #if WXWIN_COMPATIBILITY_2_6
1788 // use a separate function to avoid warnings about using deprecated
1789 // SetToTheWeek in GetWeek below
1791 SetToTheWeek(int year
,
1792 wxDateTime::wxDateTime_t numWeek
,
1793 wxDateTime::WeekDay weekday
,
1794 wxDateTime::WeekFlags flags
)
1796 // Jan 4 always lies in the 1st week of the year
1797 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1798 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1799 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1804 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1808 int year
= GetYear();
1809 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1810 if ( GetYear() != year
)
1812 // oops... numWeek was too big
1819 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1821 WeekFlags flags
) const
1823 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1825 #endif // WXWIN_COMPATIBILITY_2_6
1827 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1830 // take the current month/year if none specified
1831 if ( year
== Inv_Year
)
1833 if ( month
== Inv_Month
)
1836 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1839 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1841 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1843 int wdayDst
= weekday
,
1844 wdayThis
= GetWeekDay();
1845 if ( wdayDst
== wdayThis
)
1851 if ( flags
== Default_First
)
1853 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1856 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1857 // is the first day in the week, but breaks down for Monday_First case so
1858 // we adjust the week days in this case
1859 if ( flags
== Monday_First
)
1861 if ( wdayThis
== Sun
)
1863 if ( wdayDst
== Sun
)
1866 //else: Sunday_First, nothing to do
1868 // go forward or back in time to the day we want
1869 if ( wdayDst
< wdayThis
)
1871 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1873 else // weekday > wdayThis
1875 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1879 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1881 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1884 WeekDay wdayThis
= GetWeekDay();
1885 if ( weekday
== wdayThis
)
1890 else if ( weekday
< wdayThis
)
1892 // need to advance a week
1893 diff
= 7 - (wdayThis
- weekday
);
1895 else // weekday > wdayThis
1897 diff
= weekday
- wdayThis
;
1900 return Add(wxDateSpan::Days(diff
));
1903 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1905 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, wxT("invalid weekday") );
1908 WeekDay wdayThis
= GetWeekDay();
1909 if ( weekday
== wdayThis
)
1914 else if ( weekday
> wdayThis
)
1916 // need to go to previous week
1917 diff
= 7 - (weekday
- wdayThis
);
1919 else // weekday < wdayThis
1921 diff
= wdayThis
- weekday
;
1924 return Subtract(wxDateSpan::Days(diff
));
1927 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1932 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, wxT("invalid weekday") );
1934 // we don't check explicitly that -5 <= n <= 5 because we will return false
1935 // anyhow in such case - but may be should still give an assert for it?
1937 // take the current month/year if none specified
1938 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1942 // TODO this probably could be optimised somehow...
1946 // get the first day of the month
1947 dt
.Set(1, month
, year
);
1950 WeekDay wdayFirst
= dt
.GetWeekDay();
1952 // go to the first weekday of the month
1953 int diff
= weekday
- wdayFirst
;
1957 // add advance n-1 weeks more
1960 dt
+= wxDateSpan::Days(diff
);
1962 else // count from the end of the month
1964 // get the last day of the month
1965 dt
.SetToLastMonthDay(month
, year
);
1968 WeekDay wdayLast
= dt
.GetWeekDay();
1970 // go to the last weekday of the month
1971 int diff
= wdayLast
- weekday
;
1975 // and rewind n-1 weeks from there
1978 dt
-= wxDateSpan::Days(diff
);
1981 // check that it is still in the same month
1982 if ( dt
.GetMonth() == month
)
1990 // no such day in this month
1996 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1998 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
2001 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
2003 return GetDayOfYearFromTm(GetTm(tz
));
2006 wxDateTime::wxDateTime_t
2007 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
2009 if ( flags
== Default_First
)
2011 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2015 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
2017 int wdTarget
= GetWeekDay(tz
);
2018 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
2020 if ( flags
== Sunday_First
)
2022 // FIXME: First week is not calculated correctly.
2023 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2024 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2027 else // week starts with monday
2029 // adjust the weekdays to non-US style.
2030 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2031 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2033 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2035 // Week 01 of a year is per definition the first week that has the
2036 // Thursday in this year, which is equivalent to the week that
2037 // contains the fourth day of January. In other words, the first
2038 // week of a new year is the week that has the majority of its
2039 // days in the new year. Week 01 might also contain days from the
2040 // previous year and the week before week 01 of a year is the last
2041 // week (52 or 53) of the previous year even if it contains days
2042 // from the new year. A week starts with Monday (day 1) and ends
2043 // with Sunday (day 7).
2046 // if Jan 1 is Thursday or less, it is in the first week of this year
2047 if ( wdYearStart
< 4 )
2049 // count the number of entire weeks between Jan 1 and this date
2050 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2052 // be careful to check for overflow in the next year
2053 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2056 else // Jan 1 is in the last week of the previous year
2058 // check if we happen to be at the last week of previous year:
2059 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2060 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2062 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2066 return (wxDateTime::wxDateTime_t
)week
;
2069 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2070 const TimeZone
& tz
) const
2073 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
2074 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
2077 // this may happen for January when Jan, 1 is the last week of the
2079 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
2082 return (wxDateTime::wxDateTime_t
)nWeek
;
2085 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2087 int year
= GetYear();
2088 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2089 wxT("invalid year day") );
2091 bool isLeap
= IsLeapYear(year
);
2092 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2094 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2095 // don't need it neither - because of the CHECK above we know that
2096 // yday lies in December then
2097 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2099 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2108 // ----------------------------------------------------------------------------
2109 // Julian day number conversion and related stuff
2110 // ----------------------------------------------------------------------------
2112 double wxDateTime::GetJulianDayNumber() const
2114 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2117 double wxDateTime::GetRataDie() const
2119 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2120 return GetJulianDayNumber() - 1721119.5 - 306;
2123 // ----------------------------------------------------------------------------
2124 // timezone and DST stuff
2125 // ----------------------------------------------------------------------------
2127 int wxDateTime::IsDST(wxDateTime::Country country
) const
2129 wxCHECK_MSG( country
== Country_Default
, -1,
2130 wxT("country support not implemented") );
2132 // use the C RTL for the dates in the standard range
2133 time_t timet
= GetTicks();
2134 if ( timet
!= (time_t)-1 )
2137 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2139 wxCHECK_MSG( tm
, -1, wxT("wxLocaltime_r() failed") );
2141 return tm
->tm_isdst
;
2145 int year
= GetYear();
2147 if ( !IsDSTApplicable(year
, country
) )
2149 // no DST time in this year in this country
2153 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2157 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2159 long secDiff
= GetTimeZone() + tz
.GetOffset();
2161 // we need to know whether DST is or not in effect for this date unless
2162 // the test disabled by the caller
2163 if ( !noDST
&& (IsDST() == 1) )
2165 // FIXME we assume that the DST is always shifted by 1 hour
2169 return Add(wxTimeSpan::Seconds(secDiff
));
2172 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2174 long secDiff
= GetTimeZone() + tz
.GetOffset();
2176 // we need to know whether DST is or not in effect for this date unless
2177 // the test disabled by the caller
2178 if ( !noDST
&& (IsDST() == 1) )
2180 // FIXME we assume that the DST is always shifted by 1 hour
2184 return Subtract(wxTimeSpan::Seconds(secDiff
));
2187 // ============================================================================
2188 // wxDateTimeHolidayAuthority and related classes
2189 // ============================================================================
2191 #include "wx/arrimpl.cpp"
2193 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2195 static int wxCMPFUNC_CONV
2196 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2198 wxDateTime dt1
= **first
,
2201 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2204 // ----------------------------------------------------------------------------
2205 // wxDateTimeHolidayAuthority
2206 // ----------------------------------------------------------------------------
2208 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2211 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2213 size_t count
= ms_authorities
.size();
2214 for ( size_t n
= 0; n
< count
; n
++ )
2216 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2227 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2228 const wxDateTime
& dtEnd
,
2229 wxDateTimeArray
& holidays
)
2231 wxDateTimeArray hol
;
2235 const size_t countAuth
= ms_authorities
.size();
2236 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2238 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2240 WX_APPEND_ARRAY(holidays
, hol
);
2243 holidays
.Sort(wxDateTimeCompareFunc
);
2245 return holidays
.size();
2249 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2251 WX_CLEAR_ARRAY(ms_authorities
);
2255 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2257 ms_authorities
.push_back(auth
);
2260 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2262 // required here for Darwin
2265 // ----------------------------------------------------------------------------
2266 // wxDateTimeWorkDays
2267 // ----------------------------------------------------------------------------
2269 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2271 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2273 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2276 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2277 const wxDateTime
& dtEnd
,
2278 wxDateTimeArray
& holidays
) const
2280 if ( dtStart
> dtEnd
)
2282 wxFAIL_MSG( wxT("invalid date range in GetHolidaysInRange") );
2289 // instead of checking all days, start with the first Sat after dtStart and
2290 // end with the last Sun before dtEnd
2291 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2292 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2293 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2294 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2297 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2302 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2307 return holidays
.GetCount();
2310 // ============================================================================
2311 // other helper functions
2312 // ============================================================================
2314 // ----------------------------------------------------------------------------
2315 // iteration helpers: can be used to write a for loop over enum variable like
2317 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2318 // ----------------------------------------------------------------------------
2320 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2322 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2324 // no wrapping or the for loop above would never end!
2325 m
= (wxDateTime::Month
)(m
+ 1);
2328 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2330 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, wxT("invalid month") );
2332 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2333 : (wxDateTime::Month
)(m
- 1);
2336 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2338 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2340 // no wrapping or the for loop above would never end!
2341 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2344 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2346 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, wxT("invalid week day") );
2348 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2349 : (wxDateTime::WeekDay
)(wd
- 1);
2354 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2357 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2362 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2364 const wxDateTime::Tm
tm(GetTm());
2366 st
->wYear
= (WXWORD
)tm
.year
;
2367 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2374 st
->wMilliseconds
= 0;
2378 #endif // wxUSE_DATETIME