1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows licence
17 ///////////////////////////////////////////////////////////////////////////////
20 * Implementation notes:
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
47 // ============================================================================
49 // ============================================================================
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
55 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
56 #pragma implementation "datetime.h"
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
66 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
69 #include "wx/string.h"
74 #include "wx/thread.h"
75 #include "wx/tokenzr.h"
76 #include "wx/module.h"
80 #include "wx/datetime.h"
81 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
83 const long wxDateTime::TIME_T_FACTOR
= 1000l;
85 #if wxUSE_EXTENDED_RTTI
87 template<> void wxStringReadValue(const wxString
&s
, wxDateTime
&data
)
89 data
.ParseFormat(s
,wxT("%Y-%m-%d %H:%M:%S")) ;
92 template<> void wxStringWriteValue(wxString
&s
, const wxDateTime
&data
)
94 s
= data
.Format(wxT("%Y-%m-%d %H:%M:%S")) ;
97 wxCUSTOM_TYPE_INFO(wxDateTime
, wxToStringConverter
<wxDateTime
> , wxFromStringConverter
<wxDateTime
>)
102 // ----------------------------------------------------------------------------
103 // conditional compilation
104 // ----------------------------------------------------------------------------
106 #if defined(HAVE_STRPTIME) && defined(__GLIBC__) && \
107 ((__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
108 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
109 // crash (instead of just failing):
111 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
112 // strptime(buf, "%x", &tm);
116 #endif // broken strptime()
118 #if defined(__MWERKS__) && wxUSE_UNICODE
122 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
123 #if 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 #else // unknown platform - try timezone
146 #define WX_TIMEZONE timezone
148 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
150 // ----------------------------------------------------------------------------
152 // ----------------------------------------------------------------------------
154 // debugging helper: just a convenient replacement of wxCHECK()
155 #define wxDATETIME_CHECK(expr, msg) \
159 *this = wxInvalidDateTime; \
163 // ----------------------------------------------------------------------------
165 // ----------------------------------------------------------------------------
167 class wxDateTimeHolidaysModule
: public wxModule
170 virtual bool OnInit()
172 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
177 virtual void OnExit()
179 wxDateTimeHolidayAuthority::ClearAllAuthorities();
180 wxDateTimeHolidayAuthority::ms_authorities
.clear();
184 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
187 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
189 // ----------------------------------------------------------------------------
191 // ----------------------------------------------------------------------------
194 static const int MONTHS_IN_YEAR
= 12;
196 static const int SEC_PER_MIN
= 60;
198 static const int MIN_PER_HOUR
= 60;
200 static const int HOURS_PER_DAY
= 24;
202 static const long SECONDS_PER_DAY
= 86400l;
204 static const int DAYS_PER_WEEK
= 7;
206 static const long MILLISECONDS_PER_DAY
= 86400000l;
208 // this is the integral part of JDN of the midnight of Jan 1, 1970
209 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
210 static const long EPOCH_JDN
= 2440587l;
212 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
213 // reference date for us) is Nov 24, 4714BC
214 static const int JDN_0_YEAR
= -4713;
215 static const int JDN_0_MONTH
= wxDateTime::Nov
;
216 static const int JDN_0_DAY
= 24;
218 // the constants used for JDN calculations
219 static const long JDN_OFFSET
= 32046l;
220 static const long DAYS_PER_5_MONTHS
= 153l;
221 static const long DAYS_PER_4_YEARS
= 1461l;
222 static const long DAYS_PER_400_YEARS
= 146097l;
224 // this array contains the cumulated number of days in all previous months for
225 // normal and leap years
226 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
228 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
229 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
232 // ----------------------------------------------------------------------------
234 // ----------------------------------------------------------------------------
236 const wxChar
* wxDefaultDateTimeFormat
= wxT("%c");
237 const wxChar
* wxDefaultTimeSpanFormat
= wxT("%H:%M:%S");
239 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
240 // indicate an invalid wxDateTime object
241 const wxDateTime wxDefaultDateTime
;
243 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
249 // debugger helper: shows what the date really is
251 extern const wxChar
*wxDumpDate(const wxDateTime
* dt
)
253 static wxChar buf
[128];
255 wxStrcpy(buf
, dt
->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
261 // get the number of days in the given month of the given year
263 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
265 // the number of days in month in Julian/Gregorian calendar: the first line
266 // is for normal years, the second one is for the leap ones
267 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
269 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
270 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
273 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
276 // returns the time zone in the C sense, i.e. the difference UTC - local
278 static int GetTimeZone()
280 #ifdef WX_GMTOFF_IN_TM
281 // set to true when the timezone is set
282 static bool s_timezoneSet
= false;
283 static long gmtoffset
= LONG_MAX
; // invalid timezone
285 // ensure that the timezone variable is set by calling localtime
286 if ( !s_timezoneSet
)
288 // just call localtime() instead of figuring out whether this system
289 // supports tzset(), _tzset() or something else
294 s_timezoneSet
= true;
296 // note that GMT offset is the opposite of time zone and so to return
297 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
298 // cases we have to negate it
299 gmtoffset
= -tm
->tm_gmtoff
;
302 return (int)gmtoffset
;
303 #else // !WX_GMTOFF_IN_TM
304 return (int)WX_TIMEZONE
;
305 #endif // WX_GMTOFF_IN_TM/!WX_GMTOFF_IN_TM
308 // return the integral part of the JDN for the midnight of the given date (to
309 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
310 // noon of the previous day)
311 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
312 wxDateTime::Month mon
,
315 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
317 // check the date validity
319 (year
> JDN_0_YEAR
) ||
320 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
321 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
322 _T("date out of range - can't convert to JDN")
325 // make the year positive to avoid problems with negative numbers division
328 // months are counted from March here
330 if ( mon
>= wxDateTime::Mar
)
340 // now we can simply add all the contributions together
341 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
342 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
343 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
348 // this function is a wrapper around strftime(3) adding error checking
349 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
352 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
354 // buffer is too small?
355 wxFAIL_MSG(_T("strftime() failed"));
358 return wxString(buf
);
363 // glibc2 doesn't define this in the headers unless _XOPEN_SOURCE is defined
364 // which, unfortunately, wreaks havoc elsewhere
365 #if defined(__GLIBC__) && (__GLIBC__ == 2)
366 extern "C" char *strptime(const char *, const char *, struct tm
*);
369 // Unicode-friendly strptime() wrapper
370 static const wxChar
*
371 CallStrptime(const wxChar
*input
, const char *fmt
, tm
*tm
)
373 // the problem here is that strptime() returns pointer into the string we
374 // passed to it while we're really interested in the pointer into the
375 // original, Unicode, string so we try to transform the pointer back
377 wxCharBuffer
inputMB(wxConvertWX2MB(input
));
379 const char * const inputMB
= input
;
380 #endif // Unicode/Ascii
382 const char *result
= strptime(inputMB
, fmt
, tm
);
387 // FIXME: this is wrong in presence of surrogates &c
388 return input
+ (result
- inputMB
.data());
391 #endif // Unicode/Ascii
394 #endif // HAVE_STRPTIME
396 // if year and/or month have invalid values, replace them with the current ones
397 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
398 wxDateTime::Month
*month
)
400 struct tm
*tmNow
= NULL
;
402 if ( *year
== wxDateTime::Inv_Year
)
404 tmNow
= wxDateTime::GetTmNow();
406 *year
= 1900 + tmNow
->tm_year
;
409 if ( *month
== wxDateTime::Inv_Month
)
412 tmNow
= wxDateTime::GetTmNow();
414 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
418 // fll the struct tm with default values
419 static void InitTm(struct tm
& tm
)
421 // struct tm may have etxra fields (undocumented and with unportable
422 // names) which, nevertheless, must be set to 0
423 memset(&tm
, 0, sizeof(struct tm
));
425 tm
.tm_mday
= 1; // mday 0 is invalid
426 tm
.tm_year
= 76; // any valid year
427 tm
.tm_isdst
= -1; // auto determine
433 // return the month if the string is a month name or Inv_Month otherwise
434 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
436 wxDateTime::Month mon
;
437 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
439 // case-insensitive comparison either one of or with both abbreviated
441 if ( flags
& wxDateTime::Name_Full
)
443 if ( name
.CmpNoCase(wxDateTime::
444 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
450 if ( flags
& wxDateTime::Name_Abbr
)
452 if ( name
.CmpNoCase(wxDateTime::
453 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
463 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
464 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
466 wxDateTime::WeekDay wd
;
467 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
469 // case-insensitive comparison either one of or with both abbreviated
471 if ( flags
& wxDateTime::Name_Full
)
473 if ( name
.CmpNoCase(wxDateTime::
474 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
480 if ( flags
& wxDateTime::Name_Abbr
)
482 if ( name
.CmpNoCase(wxDateTime::
483 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
493 // scans all digits (but no more than len) and returns the resulting number
494 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
498 while ( wxIsdigit(*p
) )
502 if ( len
&& ++n
> len
)
506 return !s
.empty() && s
.ToULong(number
);
509 // scans all alphabetic characters and returns the resulting string
510 static wxString
GetAlphaToken(const wxChar
*& p
)
513 while ( wxIsalpha(*p
) )
521 // ============================================================================
522 // implementation of wxDateTime
523 // ============================================================================
525 // ----------------------------------------------------------------------------
527 // ----------------------------------------------------------------------------
531 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
532 mon
= wxDateTime::Inv_Month
;
534 hour
= min
= sec
= msec
= 0;
535 wday
= wxDateTime::Inv_WeekDay
;
538 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
542 sec
= (wxDateTime::wxDateTime_t
)tm
.tm_sec
;
543 min
= (wxDateTime::wxDateTime_t
)tm
.tm_min
;
544 hour
= (wxDateTime::wxDateTime_t
)tm
.tm_hour
;
545 mday
= (wxDateTime::wxDateTime_t
)tm
.tm_mday
;
546 mon
= (wxDateTime::Month
)tm
.tm_mon
;
547 year
= 1900 + tm
.tm_year
;
548 wday
= (wxDateTime::wxDateTime_t
)tm
.tm_wday
;
549 yday
= (wxDateTime::wxDateTime_t
)tm
.tm_yday
;
552 bool wxDateTime::Tm::IsValid() const
554 // we allow for the leap seconds, although we don't use them (yet)
555 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
556 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
557 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
560 void wxDateTime::Tm::ComputeWeekDay()
562 // compute the week day from day/month/year: we use the dumbest algorithm
563 // possible: just compute our JDN and then use the (simple to derive)
564 // formula: weekday = (JDN + 1.5) % 7
565 wday
= (wxDateTime::wxDateTime_t
)((wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7);
568 void wxDateTime::Tm::AddMonths(int monDiff
)
570 // normalize the months field
571 while ( monDiff
< -mon
)
575 monDiff
+= MONTHS_IN_YEAR
;
578 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
582 monDiff
-= MONTHS_IN_YEAR
;
585 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
587 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
589 // NB: we don't check here that the resulting date is valid, this function
590 // is private and the caller must check it if needed
593 void wxDateTime::Tm::AddDays(int dayDiff
)
595 // normalize the days field
596 while ( dayDiff
+ mday
< 1 )
600 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
603 mday
= (wxDateTime::wxDateTime_t
)( mday
+ dayDiff
);
604 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
606 mday
-= GetNumOfDaysInMonth(year
, mon
);
611 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
615 // ----------------------------------------------------------------------------
617 // ----------------------------------------------------------------------------
619 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
623 case wxDateTime::Local
:
624 // get the offset from C RTL: it returns the difference GMT-local
625 // while we want to have the offset _from_ GMT, hence the '-'
626 m_offset
= -GetTimeZone();
629 case wxDateTime::GMT_12
:
630 case wxDateTime::GMT_11
:
631 case wxDateTime::GMT_10
:
632 case wxDateTime::GMT_9
:
633 case wxDateTime::GMT_8
:
634 case wxDateTime::GMT_7
:
635 case wxDateTime::GMT_6
:
636 case wxDateTime::GMT_5
:
637 case wxDateTime::GMT_4
:
638 case wxDateTime::GMT_3
:
639 case wxDateTime::GMT_2
:
640 case wxDateTime::GMT_1
:
641 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
644 case wxDateTime::GMT0
:
645 case wxDateTime::GMT1
:
646 case wxDateTime::GMT2
:
647 case wxDateTime::GMT3
:
648 case wxDateTime::GMT4
:
649 case wxDateTime::GMT5
:
650 case wxDateTime::GMT6
:
651 case wxDateTime::GMT7
:
652 case wxDateTime::GMT8
:
653 case wxDateTime::GMT9
:
654 case wxDateTime::GMT10
:
655 case wxDateTime::GMT11
:
656 case wxDateTime::GMT12
:
657 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
660 case wxDateTime::A_CST
:
661 // Central Standard Time in use in Australia = UTC + 9.5
662 m_offset
= 60l*(9*60 + 30);
666 wxFAIL_MSG( _T("unknown time zone") );
670 // ----------------------------------------------------------------------------
672 // ----------------------------------------------------------------------------
675 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
677 if ( year
== Inv_Year
)
678 year
= GetCurrentYear();
680 if ( cal
== Gregorian
)
682 // in Gregorian calendar leap years are those divisible by 4 except
683 // those divisible by 100 unless they're also divisible by 400
684 // (in some countries, like Russia and Greece, additional corrections
685 // exist, but they won't manifest themselves until 2700)
686 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
688 else if ( cal
== Julian
)
690 // in Julian calendar the rule is simpler
691 return year
% 4 == 0;
695 wxFAIL_MSG(_T("unknown calendar"));
702 int wxDateTime::GetCentury(int year
)
704 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
708 int wxDateTime::ConvertYearToBC(int year
)
711 return year
> 0 ? year
: year
- 1;
715 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
720 return Now().GetYear();
723 wxFAIL_MSG(_T("TODO"));
727 wxFAIL_MSG(_T("unsupported calendar"));
735 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
740 return Now().GetMonth();
743 wxFAIL_MSG(_T("TODO"));
747 wxFAIL_MSG(_T("unsupported calendar"));
755 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
757 if ( year
== Inv_Year
)
759 // take the current year if none given
760 year
= GetCurrentYear();
767 return IsLeapYear(year
) ? 366 : 365;
770 wxFAIL_MSG(_T("unsupported calendar"));
778 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
780 wxDateTime::Calendar cal
)
782 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
784 if ( cal
== Gregorian
|| cal
== Julian
)
786 if ( year
== Inv_Year
)
788 // take the current year if none given
789 year
= GetCurrentYear();
792 return GetNumOfDaysInMonth(year
, month
);
796 wxFAIL_MSG(_T("unsupported calendar"));
803 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
804 wxDateTime::NameFlags flags
)
806 wxCHECK_MSG( month
!= Inv_Month
, wxEmptyString
, _T("invalid month") );
808 // notice that we must set all the fields to avoid confusing libc (GNU one
809 // gets confused to a crash if we don't do this)
814 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
820 ret
= (flags
== Name_Abbr
? wxT("Jan"): wxT("January"));
823 ret
= (flags
== Name_Abbr
? wxT("Feb"): wxT("Febuary"));
826 ret
= (flags
== Name_Abbr
? wxT("Mar"): wxT("March"));
829 ret
= (flags
== Name_Abbr
? wxT("Apr"): wxT("April"));
832 ret
= (flags
== Name_Abbr
? wxT("May"): wxT("May"));
835 ret
= (flags
== Name_Abbr
? wxT("Jun"): wxT("June"));
838 ret
= (flags
== Name_Abbr
? wxT("Jul"): wxT("July"));
841 ret
= (flags
== Name_Abbr
? wxT("Aug"): wxT("August"));
844 ret
= (flags
== Name_Abbr
? wxT("Sep"): wxT("September"));
847 ret
= (flags
== Name_Abbr
? wxT("Oct"): wxT("October"));
850 ret
= (flags
== Name_Abbr
? wxT("Nov"): wxT("November"));
853 ret
= (flags
== Name_Abbr
? wxT("Dec"): wxT("December"));
861 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
862 wxDateTime::NameFlags flags
)
864 wxCHECK_MSG( wday
!= Inv_WeekDay
, wxEmptyString
, _T("invalid weekday") );
866 // take some arbitrary Sunday (but notice that the day should be such that
867 // after adding wday to it below we still have a valid date, e.g. don't
875 // and offset it by the number of days needed to get the correct wday
878 // call mktime() to normalize it...
881 // ... and call strftime()
882 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
888 ret
= (flags
== Name_Abbr
? wxT("Sun") : wxT("Sunday"));
891 ret
= (flags
== Name_Abbr
? wxT("Mon") : wxT("Monday"));
894 ret
= (flags
== Name_Abbr
? wxT("Tue") : wxT("Tuesday"));
897 ret
= (flags
== Name_Abbr
? wxT("Wed") : wxT("Wednesday"));
900 ret
= (flags
== Name_Abbr
? wxT("Thu") : wxT("Thursday"));
903 ret
= (flags
== Name_Abbr
? wxT("Fri") : wxT("Friday"));
906 ret
= (flags
== Name_Abbr
? wxT("Sat") : wxT("Saturday"));
915 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
920 // @Note: Do not call 'CallStrftime' here! CallStrftime checks the return code
921 // and causes an assertion failed if the buffer is to small (which is good) - OR -
922 // if strftime does not return anything because the format string is invalid - OR -
923 // if there are no 'am' / 'pm' tokens defined for the current locale (which is not good).
924 // wxDateTime::ParseTime will try several different formats to parse the time.
925 // As a result, GetAmPmStrings might get called, even if the current locale
926 // does not define any 'am' / 'pm' tokens. In this case, wxStrftime would
927 // assert, even though it is a perfectly legal use.
930 if (wxStrftime(buffer
, sizeof buffer
, _T("%p"), &tm
) > 0)
931 *am
= wxString(buffer
);
938 if (wxStrftime(buffer
, sizeof buffer
, _T("%p"), &tm
) > 0)
939 *pm
= wxString(buffer
);
945 // ----------------------------------------------------------------------------
946 // Country stuff: date calculations depend on the country (DST, work days,
947 // ...), so we need to know which rules to follow.
948 // ----------------------------------------------------------------------------
951 wxDateTime::Country
wxDateTime::GetCountry()
953 // TODO use LOCALE_ICOUNTRY setting under Win32
955 if ( ms_country
== Country_Unknown
)
957 // try to guess from the time zone name
958 time_t t
= time(NULL
);
959 struct tm
*tm
= localtime(&t
);
961 wxString tz
= CallStrftime(_T("%Z"), tm
);
962 if ( tz
== _T("WET") || tz
== _T("WEST") )
966 else if ( tz
== _T("CET") || tz
== _T("CEST") )
968 ms_country
= Country_EEC
;
970 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
974 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
975 tz
== _T("EST") || tz
== _T("EDT") ||
976 tz
== _T("CST") || tz
== _T("CDT") ||
977 tz
== _T("MST") || tz
== _T("MDT") ||
978 tz
== _T("PST") || tz
== _T("PDT") )
984 // well, choose a default one
996 void wxDateTime::SetCountry(wxDateTime::Country country
)
998 ms_country
= country
;
1002 bool wxDateTime::IsWestEuropeanCountry(Country country
)
1004 if ( country
== Country_Default
)
1006 country
= GetCountry();
1009 return (Country_WesternEurope_Start
<= country
) &&
1010 (country
<= Country_WesternEurope_End
);
1013 // ----------------------------------------------------------------------------
1014 // DST calculations: we use 3 different rules for the West European countries,
1015 // USA and for the rest of the world. This is undoubtedly false for many
1016 // countries, but I lack the necessary info (and the time to gather it),
1017 // please add the other rules here!
1018 // ----------------------------------------------------------------------------
1021 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
1023 if ( year
== Inv_Year
)
1025 // take the current year if none given
1026 year
= GetCurrentYear();
1029 if ( country
== Country_Default
)
1031 country
= GetCountry();
1038 // DST was first observed in the US and UK during WWI, reused
1039 // during WWII and used again since 1966
1040 return year
>= 1966 ||
1041 (year
>= 1942 && year
<= 1945) ||
1042 (year
== 1918 || year
== 1919);
1045 // assume that it started after WWII
1051 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
1053 if ( year
== Inv_Year
)
1055 // take the current year if none given
1056 year
= GetCurrentYear();
1059 if ( country
== Country_Default
)
1061 country
= GetCountry();
1064 if ( !IsDSTApplicable(year
, country
) )
1066 return wxInvalidDateTime
;
1071 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1073 // DST begins at 1 a.m. GMT on the last Sunday of March
1074 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
1077 wxFAIL_MSG( _T("no last Sunday in March?") );
1080 dt
+= wxTimeSpan::Hours(1);
1082 // disable DST tests because it could result in an infinite recursion!
1085 else switch ( country
)
1092 // don't know for sure - assume it was in effect all year
1097 dt
.Set(1, Jan
, year
);
1101 // DST was installed Feb 2, 1942 by the Congress
1102 dt
.Set(2, Feb
, year
);
1105 // Oil embargo changed the DST period in the US
1107 dt
.Set(6, Jan
, 1974);
1111 dt
.Set(23, Feb
, 1975);
1115 // before 1986, DST begun on the last Sunday of April, but
1116 // in 1986 Reagan changed it to begin at 2 a.m. of the
1117 // first Sunday in April
1120 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1123 wxFAIL_MSG( _T("no first Sunday in April?") );
1128 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1131 wxFAIL_MSG( _T("no first Sunday in April?") );
1135 dt
+= wxTimeSpan::Hours(2);
1137 // TODO what about timezone??
1143 // assume Mar 30 as the start of the DST for the rest of the world
1144 // - totally bogus, of course
1145 dt
.Set(30, Mar
, year
);
1152 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1154 if ( year
== Inv_Year
)
1156 // take the current year if none given
1157 year
= GetCurrentYear();
1160 if ( country
== Country_Default
)
1162 country
= GetCountry();
1165 if ( !IsDSTApplicable(year
, country
) )
1167 return wxInvalidDateTime
;
1172 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1174 // DST ends at 1 a.m. GMT on the last Sunday of October
1175 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1177 // weirder and weirder...
1178 wxFAIL_MSG( _T("no last Sunday in October?") );
1181 dt
+= wxTimeSpan::Hours(1);
1183 // disable DST tests because it could result in an infinite recursion!
1186 else switch ( country
)
1193 // don't know for sure - assume it was in effect all year
1197 dt
.Set(31, Dec
, year
);
1201 // the time was reset after the end of the WWII
1202 dt
.Set(30, Sep
, year
);
1206 // DST ends at 2 a.m. on the last Sunday of October
1207 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1209 // weirder and weirder...
1210 wxFAIL_MSG( _T("no last Sunday in October?") );
1213 dt
+= wxTimeSpan::Hours(2);
1215 // TODO what about timezone??
1220 // assume October 26th as the end of the DST - totally bogus too
1221 dt
.Set(26, Oct
, year
);
1227 // ----------------------------------------------------------------------------
1228 // constructors and assignment operators
1229 // ----------------------------------------------------------------------------
1231 // return the current time with ms precision
1232 /* static */ wxDateTime
wxDateTime::UNow()
1234 return wxDateTime(wxGetLocalTimeMillis());
1237 // the values in the tm structure contain the local time
1238 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1241 time_t timet
= mktime(&tm2
);
1243 if ( timet
== (time_t)-1 )
1245 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1246 // less than timezone - try to make it work for this case
1247 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1249 return Set((time_t)(
1251 tm2
.tm_hour
* MIN_PER_HOUR
* SEC_PER_MIN
+
1252 tm2
.tm_min
* SEC_PER_MIN
+
1256 wxFAIL_MSG( _T("mktime() failed") );
1258 *this = wxInvalidDateTime
;
1268 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1269 wxDateTime_t minute
,
1270 wxDateTime_t second
,
1271 wxDateTime_t millisec
)
1273 // we allow seconds to be 61 to account for the leap seconds, even if we
1274 // don't use them really
1275 wxDATETIME_CHECK( hour
< 24 &&
1279 _T("Invalid time in wxDateTime::Set()") );
1281 // get the current date from system
1282 struct tm
*tm
= GetTmNow();
1284 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1288 tm
->tm_min
= minute
;
1289 tm
->tm_sec
= second
;
1291 // and the DST in case it changes on this date
1294 if ( tm2
.tm_isdst
!= tm
->tm_isdst
)
1295 tm
->tm_isdst
= tm2
.tm_isdst
;
1299 // and finally adjust milliseconds
1300 return SetMillisecond(millisec
);
1303 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1307 wxDateTime_t minute
,
1308 wxDateTime_t second
,
1309 wxDateTime_t millisec
)
1311 wxDATETIME_CHECK( hour
< 24 &&
1315 _T("Invalid time in wxDateTime::Set()") );
1317 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1319 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1320 _T("Invalid date in wxDateTime::Set()") );
1322 // the range of time_t type (inclusive)
1323 static const int yearMinInRange
= 1970;
1324 static const int yearMaxInRange
= 2037;
1326 // test only the year instead of testing for the exact end of the Unix
1327 // time_t range - it doesn't bring anything to do more precise checks
1328 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1330 // use the standard library version if the date is in range - this is
1331 // probably more efficient than our code
1333 tm
.tm_year
= year
- 1900;
1339 tm
.tm_isdst
= -1; // mktime() will guess it
1343 // and finally adjust milliseconds
1345 SetMillisecond(millisec
);
1351 // do time calculations ourselves: we want to calculate the number of
1352 // milliseconds between the given date and the epoch
1354 // get the JDN for the midnight of this day
1355 m_time
= GetTruncatedJDN(day
, month
, year
);
1356 m_time
-= EPOCH_JDN
;
1357 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1359 // JDN corresponds to GMT, we take localtime
1360 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1366 wxDateTime
& wxDateTime::Set(double jdn
)
1368 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1370 jdn
-= EPOCH_JDN
+ 0.5;
1372 jdn
*= MILLISECONDS_PER_DAY
;
1374 // JDNs always suppose an UTC date, so bring it back to local time zone
1375 // (also see GetJulianDayNumber() implementation)
1376 long tzDiff
= GetTimeZone();
1379 // FIXME: again, we suppose that DST is always one hour
1383 jdn
+= tzDiff
*1000; // tzDiff is in seconds
1390 wxDateTime
& wxDateTime::ResetTime()
1394 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1407 // ----------------------------------------------------------------------------
1408 // DOS Date and Time Format functions
1409 // ----------------------------------------------------------------------------
1410 // the dos date and time value is an unsigned 32 bit value in the format:
1411 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1413 // Y = year offset from 1980 (0-127)
1415 // D = day of month (1-31)
1417 // m = minute (0-59)
1418 // s = bisecond (0-29) each bisecond indicates two seconds
1419 // ----------------------------------------------------------------------------
1421 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1426 long year
= ddt
& 0xFE000000;
1431 long month
= ddt
& 0x1E00000;
1436 long day
= ddt
& 0x1F0000;
1440 long hour
= ddt
& 0xF800;
1444 long minute
= ddt
& 0x7E0;
1448 long second
= ddt
& 0x1F;
1449 tm
.tm_sec
= second
* 2;
1451 return Set(mktime(&tm
));
1454 unsigned long wxDateTime::GetAsDOS() const
1457 time_t ticks
= GetTicks();
1458 struct tm
*tm
= localtime(&ticks
);
1460 long year
= tm
->tm_year
;
1464 long month
= tm
->tm_mon
;
1468 long day
= tm
->tm_mday
;
1471 long hour
= tm
->tm_hour
;
1474 long minute
= tm
->tm_min
;
1477 long second
= tm
->tm_sec
;
1480 ddt
= year
| month
| day
| hour
| minute
| second
;
1484 // ----------------------------------------------------------------------------
1485 // time_t <-> broken down time conversions
1486 // ----------------------------------------------------------------------------
1488 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1490 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1492 time_t time
= GetTicks();
1493 if ( time
!= (time_t)-1 )
1495 // use C RTL functions
1497 if ( tz
.GetOffset() == -GetTimeZone() )
1499 // we are working with local time
1500 tm
= localtime(&time
);
1502 // should never happen
1503 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1507 time
+= (time_t)tz
.GetOffset();
1508 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1509 int time2
= (int) time
;
1517 // should never happen
1518 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1522 tm
= (struct tm
*)NULL
;
1528 // adjust the milliseconds
1530 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1531 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1534 //else: use generic code below
1537 // remember the time and do the calculations with the date only - this
1538 // eliminates rounding errors of the floating point arithmetics
1540 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1542 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1544 // we want to always have positive time and timeMidnight to be really
1545 // the midnight before it
1548 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1551 timeMidnight
-= timeOnly
;
1553 // calculate the Gregorian date from JDN for the midnight of our date:
1554 // this will yield day, month (in 1..12 range) and year
1556 // actually, this is the JDN for the noon of the previous day
1557 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1559 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1561 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1563 // calculate the century
1564 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1565 long century
= temp
/ DAYS_PER_400_YEARS
;
1567 // then the year and day of year (1 <= dayOfYear <= 366)
1568 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1569 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1570 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1572 // and finally the month and day of the month
1573 temp
= dayOfYear
* 5 - 3;
1574 long month
= temp
/ DAYS_PER_5_MONTHS
;
1575 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1577 // month is counted from March - convert to normal
1588 // year is offset by 4800
1591 // check that the algorithm gave us something reasonable
1592 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1593 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1595 // construct Tm from these values
1597 tm
.year
= (int)year
;
1598 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1599 tm
.mday
= (wxDateTime_t
)day
;
1600 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1601 timeOnly
-= tm
.msec
;
1602 timeOnly
/= 1000; // now we have time in seconds
1604 tm
.sec
= (wxDateTime_t
)(timeOnly
% 60);
1606 timeOnly
/= 60; // now we have time in minutes
1608 tm
.min
= (wxDateTime_t
)(timeOnly
% 60);
1611 tm
.hour
= (wxDateTime_t
)(timeOnly
/ 60);
1616 wxDateTime
& wxDateTime::SetYear(int year
)
1618 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1627 wxDateTime
& wxDateTime::SetMonth(Month month
)
1629 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1638 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1640 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1649 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1651 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1660 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1662 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1671 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1673 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1682 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1684 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1686 // we don't need to use GetTm() for this one
1687 m_time
-= m_time
% 1000l;
1688 m_time
+= millisecond
;
1693 // ----------------------------------------------------------------------------
1694 // wxDateTime arithmetics
1695 // ----------------------------------------------------------------------------
1697 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1701 tm
.year
+= diff
.GetYears();
1702 tm
.AddMonths(diff
.GetMonths());
1704 // check that the resulting date is valid
1705 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1707 // We suppose that when adding one month to Jan 31 we want to get Feb
1708 // 28 (or 29), i.e. adding a month to the last day of the month should
1709 // give the last day of the next month which is quite logical.
1711 // Unfortunately, there is no logic way to understand what should
1712 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1713 // We make it Feb 28 (last day too), but it is highly questionable.
1714 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1717 tm
.AddDays(diff
.GetTotalDays());
1721 wxASSERT_MSG( IsSameTime(tm
),
1722 _T("Add(wxDateSpan) shouldn't modify time") );
1727 // ----------------------------------------------------------------------------
1728 // Weekday and monthday stuff
1729 // ----------------------------------------------------------------------------
1731 // convert Sun, Mon, ..., Sat into 6, 0, ..., 5
1732 static inline int ConvertWeekDayToMondayBase(int wd
)
1734 return wd
== wxDateTime::Sun
? 6 : wd
- 1;
1739 wxDateTime::SetToWeekOfYear(int year
, wxDateTime_t numWeek
, WeekDay wd
)
1741 wxASSERT_MSG( numWeek
> 0,
1742 _T("invalid week number: weeks are counted from 1") );
1744 // Jan 4 always lies in the 1st week of the year
1745 wxDateTime
dt(4, Jan
, year
);
1746 dt
.SetToWeekDayInSameWeek(wd
);
1747 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1752 // use a separate function to avoid warnings about using deprecated
1753 // SetToTheWeek in GetWeek below
1755 SetToTheWeek(int year
,
1756 wxDateTime::wxDateTime_t numWeek
,
1757 wxDateTime::WeekDay weekday
,
1758 wxDateTime::WeekFlags flags
)
1760 // Jan 4 always lies in the 1st week of the year
1761 wxDateTime
dt(4, wxDateTime::Jan
, year
);
1762 dt
.SetToWeekDayInSameWeek(weekday
, flags
);
1763 dt
+= wxDateSpan::Weeks(numWeek
- 1);
1768 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1772 int year
= GetYear();
1773 *this = ::SetToTheWeek(year
, numWeek
, weekday
, flags
);
1774 if ( GetYear() != year
)
1776 // oops... numWeek was too big
1783 wxDateTime
wxDateTime::GetWeek(wxDateTime_t numWeek
,
1785 WeekFlags flags
) const
1787 return ::SetToTheWeek(GetYear(), numWeek
, weekday
, flags
);
1790 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1793 // take the current month/year if none specified
1794 if ( year
== Inv_Year
)
1796 if ( month
== Inv_Month
)
1799 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1802 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1804 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1806 int wdayThis
= GetWeekDay();
1807 if ( weekday
== wdayThis
)
1813 if ( flags
== Default_First
)
1815 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1818 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1819 // is the first day in the week, but breaks down for Monday_First case so
1820 // we adjust the week days in this case
1821 if( flags
== Monday_First
)
1823 if ( wdayThis
== Sun
)
1826 //else: Sunday_First, nothing to do
1828 // go forward or back in time to the day we want
1829 if ( weekday
< wdayThis
)
1831 return Subtract(wxDateSpan::Days(wdayThis
- weekday
));
1833 else // weekday > wdayThis
1835 return Add(wxDateSpan::Days(weekday
- wdayThis
));
1839 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1841 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1844 WeekDay wdayThis
= GetWeekDay();
1845 if ( weekday
== wdayThis
)
1850 else if ( weekday
< wdayThis
)
1852 // need to advance a week
1853 diff
= 7 - (wdayThis
- weekday
);
1855 else // weekday > wdayThis
1857 diff
= weekday
- wdayThis
;
1860 return Add(wxDateSpan::Days(diff
));
1863 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1865 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1868 WeekDay wdayThis
= GetWeekDay();
1869 if ( weekday
== wdayThis
)
1874 else if ( weekday
> wdayThis
)
1876 // need to go to previous week
1877 diff
= 7 - (weekday
- wdayThis
);
1879 else // weekday < wdayThis
1881 diff
= wdayThis
- weekday
;
1884 return Subtract(wxDateSpan::Days(diff
));
1887 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1892 wxCHECK_MSG( weekday
!= Inv_WeekDay
, false, _T("invalid weekday") );
1894 // we don't check explicitly that -5 <= n <= 5 because we will return false
1895 // anyhow in such case - but may be should still give an assert for it?
1897 // take the current month/year if none specified
1898 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1902 // TODO this probably could be optimised somehow...
1906 // get the first day of the month
1907 dt
.Set(1, month
, year
);
1910 WeekDay wdayFirst
= dt
.GetWeekDay();
1912 // go to the first weekday of the month
1913 int diff
= weekday
- wdayFirst
;
1917 // add advance n-1 weeks more
1920 dt
+= wxDateSpan::Days(diff
);
1922 else // count from the end of the month
1924 // get the last day of the month
1925 dt
.SetToLastMonthDay(month
, year
);
1928 WeekDay wdayLast
= dt
.GetWeekDay();
1930 // go to the last weekday of the month
1931 int diff
= wdayLast
- weekday
;
1935 // and rewind n-1 weeks from there
1938 dt
-= wxDateSpan::Days(diff
);
1941 // check that it is still in the same month
1942 if ( dt
.GetMonth() == month
)
1950 // no such day in this month
1956 wxDateTime::wxDateTime_t
GetDayOfYearFromTm(const wxDateTime::Tm
& tm
)
1958 return (wxDateTime::wxDateTime_t
)(gs_cumulatedDays
[wxDateTime::IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
);
1961 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1963 return GetDayOfYearFromTm(GetTm(tz
));
1966 wxDateTime::wxDateTime_t
1967 wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
, const TimeZone
& tz
) const
1969 if ( flags
== Default_First
)
1971 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1975 wxDateTime_t nDayInYear
= GetDayOfYearFromTm(tm
);
1977 int wdTarget
= GetWeekDay(tz
);
1978 int wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1980 if ( flags
== Sunday_First
)
1982 // FIXME: First week is not calculated correctly.
1983 week
= (nDayInYear
- wdTarget
+ 7) / 7;
1984 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1987 else // week starts with monday
1989 // adjust the weekdays to non-US style.
1990 wdYearStart
= ConvertWeekDayToMondayBase(wdYearStart
);
1991 wdTarget
= ConvertWeekDayToMondayBase(wdTarget
);
1993 // quoting from http://www.cl.cam.ac.uk/~mgk25/iso-time.html:
1995 // Week 01 of a year is per definition the first week that has the
1996 // Thursday in this year, which is equivalent to the week that
1997 // contains the fourth day of January. In other words, the first
1998 // week of a new year is the week that has the majority of its
1999 // days in the new year. Week 01 might also contain days from the
2000 // previous year and the week before week 01 of a year is the last
2001 // week (52 or 53) of the previous year even if it contains days
2002 // from the new year. A week starts with Monday (day 1) and ends
2003 // with Sunday (day 7).
2006 // if Jan 1 is Thursday or less, it is in the first week of this year
2007 if ( wdYearStart
< 4 )
2009 // count the number of entire weeks between Jan 1 and this date
2010 week
= (nDayInYear
+ wdYearStart
+ 6 - wdTarget
)/7;
2012 // be careful to check for overflow in the next year
2013 if ( week
== 53 && tm
.mday
- wdTarget
> 28 )
2016 else // Jan 1 is in the last week of the previous year
2018 // check if we happen to be at the last week of previous year:
2019 if ( tm
.mon
== Jan
&& tm
.mday
< 8 - wdYearStart
)
2020 week
= wxDateTime(31, Dec
, GetYear()-1).GetWeekOfYear();
2022 week
= (nDayInYear
+ wdYearStart
- 1 - wdTarget
)/7;
2026 return (wxDateTime::wxDateTime_t
)week
;
2029 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
2030 const TimeZone
& tz
) const
2033 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
2034 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
2037 // this may happen for January when Jan, 1 is the last week of the
2039 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
2042 return (wxDateTime::wxDateTime_t
)nWeek
;
2045 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
2047 int year
= GetYear();
2048 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
2049 _T("invalid year day") );
2051 bool isLeap
= IsLeapYear(year
);
2052 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
2054 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
2055 // don't need it neither - because of the CHECK above we know that
2056 // yday lies in December then
2057 if ( (mon
== Dec
) || (yday
<= gs_cumulatedDays
[isLeap
][mon
+ 1]) )
2059 Set((wxDateTime::wxDateTime_t
)(yday
- gs_cumulatedDays
[isLeap
][mon
]), mon
, year
);
2068 // ----------------------------------------------------------------------------
2069 // Julian day number conversion and related stuff
2070 // ----------------------------------------------------------------------------
2072 double wxDateTime::GetJulianDayNumber() const
2074 // JDN are always expressed for the UTC dates
2075 Tm
tm(ToTimezone(UTC
).GetTm(UTC
));
2077 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
2079 // add the part GetTruncatedJDN() neglected
2082 // and now add the time: 86400 sec = 1 JDN
2083 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
2086 double wxDateTime::GetRataDie() const
2088 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
2089 return GetJulianDayNumber() - 1721119.5 - 306;
2092 // ----------------------------------------------------------------------------
2093 // timezone and DST stuff
2094 // ----------------------------------------------------------------------------
2096 int wxDateTime::IsDST(wxDateTime::Country country
) const
2098 wxCHECK_MSG( country
== Country_Default
, -1,
2099 _T("country support not implemented") );
2101 // use the C RTL for the dates in the standard range
2102 time_t timet
= GetTicks();
2103 if ( timet
!= (time_t)-1 )
2105 tm
*tm
= localtime(&timet
);
2107 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
2109 return tm
->tm_isdst
;
2113 int year
= GetYear();
2115 if ( !IsDSTApplicable(year
, country
) )
2117 // no DST time in this year in this country
2121 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
2125 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
2127 long secDiff
= GetTimeZone() + tz
.GetOffset();
2129 // we need to know whether DST is or not in effect for this date unless
2130 // the test disabled by the caller
2131 if ( !noDST
&& (IsDST() == 1) )
2133 // FIXME we assume that the DST is always shifted by 1 hour
2137 return Subtract(wxTimeSpan::Seconds(secDiff
));
2140 // ----------------------------------------------------------------------------
2141 // wxDateTime to/from text representations
2142 // ----------------------------------------------------------------------------
2144 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
2146 wxCHECK_MSG( format
, wxEmptyString
, _T("NULL format in wxDateTime::Format") );
2148 // we have to use our own implementation if the date is out of range of
2149 // strftime() or if we use non standard specificators
2150 time_t time
= GetTicks();
2151 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
2155 if ( tz
.GetOffset() == -GetTimeZone() )
2157 // we are working with local time
2158 tm
= localtime(&time
);
2160 // should never happen
2161 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
2165 time
+= (int)tz
.GetOffset();
2167 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
2168 int time2
= (int) time
;
2176 // should never happen
2177 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
2181 tm
= (struct tm
*)NULL
;
2185 //Windows CE doesn't support strftime or wcsftime, so we use the generic implementation
2188 return CallStrftime(format
, tm
);
2191 //else: use generic code below
2194 // we only parse ANSI C format specifications here, no POSIX 2
2195 // complications, no GNU extensions but we do add support for a "%l" format
2196 // specifier allowing to get the number of milliseconds
2199 // used for calls to strftime() when we only deal with time
2200 struct tm tmTimeOnly
;
2201 tmTimeOnly
.tm_hour
= tm
.hour
;
2202 tmTimeOnly
.tm_min
= tm
.min
;
2203 tmTimeOnly
.tm_sec
= tm
.sec
;
2204 tmTimeOnly
.tm_wday
= 0;
2205 tmTimeOnly
.tm_yday
= 0;
2206 tmTimeOnly
.tm_mday
= 1; // any date will do
2207 tmTimeOnly
.tm_mon
= 0;
2208 tmTimeOnly
.tm_year
= 76;
2209 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
2211 wxString tmp
, res
, fmt
;
2212 for ( const wxChar
*p
= format
; *p
; p
++ )
2214 if ( *p
!= _T('%') )
2222 // set the default format
2225 case _T('Y'): // year has 4 digits
2229 case _T('j'): // day of year has 3 digits
2230 case _T('l'): // milliseconds have 3 digits
2234 case _T('w'): // week day as number has only one
2239 // it's either another valid format specifier in which case
2240 // the format is "%02d" (for all the rest) or we have the
2241 // field width preceding the format in which case it will
2242 // override the default format anyhow
2246 bool restart
= true;
2251 // start of the format specification
2254 case _T('a'): // a weekday name
2256 // second parameter should be true for abbreviated names
2257 res
+= GetWeekDayName(tm
.GetWeekDay(),
2258 *p
== _T('a') ? Name_Abbr
: Name_Full
);
2261 case _T('b'): // a month name
2263 res
+= GetMonthName(tm
.mon
,
2264 *p
== _T('b') ? Name_Abbr
: Name_Full
);
2267 case _T('c'): // locale default date and time representation
2268 case _T('x'): // locale default date representation
2271 // the problem: there is no way to know what do these format
2272 // specifications correspond to for the current locale.
2274 // the solution: use a hack and still use strftime(): first
2275 // find the YEAR which is a year in the strftime() range (1970
2276 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
2277 // of the real year. Then make a copy of the format and
2278 // replace all occurences of YEAR in it with some unique
2279 // string not appearing anywhere else in it, then use
2280 // strftime() to format the date in year YEAR and then replace
2281 // YEAR back by the real year and the unique replacement
2282 // string back with YEAR. Notice that "all occurences of YEAR"
2283 // means all occurences of 4 digit as well as 2 digit form!
2285 // the bugs: we assume that neither of %c nor %x contains any
2286 // fields which may change between the YEAR and real year. For
2287 // example, the week number (%U, %W) and the day number (%j)
2288 // will change if one of these years is leap and the other one
2291 // find the YEAR: normally, for any year X, Jan 1 or the
2292 // year X + 28 is the same weekday as Jan 1 of X (because
2293 // the weekday advances by 1 for each normal X and by 2
2294 // for each leap X, hence by 5 every 4 years or by 35
2295 // which is 0 mod 7 every 28 years) but this rule breaks
2296 // down if there are years between X and Y which are
2297 // divisible by 4 but not leap (i.e. divisible by 100 but
2298 // not 400), hence the correction.
2300 int yearReal
= GetYear(tz
);
2301 int mod28
= yearReal
% 28;
2303 // be careful to not go too far - we risk to leave the
2308 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
2312 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
2315 int nCentury
= year
/ 100,
2316 nCenturyReal
= yearReal
/ 100;
2318 // need to adjust for the years divisble by 400 which are
2319 // not leap but are counted like leap ones if we just take
2320 // the number of centuries in between for nLostWeekDays
2321 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
2322 (nCentury
/ 4 - nCenturyReal
/ 4);
2324 // we have to gain back the "lost" weekdays: note that the
2325 // effect of this loop is to not do anything to
2326 // nLostWeekDays (which we won't use any more), but to
2327 // (indirectly) set the year correctly
2328 while ( (nLostWeekDays
% 7) != 0 )
2330 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
2333 // at any rate, we couldn't go further than 1988 + 9 + 28!
2334 wxASSERT_MSG( year
< 2030,
2335 _T("logic error in wxDateTime::Format") );
2337 wxString strYear
, strYear2
;
2338 strYear
.Printf(_T("%d"), year
);
2339 strYear2
.Printf(_T("%d"), year
% 100);
2341 // find two strings not occuring in format (this is surely
2342 // not optimal way of doing it... improvements welcome!)
2343 wxString fmt
= format
;
2344 wxString replacement
= (wxChar
)-1;
2345 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2347 replacement
<< (wxChar
)-1;
2350 wxString replacement2
= (wxChar
)-2;
2351 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2353 replacement
<< (wxChar
)-2;
2356 // replace all occurences of year with it
2357 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
2359 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
2361 // use strftime() to format the same date but in supported
2364 // NB: we assume that strftime() doesn't check for the
2365 // date validity and will happily format the date
2366 // corresponding to Feb 29 of a non leap year (which
2367 // may happen if yearReal was leap and year is not)
2368 struct tm tmAdjusted
;
2370 tmAdjusted
.tm_hour
= tm
.hour
;
2371 tmAdjusted
.tm_min
= tm
.min
;
2372 tmAdjusted
.tm_sec
= tm
.sec
;
2373 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
2374 tmAdjusted
.tm_yday
= GetDayOfYear();
2375 tmAdjusted
.tm_mday
= tm
.mday
;
2376 tmAdjusted
.tm_mon
= tm
.mon
;
2377 tmAdjusted
.tm_year
= year
- 1900;
2378 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
2379 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
2383 // now replace the occurence of 1999 with the real year
2384 wxString strYearReal
, strYearReal2
;
2385 strYearReal
.Printf(_T("%04d"), yearReal
);
2386 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
2387 str
.Replace(strYear
, strYearReal
);
2388 str
.Replace(strYear2
, strYearReal2
);
2390 // and replace back all occurences of replacement string
2393 str
.Replace(replacement2
, strYear2
);
2394 str
.Replace(replacement
, strYear
);
2400 //Use "%m/%d/%y %H:%M:%S" format instead
2401 res
+= wxString::Format(wxT("%02d/%02d/%04d %02d:%02d:%02d"),
2402 tm
.mon
+1,tm
.mday
, tm
.year
, tm
.hour
, tm
.min
, tm
.sec
);
2406 case _T('d'): // day of a month (01-31)
2407 res
+= wxString::Format(fmt
, tm
.mday
);
2410 case _T('H'): // hour in 24h format (00-23)
2411 res
+= wxString::Format(fmt
, tm
.hour
);
2414 case _T('I'): // hour in 12h format (01-12)
2416 // 24h -> 12h, 0h -> 12h too
2417 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
2418 : tm
.hour
? tm
.hour
: 12;
2419 res
+= wxString::Format(fmt
, hour12
);
2423 case _T('j'): // day of the year
2424 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
2427 case _T('l'): // milliseconds (NOT STANDARD)
2428 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
2431 case _T('m'): // month as a number (01-12)
2432 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
2435 case _T('M'): // minute as a decimal number (00-59)
2436 res
+= wxString::Format(fmt
, tm
.min
);
2439 case _T('p'): // AM or PM string
2441 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
2443 res
+= (tmTimeOnly
.tm_hour
> 12) ? wxT("pm") : wxT("am");
2447 case _T('S'): // second as a decimal number (00-61)
2448 res
+= wxString::Format(fmt
, tm
.sec
);
2451 case _T('U'): // week number in the year (Sunday 1st week day)
2452 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
2455 case _T('W'): // week number in the year (Monday 1st week day)
2456 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
2459 case _T('w'): // weekday as a number (0-6), Sunday = 0
2460 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
2463 // case _T('x'): -- handled with "%c"
2465 case _T('X'): // locale default time representation
2466 // just use strftime() to format the time for us
2468 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
2470 res
+= wxString::Format(wxT("%02d:%02d:%02d"),tm
.hour
, tm
.min
, tm
.sec
);
2474 case _T('y'): // year without century (00-99)
2475 res
+= wxString::Format(fmt
, tm
.year
% 100);
2478 case _T('Y'): // year with century
2479 res
+= wxString::Format(fmt
, tm
.year
);
2482 case _T('Z'): // timezone name
2484 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
2489 // is it the format width?
2491 while ( *p
== _T('-') || *p
== _T('+') ||
2492 *p
== _T(' ') || wxIsdigit(*p
) )
2499 // we've only got the flags and width so far in fmt
2500 fmt
.Prepend(_T('%'));
2501 fmt
.Append(_T('d'));
2508 // no, it wasn't the width
2509 wxFAIL_MSG(_T("unknown format specificator"));
2511 // fall through and just copy it nevertheless
2513 case _T('%'): // a percent sign
2517 case 0: // the end of string
2518 wxFAIL_MSG(_T("missing format at the end of string"));
2520 // just put the '%' which was the last char in format
2530 // this function parses a string in (strict) RFC 822 format: see the section 5
2531 // of the RFC for the detailed description, but briefly it's something of the
2532 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2534 // this function is "strict" by design - it must reject anything except true
2535 // RFC822 time specs.
2537 // TODO a great candidate for using reg exps
2538 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
2540 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2542 const wxChar
*p
= date
;
2543 const wxChar
*comma
= wxStrchr(p
, _T(','));
2546 // the part before comma is the weekday
2548 // skip it for now - we don't use but might check that it really
2549 // corresponds to the specfied date
2552 if ( *p
!= _T(' ') )
2554 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2556 return (wxChar
*)NULL
;
2562 // the following 1 or 2 digits are the day number
2563 if ( !wxIsdigit(*p
) )
2565 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2567 return (wxChar
*)NULL
;
2570 wxDateTime_t day
= (wxDateTime_t
)(*p
++ - _T('0'));
2571 if ( wxIsdigit(*p
) )
2574 day
= (wxDateTime_t
)(day
+ (*p
++ - _T('0')));
2577 if ( *p
++ != _T(' ') )
2579 return (wxChar
*)NULL
;
2582 // the following 3 letters specify the month
2583 wxString
monName(p
, 3);
2585 if ( monName
== _T("Jan") )
2587 else if ( monName
== _T("Feb") )
2589 else if ( monName
== _T("Mar") )
2591 else if ( monName
== _T("Apr") )
2593 else if ( monName
== _T("May") )
2595 else if ( monName
== _T("Jun") )
2597 else if ( monName
== _T("Jul") )
2599 else if ( monName
== _T("Aug") )
2601 else if ( monName
== _T("Sep") )
2603 else if ( monName
== _T("Oct") )
2605 else if ( monName
== _T("Nov") )
2607 else if ( monName
== _T("Dec") )
2611 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
2613 return (wxChar
*)NULL
;
2618 if ( *p
++ != _T(' ') )
2620 return (wxChar
*)NULL
;
2624 if ( !wxIsdigit(*p
) )
2627 return (wxChar
*)NULL
;
2630 int year
= *p
++ - _T('0');
2632 if ( !wxIsdigit(*p
) )
2634 // should have at least 2 digits in the year
2635 return (wxChar
*)NULL
;
2639 year
+= *p
++ - _T('0');
2641 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2642 if ( wxIsdigit(*p
) )
2645 year
+= *p
++ - _T('0');
2647 if ( !wxIsdigit(*p
) )
2649 // no 3 digit years please
2650 return (wxChar
*)NULL
;
2654 year
+= *p
++ - _T('0');
2657 if ( *p
++ != _T(' ') )
2659 return (wxChar
*)NULL
;
2662 // time is in the format hh:mm:ss and seconds are optional
2663 if ( !wxIsdigit(*p
) )
2665 return (wxChar
*)NULL
;
2668 wxDateTime_t hour
= (wxDateTime_t
)(*p
++ - _T('0'));
2670 if ( !wxIsdigit(*p
) )
2672 return (wxChar
*)NULL
;
2676 hour
= (wxDateTime_t
)(hour
+ (*p
++ - _T('0')));
2678 if ( *p
++ != _T(':') )
2680 return (wxChar
*)NULL
;
2683 if ( !wxIsdigit(*p
) )
2685 return (wxChar
*)NULL
;
2688 wxDateTime_t min
= (wxDateTime_t
)(*p
++ - _T('0'));
2690 if ( !wxIsdigit(*p
) )
2692 return (wxChar
*)NULL
;
2696 min
= (wxDateTime_t
)(min
+ *p
++ - _T('0'));
2698 wxDateTime_t sec
= 0;
2699 if ( *p
++ == _T(':') )
2701 if ( !wxIsdigit(*p
) )
2703 return (wxChar
*)NULL
;
2706 sec
= (wxDateTime_t
)(*p
++ - _T('0'));
2708 if ( !wxIsdigit(*p
) )
2710 return (wxChar
*)NULL
;
2714 sec
= (wxDateTime_t
)(sec
+ *p
++ - _T('0'));
2717 if ( *p
++ != _T(' ') )
2719 return (wxChar
*)NULL
;
2722 // and now the interesting part: the timezone
2724 if ( *p
== _T('-') || *p
== _T('+') )
2726 // the explicit offset given: it has the form of hhmm
2727 bool plus
= *p
++ == _T('+');
2729 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2731 return (wxChar
*)NULL
;
2735 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
2739 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2741 return (wxChar
*)NULL
;
2745 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
2756 // the symbolic timezone given: may be either military timezone or one
2757 // of standard abbreviations
2760 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2761 static const int offsets
[26] =
2763 //A B C D E F G H I J K L M
2764 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2765 //N O P R Q S T U V W Z Y Z
2766 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2769 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
2771 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
2773 return (wxChar
*)NULL
;
2776 offset
= offsets
[*p
++ - _T('A')];
2782 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
2784 else if ( tz
== _T("AST") )
2785 offset
= AST
- GMT0
;
2786 else if ( tz
== _T("ADT") )
2787 offset
= ADT
- GMT0
;
2788 else if ( tz
== _T("EST") )
2789 offset
= EST
- GMT0
;
2790 else if ( tz
== _T("EDT") )
2791 offset
= EDT
- GMT0
;
2792 else if ( tz
== _T("CST") )
2793 offset
= CST
- GMT0
;
2794 else if ( tz
== _T("CDT") )
2795 offset
= CDT
- GMT0
;
2796 else if ( tz
== _T("MST") )
2797 offset
= MST
- GMT0
;
2798 else if ( tz
== _T("MDT") )
2799 offset
= MDT
- GMT0
;
2800 else if ( tz
== _T("PST") )
2801 offset
= PST
- GMT0
;
2802 else if ( tz
== _T("PDT") )
2803 offset
= PDT
- GMT0
;
2806 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
2808 return (wxChar
*)NULL
;
2818 // the spec was correct
2819 Set(day
, mon
, year
, hour
, min
, sec
);
2820 MakeTimezone((wxDateTime_t
)(60*offset
));
2825 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
,
2826 const wxChar
*format
,
2827 const wxDateTime
& dateDef
)
2829 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
2830 _T("NULL pointer in wxDateTime::ParseFormat()") );
2835 // what fields have we found?
2836 bool haveWDay
= false,
2845 bool hourIsIn12hFormat
= false, // or in 24h one?
2846 isPM
= false; // AM by default
2848 // and the value of the items we have (init them to get rid of warnings)
2849 wxDateTime_t sec
= 0,
2852 WeekDay wday
= Inv_WeekDay
;
2853 wxDateTime_t yday
= 0,
2855 wxDateTime::Month mon
= Inv_Month
;
2858 const wxChar
*input
= date
;
2859 for ( const wxChar
*fmt
= format
; *fmt
; fmt
++ )
2861 if ( *fmt
!= _T('%') )
2863 if ( wxIsspace(*fmt
) )
2865 // a white space in the format string matches 0 or more white
2866 // spaces in the input
2867 while ( wxIsspace(*input
) )
2874 // any other character (not whitespace, not '%') must be
2875 // matched by itself in the input
2876 if ( *input
++ != *fmt
)
2879 return (wxChar
*)NULL
;
2883 // done with this format char
2887 // start of a format specification
2889 // parse the optional width
2891 while ( wxIsdigit(*++fmt
) )
2894 width
+= *fmt
- _T('0');
2897 // the default widths for the various fields
2902 case _T('Y'): // year has 4 digits
2906 case _T('j'): // day of year has 3 digits
2907 case _T('l'): // milliseconds have 3 digits
2911 case _T('w'): // week day as number has only one
2916 // default for all other fields
2921 // then the format itself
2924 case _T('a'): // a weekday name
2927 int flag
= *fmt
== _T('a') ? Name_Abbr
: Name_Full
;
2928 wday
= GetWeekDayFromName(GetAlphaToken(input
), flag
);
2929 if ( wday
== Inv_WeekDay
)
2932 return (wxChar
*)NULL
;
2938 case _T('b'): // a month name
2941 int flag
= *fmt
== _T('b') ? Name_Abbr
: Name_Full
;
2942 mon
= GetMonthFromName(GetAlphaToken(input
), flag
);
2943 if ( mon
== Inv_Month
)
2946 return (wxChar
*)NULL
;
2952 case _T('c'): // locale default date and time representation
2956 // this is the format which corresponds to ctime() output
2957 // and strptime("%c") should parse it, so try it first
2958 static const wxChar
*fmtCtime
= _T("%a %b %d %H:%M:%S %Y");
2960 const wxChar
*result
= dt
.ParseFormat(input
, fmtCtime
);
2963 result
= dt
.ParseFormat(input
, _T("%x %X"));
2968 result
= dt
.ParseFormat(input
, _T("%X %x"));
2973 // we've tried everything and still no match
2974 return (wxChar
*)NULL
;
2979 haveDay
= haveMon
= haveYear
=
2980 haveHour
= haveMin
= haveSec
= true;
2994 case _T('d'): // day of a month (01-31)
2995 if ( !GetNumericToken(width
, input
, &num
) ||
2996 (num
> 31) || (num
< 1) )
2999 return (wxChar
*)NULL
;
3002 // we can't check whether the day range is correct yet, will
3003 // do it later - assume ok for now
3005 mday
= (wxDateTime_t
)num
;
3008 case _T('H'): // hour in 24h format (00-23)
3009 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
3012 return (wxChar
*)NULL
;
3016 hour
= (wxDateTime_t
)num
;
3019 case _T('I'): // hour in 12h format (01-12)
3020 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
3023 return (wxChar
*)NULL
;
3027 hourIsIn12hFormat
= true;
3028 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
3031 case _T('j'): // day of the year
3032 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
3035 return (wxChar
*)NULL
;
3039 yday
= (wxDateTime_t
)num
;
3042 case _T('m'): // month as a number (01-12)
3043 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
3046 return (wxChar
*)NULL
;
3050 mon
= (Month
)(num
- 1);
3053 case _T('M'): // minute as a decimal number (00-59)
3054 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
3057 return (wxChar
*)NULL
;
3061 min
= (wxDateTime_t
)num
;
3064 case _T('p'): // AM or PM string
3066 wxString am
, pm
, token
= GetAlphaToken(input
);
3068 GetAmPmStrings(&am
, &pm
);
3069 if (am
.empty() && pm
.empty())
3070 return (wxChar
*)NULL
; // no am/pm strings defined
3071 if ( token
.CmpNoCase(pm
) == 0 )
3075 else if ( token
.CmpNoCase(am
) != 0 )
3078 return (wxChar
*)NULL
;
3083 case _T('r'): // time as %I:%M:%S %p
3086 input
= dt
.ParseFormat(input
, _T("%I:%M:%S %p"));
3090 return (wxChar
*)NULL
;
3093 haveHour
= haveMin
= haveSec
= true;
3102 case _T('R'): // time as %H:%M
3105 input
= dt
.ParseFormat(input
, _T("%H:%M"));
3109 return (wxChar
*)NULL
;
3112 haveHour
= haveMin
= true;
3119 case _T('S'): // second as a decimal number (00-61)
3120 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
3123 return (wxChar
*)NULL
;
3127 sec
= (wxDateTime_t
)num
;
3130 case _T('T'): // time as %H:%M:%S
3133 input
= dt
.ParseFormat(input
, _T("%H:%M:%S"));
3137 return (wxChar
*)NULL
;
3140 haveHour
= haveMin
= haveSec
= true;
3149 case _T('w'): // weekday as a number (0-6), Sunday = 0
3150 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
3153 return (wxChar
*)NULL
;
3157 wday
= (WeekDay
)num
;
3160 case _T('x'): // locale default date representation
3161 #ifdef HAVE_STRPTIME
3162 // try using strptime() -- it may fail even if the input is
3163 // correct but the date is out of range, so we will fall back
3164 // to our generic code anyhow
3168 const wxChar
*result
= CallStrptime(input
, "%x", &tm
);
3173 haveDay
= haveMon
= haveYear
= true;
3175 year
= 1900 + tm
.tm_year
;
3176 mon
= (Month
)tm
.tm_mon
;
3182 #endif // HAVE_STRPTIME
3184 // TODO query the LOCALE_IDATE setting under Win32
3188 wxString fmtDate
, fmtDateAlt
;
3189 if ( IsWestEuropeanCountry(GetCountry()) ||
3190 GetCountry() == Russia
)
3192 fmtDate
= _T("%d/%m/%y");
3193 fmtDateAlt
= _T("%m/%d/%y");
3197 fmtDate
= _T("%m/%d/%y");
3198 fmtDateAlt
= _T("%d/%m/%y");
3201 const wxChar
*result
= dt
.ParseFormat(input
, fmtDate
);
3205 // ok, be nice and try another one
3206 result
= dt
.ParseFormat(input
, fmtDateAlt
);
3212 return (wxChar
*)NULL
;
3217 haveDay
= haveMon
= haveYear
= true;
3228 case _T('X'): // locale default time representation
3229 #ifdef HAVE_STRPTIME
3231 // use strptime() to do it for us (FIXME !Unicode friendly)
3233 input
= CallStrptime(input
, "%X", &tm
);
3236 return (wxChar
*)NULL
;
3239 haveHour
= haveMin
= haveSec
= true;
3245 #else // !HAVE_STRPTIME
3246 // TODO under Win32 we can query the LOCALE_ITIME system
3247 // setting which says whether the default time format is
3250 // try to parse what follows as "%H:%M:%S" and, if this
3251 // fails, as "%I:%M:%S %p" - this should catch the most
3255 const wxChar
*result
= dt
.ParseFormat(input
, _T("%T"));
3258 result
= dt
.ParseFormat(input
, _T("%r"));
3264 return (wxChar
*)NULL
;
3267 haveHour
= haveMin
= haveSec
= true;
3276 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3279 case _T('y'): // year without century (00-99)
3280 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
3283 return (wxChar
*)NULL
;
3288 // TODO should have an option for roll over date instead of
3289 // hard coding it here
3290 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
3293 case _T('Y'): // year with century
3294 if ( !GetNumericToken(width
, input
, &num
) )
3297 return (wxChar
*)NULL
;
3301 year
= (wxDateTime_t
)num
;
3304 case _T('Z'): // timezone name
3305 wxFAIL_MSG(_T("TODO"));
3308 case _T('%'): // a percent sign
3309 if ( *input
++ != _T('%') )
3312 return (wxChar
*)NULL
;
3316 case 0: // the end of string
3317 wxFAIL_MSG(_T("unexpected format end"));
3321 default: // not a known format spec
3322 return (wxChar
*)NULL
;
3326 // format matched, try to construct a date from what we have now
3328 if ( dateDef
.IsValid() )
3330 // take this date as default
3331 tmDef
= dateDef
.GetTm();
3333 else if ( IsValid() )
3335 // if this date is valid, don't change it
3340 // no default and this date is invalid - fall back to Today()
3341 tmDef
= Today().GetTm();
3352 // TODO we don't check here that the values are consistent, if both year
3353 // day and month/day were found, we just ignore the year day and we
3354 // also always ignore the week day
3355 if ( haveMon
&& haveDay
)
3357 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
3359 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3361 return (wxChar
*)NULL
;
3367 else if ( haveYDay
)
3369 if ( yday
> GetNumberOfDays(tm
.year
) )
3371 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3373 return (wxChar
*)NULL
;
3376 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
3383 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
3385 // translate to 24hour format
3388 //else: either already in 24h format or no translation needed
3408 // finally check that the week day is consistent -- if we had it
3409 if ( haveWDay
&& GetWeekDay() != wday
)
3411 wxLogDebug(_T("inconsistsnet week day in wxDateTime::ParseFormat()"));
3419 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3421 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3423 // Set to current day and hour, so strings like '14:00' becomes today at
3424 // 14, not some other random date
3425 wxDateTime dtDate
= wxDateTime::Today();
3426 wxDateTime dtTime
= wxDateTime::Today();
3428 const wxChar
* pchTime
;
3430 // Try to parse the beginning of the string as a date
3431 const wxChar
* pchDate
= dtDate
.ParseDate(date
);
3433 // We got a date in the beginning, see if there is a time specified after the date
3436 // Skip spaces, as the ParseTime() function fails on spaces
3437 while ( wxIsspace(*pchDate
) )
3440 pchTime
= dtTime
.ParseTime(pchDate
);
3442 else // no date in the beginning
3444 // check and see if we have a time followed by a date
3445 pchTime
= dtTime
.ParseTime(date
);
3448 while ( wxIsspace(*pchTime
) )
3451 pchDate
= dtDate
.ParseDate(pchTime
);
3455 // If we have a date specified, set our own data to the same date
3456 if ( !pchDate
|| !pchTime
)
3459 Set(dtDate
.GetDay(), dtDate
.GetMonth(), dtDate
.GetYear(),
3460 dtTime
.GetHour(), dtTime
.GetMinute(), dtTime
.GetSecond(),
3461 dtTime
.GetMillisecond());
3463 // Return endpoint of scan
3464 return pchDate
> pchTime
? pchDate
: pchTime
;
3467 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3469 // this is a simplified version of ParseDateTime() which understands only
3470 // "today" (for wxDate compatibility) and digits only otherwise (and not
3471 // all esoteric constructions ParseDateTime() knows about)
3473 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3475 const wxChar
*p
= date
;
3476 while ( wxIsspace(*p
) )
3479 // some special cases
3483 int dayDiffFromToday
;
3486 { wxTRANSLATE("today"), 0 },
3487 { wxTRANSLATE("yesterday"), -1 },
3488 { wxTRANSLATE("tomorrow"), 1 },
3491 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3493 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3494 size_t len
= date
.length();
3495 if ( wxStrlen(p
) >= len
)
3497 wxString
str(p
, len
);
3498 if ( str
.CmpNoCase(date
) == 0 )
3500 // nothing can follow this, so stop here
3503 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3505 if ( dayDiffFromToday
)
3507 *this += wxDateSpan::Days(dayDiffFromToday
);
3515 // We try to guess what we have here: for each new (numeric) token, we
3516 // determine if it can be a month, day or a year. Of course, there is an
3517 // ambiguity as some numbers may be days as well as months, so we also
3518 // have the ability to back track.
3521 bool haveDay
= false, // the months day?
3522 haveWDay
= false, // the day of week?
3523 haveMon
= false, // the month?
3524 haveYear
= false; // the year?
3526 // and the value of the items we have (init them to get rid of warnings)
3527 WeekDay wday
= Inv_WeekDay
;
3528 wxDateTime_t day
= 0;
3529 wxDateTime::Month mon
= Inv_Month
;
3532 // tokenize the string
3534 static const wxChar
*dateDelimiters
= _T(".,/-\t\r\n ");
3535 wxStringTokenizer
tok(p
, dateDelimiters
);
3536 while ( tok
.HasMoreTokens() )
3538 wxString token
= tok
.GetNextToken();
3544 if ( token
.ToULong(&val
) )
3546 // guess what this number is
3552 if ( !haveMon
&& val
> 0 && val
<= 12 )
3554 // assume it is month
3557 else // not the month
3561 // this can only be the year
3564 else // may be either day or year
3566 wxDateTime_t maxDays
= (wxDateTime_t
)(
3568 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3573 if ( (val
== 0) || (val
> (unsigned long)maxDays
) )
3578 else // yes, suppose it's the day
3592 year
= (wxDateTime_t
)val
;
3601 day
= (wxDateTime_t
)val
;
3607 mon
= (Month
)(val
- 1);
3610 else // not a number
3612 // be careful not to overwrite the current mon value
3613 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3614 if ( mon2
!= Inv_Month
)
3619 // but we already have a month - maybe we guessed wrong?
3622 // no need to check in month range as always < 12, but
3623 // the days are counted from 1 unlike the months
3624 day
= (wxDateTime_t
)(mon
+ 1);
3629 // could possible be the year (doesn't the year come
3630 // before the month in the japanese format?) (FIXME)
3639 else // not a valid month name
3641 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3642 if ( wday
!= Inv_WeekDay
)
3652 else // not a valid weekday name
3655 static const wxChar
*ordinals
[] =
3657 wxTRANSLATE("first"),
3658 wxTRANSLATE("second"),
3659 wxTRANSLATE("third"),
3660 wxTRANSLATE("fourth"),
3661 wxTRANSLATE("fifth"),
3662 wxTRANSLATE("sixth"),
3663 wxTRANSLATE("seventh"),
3664 wxTRANSLATE("eighth"),
3665 wxTRANSLATE("ninth"),
3666 wxTRANSLATE("tenth"),
3667 wxTRANSLATE("eleventh"),
3668 wxTRANSLATE("twelfth"),
3669 wxTRANSLATE("thirteenth"),
3670 wxTRANSLATE("fourteenth"),
3671 wxTRANSLATE("fifteenth"),
3672 wxTRANSLATE("sixteenth"),
3673 wxTRANSLATE("seventeenth"),
3674 wxTRANSLATE("eighteenth"),
3675 wxTRANSLATE("nineteenth"),
3676 wxTRANSLATE("twentieth"),
3677 // that's enough - otherwise we'd have problems with
3678 // composite (or not) ordinals
3682 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3684 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3690 if ( n
== WXSIZEOF(ordinals
) )
3692 // stop here - something unknown
3699 // don't try anything here (as in case of numeric day
3700 // above) - the symbolic day spec should always
3701 // precede the month/year
3707 day
= (wxDateTime_t
)(n
+ 1);
3712 nPosCur
= tok
.GetPosition();
3715 // either no more tokens or the scan was stopped by something we couldn't
3716 // parse - in any case, see if we can construct a date from what we have
3717 if ( !haveDay
&& !haveWDay
)
3719 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3721 return (wxChar
*)NULL
;
3724 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3725 !(haveDay
&& haveMon
&& haveYear
) )
3727 // without adjectives (which we don't support here) the week day only
3728 // makes sense completely separately or with the full date
3729 // specification (what would "Wed 1999" mean?)
3730 return (wxChar
*)NULL
;
3733 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3735 // may be we have month and day instead of day and year?
3736 if ( haveDay
&& !haveMon
)
3740 // exchange day and month
3741 mon
= (wxDateTime::Month
)(day
- 1);
3743 // we're in the current year then
3744 if ( (year
> 0) && (year
<= (int)GetNumOfDaysInMonth(Inv_Year
, mon
)) )
3746 day
= (wxDateTime_t
)year
;
3751 //else: no, can't exchange, leave haveMon == false
3757 // if we give the year, month and day must be given too
3758 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3760 return (wxChar
*)NULL
;
3766 mon
= GetCurrentMonth();
3771 year
= GetCurrentYear();
3776 Set(day
, mon
, year
);
3780 // check that it is really the same
3781 if ( GetWeekDay() != wday
)
3783 // inconsistency detected
3784 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3786 return (wxChar
*)NULL
;
3794 SetToWeekDayInSameWeek(wday
);
3797 // return the pointer to the first unparsed char
3799 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3801 // if we couldn't parse the token after the delimiter, put back the
3802 // delimiter as well
3809 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3811 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3813 // first try some extra things
3820 { wxTRANSLATE("noon"), 12 },
3821 { wxTRANSLATE("midnight"), 00 },
3825 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3827 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3828 size_t len
= timeString
.length();
3829 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3831 // casts required by DigitalMars
3832 Set(stdTimes
[n
].hour
, wxDateTime_t(0), wxDateTime_t(0));
3838 // try all time formats we may think about in the order from longest to
3841 // 12hour with AM/PM?
3842 const wxChar
*result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3846 // normally, it's the same, but why not try it?
3847 result
= ParseFormat(time
, _T("%H:%M:%S"));
3852 // 12hour with AM/PM but without seconds?
3853 result
= ParseFormat(time
, _T("%I:%M %p"));
3859 result
= ParseFormat(time
, _T("%H:%M"));
3864 // just the hour and AM/PM?
3865 result
= ParseFormat(time
, _T("%I %p"));
3871 result
= ParseFormat(time
, _T("%H"));
3876 // parse the standard format: normally it is one of the formats above
3877 // but it may be set to something completely different by the user
3878 result
= ParseFormat(time
, _T("%X"));
3881 // TODO: parse timezones
3886 // ----------------------------------------------------------------------------
3887 // Workdays and holidays support
3888 // ----------------------------------------------------------------------------
3890 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3892 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3895 // ============================================================================
3897 // ============================================================================
3899 wxDateSpan WXDLLIMPEXP_BASE
operator*(int n
, const wxDateSpan
& ds
)
3902 return ds1
.Multiply(n
);
3905 // ============================================================================
3907 // ============================================================================
3909 wxTimeSpan WXDLLIMPEXP_BASE
operator*(int n
, const wxTimeSpan
& ts
)
3911 return wxTimeSpan(ts
).Multiply(n
);
3914 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3915 // it locally to the method as it provokes an internal compiler error in egcs
3916 // 2.91.60 when building with -O2
3927 // not all strftime(3) format specifiers make sense here because, for example,
3928 // a time span doesn't have a year nor a timezone
3930 // Here are the ones which are supported (all of them are supported by strftime
3932 // %H hour in 24 hour format
3933 // %M minute (00 - 59)
3934 // %S second (00 - 59)
3937 // Also, for MFC CTimeSpan compatibility, we support
3938 // %D number of days
3940 // And, to be better than MFC :-), we also have
3941 // %E number of wEeks
3942 // %l milliseconds (000 - 999)
3943 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3945 wxCHECK_MSG( format
, wxEmptyString
, _T("NULL format in wxTimeSpan::Format") );
3948 str
.Alloc(wxStrlen(format
));
3950 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3952 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3953 // question is what should ts.Format("%S") do? The code here returns "3273"
3954 // in this case (i.e. the total number of seconds, not just seconds % 60)
3955 // because, for me, this call means "give me entire time interval in
3956 // seconds" and not "give me the seconds part of the time interval"
3958 // If we agree that it should behave like this, it is clear that the
3959 // interpretation of each format specifier depends on the presence of the
3960 // other format specs in the string: if there was "%H" before "%M", we
3961 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3963 // we remember the most important unit found so far
3964 TimeSpanPart partBiggest
= Part_MSec
;
3966 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3970 if ( ch
== _T('%') )
3972 // the start of the format specification of the printf() below
3973 wxString fmtPrefix
= _T('%');
3978 ch
= *++pch
; // get the format spec char
3982 wxFAIL_MSG( _T("invalid format character") );
3988 // skip the part below switch
3993 if ( partBiggest
< Part_Day
)
3999 partBiggest
= Part_Day
;
4004 partBiggest
= Part_Week
;
4010 if ( partBiggest
< Part_Hour
)
4016 partBiggest
= Part_Hour
;
4019 fmtPrefix
+= _T("02");
4023 n
= GetMilliseconds().ToLong();
4024 if ( partBiggest
< Part_MSec
)
4028 //else: no need to reset partBiggest to Part_MSec, it is
4029 // the least significant one anyhow
4031 fmtPrefix
+= _T("03");
4036 if ( partBiggest
< Part_Min
)
4042 partBiggest
= Part_Min
;
4045 fmtPrefix
+= _T("02");
4049 n
= GetSeconds().ToLong();
4050 if ( partBiggest
< Part_Sec
)
4056 partBiggest
= Part_Sec
;
4059 fmtPrefix
+= _T("02");
4063 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
4067 // normal character, just copy
4075 // ============================================================================
4076 // wxDateTimeHolidayAuthority and related classes
4077 // ============================================================================
4079 #include "wx/arrimpl.cpp"
4081 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
4083 static int wxCMPFUNC_CONV
4084 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
4086 wxDateTime dt1
= **first
,
4089 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
4092 // ----------------------------------------------------------------------------
4093 // wxDateTimeHolidayAuthority
4094 // ----------------------------------------------------------------------------
4096 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
4099 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
4101 size_t count
= ms_authorities
.size();
4102 for ( size_t n
= 0; n
< count
; n
++ )
4104 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
4115 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
4116 const wxDateTime
& dtEnd
,
4117 wxDateTimeArray
& holidays
)
4119 wxDateTimeArray hol
;
4123 size_t count
= ms_authorities
.size();
4124 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
4126 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
4128 WX_APPEND_ARRAY(holidays
, hol
);
4131 holidays
.Sort(wxDateTimeCompareFunc
);
4133 return holidays
.size();
4137 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
4139 WX_CLEAR_ARRAY(ms_authorities
);
4143 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
4145 ms_authorities
.push_back(auth
);
4148 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
4150 // required here for Darwin
4153 // ----------------------------------------------------------------------------
4154 // wxDateTimeWorkDays
4155 // ----------------------------------------------------------------------------
4157 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
4159 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
4161 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
4164 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
4165 const wxDateTime
& dtEnd
,
4166 wxDateTimeArray
& holidays
) const
4168 if ( dtStart
> dtEnd
)
4170 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
4177 // instead of checking all days, start with the first Sat after dtStart and
4178 // end with the last Sun before dtEnd
4179 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
4180 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
4181 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
4182 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
4185 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
4190 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
4195 return holidays
.GetCount();
4198 // ============================================================================
4199 // other helper functions
4200 // ============================================================================
4202 // ----------------------------------------------------------------------------
4203 // iteration helpers: can be used to write a for loop over enum variable like
4205 // for ( m = wxDateTime::Jan; m < wxDateTime::Inv_Month; wxNextMonth(m) )
4206 // ----------------------------------------------------------------------------
4208 WXDLLIMPEXP_BASE
void wxNextMonth(wxDateTime::Month
& m
)
4210 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, _T("invalid month") );
4212 // no wrapping or the for loop above would never end!
4213 m
= (wxDateTime::Month
)(m
+ 1);
4216 WXDLLIMPEXP_BASE
void wxPrevMonth(wxDateTime::Month
& m
)
4218 wxASSERT_MSG( m
< wxDateTime::Inv_Month
, _T("invalid month") );
4220 m
= m
== wxDateTime::Jan
? wxDateTime::Inv_Month
4221 : (wxDateTime::Month
)(m
- 1);
4224 WXDLLIMPEXP_BASE
void wxNextWDay(wxDateTime::WeekDay
& wd
)
4226 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, _T("invalid week day") );
4228 // no wrapping or the for loop above would never end!
4229 wd
= (wxDateTime::WeekDay
)(wd
+ 1);
4232 WXDLLIMPEXP_BASE
void wxPrevWDay(wxDateTime::WeekDay
& wd
)
4234 wxASSERT_MSG( wd
< wxDateTime::Inv_WeekDay
, _T("invalid week day") );
4236 wd
= wd
== wxDateTime::Sun
? wxDateTime::Inv_WeekDay
4237 : (wxDateTime::WeekDay
)(wd
- 1);
4240 #endif // wxUSE_DATETIME