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 _T("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
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(_T("strftime() failed"));
479 #endif // HAVE_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
, _T("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
),
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( _T("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(_T("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(_T("TODO"));
731 wxFAIL_MSG(_T("unsupported calendar"));
739 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
744 return Now().GetMonth();
747 wxFAIL_MSG(_T("TODO"));
751 wxFAIL_MSG(_T("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(_T("unsupported calendar"));
782 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
784 wxDateTime::Calendar cal
)
786 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("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(_T("unsupported calendar"));
807 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
808 wxDateTime::NameFlags flags
)
810 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, _T("invalid month") );
812 // notice that we must set all the fields to avoid confusing libc (GNU one
813 // gets confused to a crash if we don't do this)
818 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
819 #else // !HAVE_STRFTIME
824 ret
= (flags
== Name_Abbr
? wxT("Jan"): wxT("January"));
827 ret
= (flags
== Name_Abbr
? wxT("Feb"): wxT("Febuary"));
830 ret
= (flags
== Name_Abbr
? wxT("Mar"): wxT("March"));
833 ret
= (flags
== Name_Abbr
? wxT("Apr"): wxT("April"));
836 ret
= (flags
== Name_Abbr
? wxT("May"): wxT("May"));
839 ret
= (flags
== Name_Abbr
? wxT("Jun"): wxT("June"));
842 ret
= (flags
== Name_Abbr
? wxT("Jul"): wxT("July"));
845 ret
= (flags
== Name_Abbr
? wxT("Aug"): wxT("August"));
848 ret
= (flags
== Name_Abbr
? wxT("Sep"): wxT("September"));
851 ret
= (flags
== Name_Abbr
? wxT("Oct"): wxT("October"));
854 ret
= (flags
== Name_Abbr
? wxT("Nov"): wxT("November"));
857 ret
= (flags
== Name_Abbr
? wxT("Dec"): wxT("December"));
861 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
865 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
866 wxDateTime::NameFlags flags
)
868 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, _T("invalid weekday") );
870 // take some arbitrary Sunday (but notice that the day should be such that
871 // after adding wday to it below we still have a valid date, e.g. don't
879 // and offset it by the number of days needed to get the correct wday
882 // call mktime() to normalize it...
885 // ... and call strftime()
886 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
887 #else // !HAVE_STRFTIME
892 ret
= (flags
== Name_Abbr
? wxT("Sun") : wxT("Sunday"));
895 ret
= (flags
== Name_Abbr
? wxT("Mon") : wxT("Monday"));
898 ret
= (flags
== Name_Abbr
? wxT("Tue") : wxT("Tuesday"));
901 ret
= (flags
== Name_Abbr
? wxT("Wed") : wxT("Wednesday"));
904 ret
= (flags
== Name_Abbr
? wxT("Thu") : wxT("Thursday"));
907 ret
= (flags
== Name_Abbr
? wxT("Fri") : wxT("Friday"));
910 ret
= (flags
== Name_Abbr
? wxT("Sat") : wxT("Saturday"));
914 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
918 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
923 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
924 // and causes an assertion failed if the buffer is to small (which is good) - OR -
925 // if strftime does not return anything because the format string is invalid - OR -
926 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
927 // wxDateTime::ParseTime will try several different formats to parse the time.
928 // As a result, GetAmPmStrings might get called, even if the current locale
929 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
930 // assert, even though it is a perfectly legal use.
933 if (wxStrftime(buffer
, sizeof(buffer
)/sizeof(wxChar
), _T("%p"), &tm
) > 0)
934 *am
= wxString(buffer
);
941 if (wxStrftime(buffer
, sizeof(buffer
)/sizeof(wxChar
), _T("%p"), &tm
) > 0)
942 *pm
= wxString(buffer
);
949 // ----------------------------------------------------------------------------
950 // Country stuff: date calculations depend on the country (DST, work days,
951 // ...), so we need to know which rules to follow.
952 // ----------------------------------------------------------------------------
955 wxDateTime::Country
wxDateTime::GetCountry()
957 // TODO use LOCALE_ICOUNTRY setting under Win32
959 if ( ms_country
== Country_Unknown
)
961 // try to guess from the time zone name
962 time_t t
= time(NULL
);
964 struct tm
*tm
= wxLocaltime_r(&t
, &tmstruct
);
966 wxString tz
= CallStrftime(_T("%Z"), tm
);
967 if ( tz
== _T("WET") || tz
== _T("WEST") )
971 else if ( tz
== _T("CET") || tz
== _T("CEST") )
973 ms_country
= Country_EEC
;
975 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
979 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
980 tz
== _T("EST") || tz
== _T("EDT") ||
981 tz
== _T("CST") || tz
== _T("CDT") ||
982 tz
== _T("MST") || tz
== _T("MDT") ||
983 tz
== _T("PST") || tz
== _T("PDT") )
989 // well, choose a default one
995 #endif // !__WXWINCE__/__WXWINCE__
1001 void wxDateTime::SetCountry(wxDateTime::Country country
)
1003 ms_country
= country
;
1007 bool wxDateTime::IsWestEuropeanCountry(Country country
)
1009 if ( country
== Country_Default
)
1011 country
= GetCountry();
1014 return (Country_WesternEurope_Start
<= country
) &&
1015 (country
<= Country_WesternEurope_End
);
1018 // ----------------------------------------------------------------------------
1019 // DST calculations: we use 3 different rules for the West European countries,
1020 // USA and for the rest of the world. This is undoubtedly false for many
1021 // countries, but I lack the necessary info (and the time to gather it),
1022 // please add the other rules here!
1023 // ----------------------------------------------------------------------------
1026 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1028 if ( year
== Inv_Year
)
1030 // take the current year if none given
1031 year
= GetCurrentYear();
1034 if ( country
== Country_Default
)
1036 country
= GetCountry();
1043 // DST was first observed in the US and UK during WWI, reused
1044 // during WWII and used again since 1966
1045 return year
>= 1966 ||
1046 (year
>= 1942 && year
<= 1945) ||
1047 (year
== 1918 || year
== 1919);
1050 // assume that it started after WWII
1056 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1058 if ( year
== Inv_Year
)
1060 // take the current year if none given
1061 year
= GetCurrentYear();
1064 if ( country
== Country_Default
)
1066 country
= GetCountry();
1069 if ( !IsDSTApplicable(year
, country
) )
1071 return wxInvalidDateTime
;
1076 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1078 // DST begins at 1 a.m. GMT on the last Sunday of March
1079 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1082 wxFAIL_MSG( _T("no last Sunday in March?") );
1085 dt
+= wxTimeSpan::Hours(1);
1087 else switch ( country
)
1094 // don't know for sure - assume it was in effect all year
1099 dt
.Set(1, Jan
, year
);
1103 // DST was installed Feb 2, 1942 by the Congress
1104 dt
.Set(2, Feb
, year
);
1107 // Oil embargo changed the DST period in the US
1109 dt
.Set(6, Jan
, 1974);
1113 dt
.Set(23, Feb
, 1975);
1117 // before 1986, DST begun on the last Sunday of April, but
1118 // in 1986 Reagan changed it to begin at 2 a.m. of the
1119 // first Sunday in April
1122 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1125 wxFAIL_MSG( _T("no first Sunday in April?") );
1128 else if ( year
> 2006 )
1129 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1130 // Starting in 2007, daylight time begins in the United States on the
1131 // second Sunday in March and ends on the first Sunday in November
1133 if ( !dt
.SetToWeekDay(Sun
, 2, Mar
, year
) )
1136 wxFAIL_MSG( _T("no second Sunday in March?") );
1141 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1144 wxFAIL_MSG( _T("no first Sunday in April?") );
1148 dt
+= wxTimeSpan::Hours(2);
1150 // TODO what about timezone??
1156 // assume Mar 30 as the start of the DST for the rest of the world
1157 // - totally bogus, of course
1158 dt
.Set(30, Mar
, year
);
1165 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1167 if ( year
== Inv_Year
)
1169 // take the current year if none given
1170 year
= GetCurrentYear();
1173 if ( country
== Country_Default
)
1175 country
= GetCountry();
1178 if ( !IsDSTApplicable(year
, country
) )
1180 return wxInvalidDateTime
;
1185 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1187 // DST ends at 1 a.m. GMT on the last Sunday of October
1188 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1190 // weirder and weirder...
1191 wxFAIL_MSG( _T("no last Sunday in October?") );
1194 dt
+= wxTimeSpan::Hours(1);
1196 else switch ( country
)
1203 // don't know for sure - assume it was in effect all year
1207 dt
.Set(31, Dec
, year
);
1211 // the time was reset after the end of the WWII
1212 dt
.Set(30, Sep
, year
);
1215 default: // default for switch (year)
1217 // Energy Policy Act of 2005, Pub. L. no. 109-58, 119 Stat 594 (2005).
1218 // Starting in 2007, daylight time begins in the United States on the
1219 // second Sunday in March and ends on the first Sunday in November
1221 if ( !dt
.SetToWeekDay(Sun
, 1, Nov
, year
) )
1224 wxFAIL_MSG( _T("no first Sunday in November?") );
1229 // DST ends at 2 a.m. on the last Sunday of October
1231 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1233 // weirder and weirder...
1234 wxFAIL_MSG( _T("no last Sunday in October?") );
1238 dt
+= wxTimeSpan::Hours(2);
1240 // TODO: what about timezone??
1244 default: // default for switch (country)
1245 // assume October 26th as the end of the DST - totally bogus too
1246 dt
.Set(26, Oct
, year
);
1252 // ----------------------------------------------------------------------------
1253 // constructors and assignment operators
1254 // ----------------------------------------------------------------------------
1256 // return the current time with ms precision
1257 /* static */ wxDateTime
wxDateTime::UNow()
1259 return wxDateTime(wxGetLocalTimeMillis());
1262 // the values in the tm structure contain the local time
1263 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1266 time_t timet
= mktime(&tm2
);
1268 if ( timet
== (time_t)-1 )
1270 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1271 // less than timezone - try to make it work for this case
1272 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1274 return Set((time_t)(
1276 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1277 tm2
.tm_min
* SEC_PER_MIN
+
1281 wxFAIL_MSG( _T("mktime() failed") );
1283 *this = wxInvalidDateTime
;
1293 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1294 wxDateTime_t minute
,
1295 wxDateTime_t second
,
1296 wxDateTime_t millisec
)
1298 // we allow seconds to be 61 to account for the leap seconds, even if we
1299 // don't use them really
1300 wxDATETIME_CHECK( hour
< 24 &&
1304 _T("Invalid time in wxDateTime::Set()") );
1306 // get the current date from system
1308 struct tm
*tm
= GetTmNow(&tmstruct
);
1310 wxDATETIME_CHECK( tm
, _T("wxLocaltime_r() failed") );
1312 // make a copy so it isn't clobbered by the call to mktime() below
1317 tm1
.tm_min
= minute
;
1318 tm1
.tm_sec
= second
;
1320 // and the DST in case it changes on this date
1323 if ( tm2
.tm_isdst
!= tm1
.tm_isdst
)
1324 tm1
.tm_isdst
= tm2
.tm_isdst
;
1328 // and finally adjust milliseconds
1329 return SetMillisecond(millisec
);
1332 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1336 wxDateTime_t minute
,
1337 wxDateTime_t second
,
1338 wxDateTime_t millisec
)
1340 wxDATETIME_CHECK( hour
< 24 &&
1344 _T("Invalid time in wxDateTime::Set()") );
1346 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1348 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1349 _T("Invalid date in wxDateTime::Set()") );
1351 // the range of time_t type (inclusive)
1352 static const int yearMinInRange
= 1970;
1353 static const int yearMaxInRange
= 2037;
1355 // test only the year instead of testing for the exact end of the Unix
1356 // time_t range - it doesn't bring anything to do more precise checks
1357 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1359 // use the standard library version if the date is in range - this is
1360 // probably more efficient than our code
1362 tm
.tm_year
= year
- 1900;
1368 tm
.tm_isdst
= -1; // mktime() will guess it
1372 // and finally adjust milliseconds
1374 SetMillisecond(millisec
);
1380 // do time calculations ourselves: we want to calculate the number of
1381 // milliseconds between the given date and the epoch
1383 // get the JDN for the midnight of this day
1384 m_time
= GetTruncatedJDN(day
, month
, year
);
1385 m_time
-= EPOCH_JDN
;
1386 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1388 // JDN corresponds to GMT, we take localtime
1389 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1395 wxDateTime
& wxDateTime::Set(double jdn
)
1397 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1399 jdn
-= EPOCH_JDN
+ 0.5;
1401 m_time
.Assign(jdn
*MILLISECONDS_PER_DAY
);
1403 // JDNs always are in UTC, so we don't need any adjustments for time zone
1408 wxDateTime
& wxDateTime::ResetTime()
1412 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1425 wxDateTime
wxDateTime::GetDateOnly() const
1432 return wxDateTime(tm
);
1435 // ----------------------------------------------------------------------------
1436 // DOS Date and Time Format functions
1437 // ----------------------------------------------------------------------------
1438 // the dos date and time value is an unsigned 32 bit value in the format:
1439 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1441 // Y = year offset from 1980 (0-127)
1443 // D = day of month (1-31)
1445 // m = minute (0-59)
1446 // s = bisecond (0-29) each bisecond indicates two seconds
1447 // ----------------------------------------------------------------------------
1449 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1454 long year
= ddt
& 0xFE000000;
1459 long month
= ddt
& 0x1E00000;
1464 long day
= ddt
& 0x1F0000;
1468 long hour
= ddt
& 0xF800;
1472 long minute
= ddt
& 0x7E0;
1476 long second
= ddt
& 0x1F;
1477 tm
.tm_sec
= second
* 2;
1479 return Set(mktime(&tm
));
1482 unsigned long wxDateTime::GetAsDOS() const
1485 time_t ticks
= GetTicks();
1487 struct tm
*tm
= wxLocaltime_r(&ticks
, &tmstruct
);
1488 wxCHECK_MSG( tm
, ULONG_MAX
, _T("time can't be represented in DOS format") );
1490 long year
= tm
->tm_year
;
1494 long month
= tm
->tm_mon
;
1498 long day
= tm
->tm_mday
;
1501 long hour
= tm
->tm_hour
;
1504 long minute
= tm
->tm_min
;
1507 long second
= tm
->tm_sec
;
1510 ddt
= year
| month
| day
| hour
| minute
| second
;
1514 // ----------------------------------------------------------------------------
1515 // time_t <-> broken down time conversions
1516 // ----------------------------------------------------------------------------
1518 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1520 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1522 time_t time
= GetTicks();
1523 if ( time
!= (time_t)-1 )
1525 // use C RTL functions
1528 if ( tz
.GetOffset() == -GetTimeZone() )
1530 // we are working with local time
1531 tm
= wxLocaltime_r(&time
, &tmstruct
);
1533 // should never happen
1534 wxCHECK_MSG( tm
, Tm(), _T("wxLocaltime_r() failed") );
1538 time
+= (time_t)tz
.GetOffset();
1539 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1540 int time2
= (int) time
;
1546 tm
= wxGmtime_r(&time
, &tmstruct
);
1548 // should never happen
1549 wxCHECK_MSG( tm
, Tm(), _T("wxGmtime_r() failed") );
1553 tm
= (struct tm
*)NULL
;
1559 // adjust the milliseconds
1561 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1562 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1565 //else: use generic code below
1568 // remember the time and do the calculations with the date only - this
1569 // eliminates rounding errors of the floating point arithmetics
1571 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1573 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1575 // we want to always have positive time and timeMidnight to be really
1576 // the midnight before it
1579 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1582 timeMidnight
-= timeOnly
;
1584 // calculate the Gregorian date from JDN for the midnight of our date:
1585 // this will yield day, month (in 1..12 range) and year
1587 // actually, this is the JDN for the noon of the previous day
1588 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1590 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1592 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1594 // calculate the century
1595 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1596 long century
= temp
/ DAYS_PER_400_YEARS
;
1598 // then the year and day of year (1 <= dayOfYear <= 366)
1599 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1600 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1601 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1603 // and finally the month and day of the month
1604 temp
= dayOfYear
* 5 - 3;
1605 long month
= temp
/ DAYS_PER_5_MONTHS
;
1606 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1608 // month is counted from March - convert to normal
1619 // year is offset by 4800
1622 // check that the algorithm gave us something reasonable
1623 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1624 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1626 // construct Tm from these values
1628 tm
.year
= (int)year
;
1629 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1630 tm
.mday
= (wxDateTime_t
)day
;
1631 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1632 timeOnly
-= tm
.msec
;
1633 timeOnly
/= 1000; // now we have time in seconds
1635 tm
.sec
= (wxDateTime_t
)(timeOnly
% SEC_PER_MIN
);
1637 timeOnly
/= SEC_PER_MIN
; // now we have time in minutes
1639 tm
.min
= (wxDateTime_t
)(timeOnly
% MIN_PER_HOUR
);
1642 tm
.hour
= (wxDateTime_t
)(timeOnly
/ MIN_PER_HOUR
);
1647 wxDateTime
& wxDateTime::SetYear(int year
)
1649 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1658 wxDateTime
& wxDateTime::SetMonth(Month month
)
1660 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1669 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1671 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1680 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1682 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1691 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1693 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1702 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1704 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1713 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1715 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1717 // we don't need to use GetTm() for this one
1718 m_time
-= m_time
% 1000l;
1719 m_time
+= millisecond
;
1724 // ----------------------------------------------------------------------------
1725 // wxDateTime arithmetics
1726 // ----------------------------------------------------------------------------
1728 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1732 tm
.year
+= diff
.GetYears();
1733 tm
.AddMonths(diff
.GetMonths());
1735 // check that the resulting date is valid
1736 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1738 // We suppose that when adding one month to Jan 31 we want to get Feb
1739 // 28 (or 29), i.e. adding a month to the last day of the month should
1740 // give the last day of the next month which is quite logical.
1742 // Unfortunately, there is no logic way to understand what should
1743 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1744 // We make it Feb 28 (last day too), but it is highly questionable.
1745 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1748 tm
.AddDays(diff
.GetTotalDays());
1752 wxASSERT_MSG( IsSameTime(tm
),
1753 _T("Add(wxDateSpan) shouldn't modify time") );
1758 // ----------------------------------------------------------------------------
1759 // Weekday and monthday stuff
1760 // ----------------------------------------------------------------------------
1762 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1763 static inline int ConvertWeekDayToMondayBase(int wd
)
1765 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1770 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1772 wxASSERT_MSG( numWeek
> 0,
1773 _T("invalid week number: weeks are counted from 1") );
1775 // Jan 4 always lies in the 1st week of the year
1776 wxDateTime
dt(4, Jan
, year
);
1777 dt
.SetToWeekDayInSameWeek(wd
);
1778 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1783 #if WXWIN_COMPATIBILITY_2_6
1784 // use a separate function to avoid warnings about using deprecated
1785 // SetToTheWeek in GetWeek below
1787 SetToTheWeek(int year
,
1788 wxDateTime::wxDateTime_t numWeek
,
1789 wxDateTime::WeekDay weekday
,
1790 wxDateTime::WeekFlags flags
)
1792 // Jan 4 always lies in the 1st week of the year
1793 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1794 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1795 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1800 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1804 int year
= GetYear();
1805 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1806 if ( GetYear() != year
)
1808 // oops... numWeek was too big
1815 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1817 WeekFlags flags
) const
1819 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1821 #endif // WXWIN_COMPATIBILITY_2_6
1823 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1826 // take the current month/year if none specified
1827 if ( year
== Inv_Year
)
1829 if ( month
== Inv_Month
)
1832 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1835 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1837 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1839 int wdayDst
= weekday
,
1840 wdayThis
= GetWeekDay();
1841 if ( wdayDst
== wdayThis
)
1847 if ( flags
== Default_First
)
1849 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1852 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1853 // is the first day in the week, but breaks down for Monday_First case so
1854 // we adjust the week days in this case
1855 if ( flags
== Monday_First
)
1857 if ( wdayThis
== Sun
)
1859 if ( wdayDst
== Sun
)
1862 //else: Sunday_First, nothing to do
1864 // go forward or back in time to the day we want
1865 if ( wdayDst
< wdayThis
)
1867 return Subtract(wxDateSpan::Days(wdayThis
- wdayDst
));
1869 else // weekday > wdayThis
1871 return Add(wxDateSpan::Days(wdayDst
- wdayThis
));
1875 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1877 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1880 WeekDay wdayThis
= GetWeekDay();
1881 if ( weekday
== wdayThis
)
1886 else if ( weekday
< wdayThis
)
1888 // need to advance a week
1889 diff
= 7 - (wdayThis
- weekday
);
1891 else // weekday > wdayThis
1893 diff
= weekday
- wdayThis
;
1896 return Add(wxDateSpan::Days(diff
));
1899 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1901 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1904 WeekDay wdayThis
= GetWeekDay();
1905 if ( weekday
== wdayThis
)
1910 else if ( weekday
> wdayThis
)
1912 // need to go to previous week
1913 diff
= 7 - (weekday
- wdayThis
);
1915 else // weekday < wdayThis
1917 diff
= wdayThis
- weekday
;
1920 return Subtract(wxDateSpan::Days(diff
));
1923 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1928 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, _T("invalid weekday") );
1930 // we don't check explicitly that -5 <= n <= 5 because we will return false
1931 // anyhow in such case - but may be should still give an assert for it?
1933 // take the current month/year if none specified
1934 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1938 // TODO this probably could be optimised somehow...
1942 // get the first day of the month
1943 dt
.Set(1, month
, year
);
1946 WeekDay wdayFirst
= dt
.GetWeekDay();
1948 // go to the first weekday of the month
1949 int diff
= weekday
- wdayFirst
;
1953 // add advance n-1 weeks more
1956 dt
+= wxDateSpan::Days(diff
);
1958 else // count from the end of the month
1960 // get the last day of the month
1961 dt
.SetToLastMonthDay(month
, year
);
1964 WeekDay wdayLast
= dt
.GetWeekDay();
1966 // go to the last weekday of the month
1967 int diff
= wdayLast
- weekday
;
1971 // and rewind n-1 weeks from there
1974 dt
-= wxDateSpan::Days(diff
);
1977 // check that it is still in the same month
1978 if ( dt
.GetMonth() == month
)
1986 // no such day in this month
1992 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1994 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1997 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1999 return GetDayOfYearFromTm(GetTm(tz
));
2002 wxDateTime::wxDateTime_t
2003 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
2005 if ( flags
== Default_First
)
2007 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
2011 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
2013 int wdTarget
= GetWeekDay(tz
);
2014 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
2016 if ( flags
== Sunday_First
)
2018 // FIXME: First week is not calculated correctly.
2019 week
= (nDayInYear
- wdTarget
+ 7) / 7;
2020 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
2023 else // week starts with monday
2025 // adjust the weekdays to non-US style.
2026 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
2027 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
2029 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
2031 // Week 01 of a year is per definition the first week that has the
2032 // Thursday in this year, which is equivalent to the week that
2033 // contains the fourth day of January. In other words, the first
2034 // week of a new year is the week that has the majority of its
2035 // days in the new year. Week 01 might also contain days from the
2036 // previous year and the week before week 01 of a year is the last
2037 // week (52 or 53) of the previous year even if it contains days
2038 // from the new year. A week starts with Monday (day 1) and ends
2039 // with Sunday (day 7).
2042 // if Jan 1 is Thursday or less, it is in the first week of this year
2043 if ( wdYearStart
< 4 )
2045 // count the number of entire weeks between Jan 1 and this date
2046 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2048 // be careful to check for overflow in the next year
2049 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2052 else // Jan 1 is in the last week of the previous year
2054 // check if we happen to be at the last week of previous year:
2055 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2056 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2058 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2062 return (wxDateTime::wxDateTime_t
)week
;
2065 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2066 const TimeZone
& tz
) const
2069 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
2070 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
2073 // this may happen for January when Jan, 1 is the last week of the
2075 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
2078 return (wxDateTime::wxDateTime_t
)nWeek
;
2081 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2083 int year
= GetYear();
2084 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2085 _T("invalid year day") );
2087 bool isLeap
= IsLeapYear(year
);
2088 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2090 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2091 // don't need it neither - because of the CHECK above we know that
2092 // yday lies in December then
2093 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2095 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2104 // ----------------------------------------------------------------------------
2105 // Julian day number conversion and related stuff
2106 // ----------------------------------------------------------------------------
2108 double wxDateTime::GetJulianDayNumber() const
2110 return m_time
.ToDouble() / MILLISECONDS_PER_DAY
+ EPOCH_JDN
+ 0.5;
2113 double wxDateTime::GetRataDie() const
2115 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2116 return GetJulianDayNumber() - 1721119.5 - 306;
2119 // ----------------------------------------------------------------------------
2120 // timezone and DST stuff
2121 // ----------------------------------------------------------------------------
2123 int wxDateTime::IsDST(wxDateTime::Country country
) const
2125 wxCHECK_MSG( country
== Country_Default
, -1,
2126 _T("country support not implemented") );
2128 // use the C RTL for the dates in the standard range
2129 time_t timet
= GetTicks();
2130 if ( timet
!= (time_t)-1 )
2133 tm
*tm
= wxLocaltime_r(&timet
, &tmstruct
);
2135 wxCHECK_MSG( tm
, -1, _T("wxLocaltime_r() failed") );
2137 return tm
->tm_isdst
;
2141 int year
= GetYear();
2143 if ( !IsDSTApplicable(year
, country
) )
2145 // no DST time in this year in this country
2149 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2153 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2155 long secDiff
= GetTimeZone() + tz
.GetOffset();
2157 // we need to know whether DST is or not in effect for this date unless
2158 // the test disabled by the caller
2159 if ( !noDST
&& (IsDST() == 1) )
2161 // FIXME we assume that the DST is always shifted by 1 hour
2165 return Add(wxTimeSpan::Seconds(secDiff
));
2168 wxDateTime
& wxDateTime::MakeFromTimezone(const TimeZone
& tz
, bool noDST
)
2170 long secDiff
= GetTimeZone() + tz
.GetOffset();
2172 // we need to know whether DST is or not in effect for this date unless
2173 // the test disabled by the caller
2174 if ( !noDST
&& (IsDST() == 1) )
2176 // FIXME we assume that the DST is always shifted by 1 hour
2180 return Subtract(wxTimeSpan::Seconds(secDiff
));
2183 // ============================================================================
2184 // wxDateTimeHolidayAuthority and related classes
2185 // ============================================================================
2187 #include "wx/arrimpl.cpp"
2189 WX_DEFINE_OBJARRAY(wxDateTimeArray
)
2191 static int wxCMPFUNC_CONV
2192 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
2194 wxDateTime dt1
= **first
,
2197 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
2200 // ----------------------------------------------------------------------------
2201 // wxDateTimeHolidayAuthority
2202 // ----------------------------------------------------------------------------
2204 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
2207 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
2209 size_t count
= ms_authorities
.size();
2210 for ( size_t n
= 0; n
< count
; n
++ )
2212 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
2223 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
2224 const wxDateTime
& dtEnd
,
2225 wxDateTimeArray
& holidays
)
2227 wxDateTimeArray hol
;
2231 const size_t countAuth
= ms_authorities
.size();
2232 for ( size_t nAuth
= 0; nAuth
< countAuth
; nAuth
++ )
2234 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
2236 WX_APPEND_ARRAY(holidays
, hol
);
2239 holidays
.Sort(wxDateTimeCompareFunc
);
2241 return holidays
.size();
2245 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
2247 WX_CLEAR_ARRAY(ms_authorities
);
2251 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
2253 ms_authorities
.push_back(auth
);
2256 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
2258 // required here for Darwin
2261 // ----------------------------------------------------------------------------
2262 // wxDateTimeWorkDays
2263 // ----------------------------------------------------------------------------
2265 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
2267 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
2269 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
2272 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
2273 const wxDateTime
& dtEnd
,
2274 wxDateTimeArray
& holidays
) const
2276 if ( dtStart
> dtEnd
)
2278 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
2285 // instead of checking all days, start with the first Sat after dtStart and
2286 // end with the last Sun before dtEnd
2287 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
2288 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
2289 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
2290 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
2293 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
2298 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
2303 return holidays
.GetCount();
2306 // ============================================================================
2307 // other helper functions
2308 // ============================================================================
2310 // ----------------------------------------------------------------------------
2311 // iteration helpers: can be used to write a for loop over enum variable like
2313 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
2314 // ----------------------------------------------------------------------------
2316 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
2318 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, _T("invalid month") );
2320 // no wrapping or the for loop above would never end!
2321 m
= (wxDateTime::Month
)(m
+ 1);
2324 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
2326 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, _T("invalid month") );
2328 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
2329 : (wxDateTime::Month
)(m
- 1);
2332 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
2334 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, _T("invalid week day") );
2336 // no wrapping or the for loop above would never end!
2337 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
2340 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
2342 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, _T("invalid week day") );
2344 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
2345 : (wxDateTime::WeekDay
)(wd
- 1);
2350 wxDateTime
& wxDateTime::SetFromMSWSysTime(const SYSTEMTIME
& st
)
2353 static_cast<wxDateTime::Month
>(wxDateTime::Jan
+ st
.wMonth
- 1),
2358 void wxDateTime::GetAsMSWSysTime(SYSTEMTIME
* st
) const
2360 const wxDateTime::Tm
tm(GetTm());
2362 st
->wYear
= (WXWORD
)tm
.year
;
2363 st
->wMonth
= (WXWORD
)(tm
.mon
- wxDateTime::Jan
+ 1);
2370 st
->wMilliseconds
= 0;
2374 #endif // wxUSE_DATETIME