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 // ----------------------------------------------------------------------------
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/timer.h" // for wxGetLocalTimeMillis()
83 const long wxDateTime::TIME_T_FACTOR
= 1000l;
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 #if defined(HAVE_STRPTIME) && defined(__GLIBC__) && \
90 ((__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
91 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
92 // crash (instead of just failing):
94 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
95 // strptime(buf, "%x", &tm);
99 #endif // broken strptime()
101 #if defined(__MWERKS__) && wxUSE_UNICODE
105 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
106 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
107 #define WX_TIMEZONE _timezone
108 #elif defined(__MWERKS__)
109 long wxmw_timezone
= 28800;
110 #define WX_TIMEZONE wxmw_timezone
111 #elif defined(__DJGPP__) || defined(__WINE__)
112 #include <sys/timeb.h>
114 static long wxGetTimeZone()
116 static long timezone
= MAXLONG
; // invalid timezone
117 if (timezone
== MAXLONG
)
121 timezone
= tb
.timezone
;
125 #define WX_TIMEZONE wxGetTimeZone()
126 #elif defined(__DARWIN__)
127 #define WX_GMTOFF_IN_TM
128 #else // unknown platform - try timezone
129 #define WX_TIMEZONE timezone
131 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 // debugging helper: just a convenient replacement of wxCHECK()
138 #define wxDATETIME_CHECK(expr, msg) \
142 *this = wxInvalidDateTime; \
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
150 class wxDateTimeHolidaysModule
: public wxModule
153 virtual bool OnInit()
155 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
160 virtual void OnExit()
162 wxDateTimeHolidayAuthority::ClearAllAuthorities();
163 wxDateTimeHolidayAuthority::ms_authorities
.clear();
167 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
170 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
177 static const int MONTHS_IN_YEAR
= 12;
179 static const int SEC_PER_MIN
= 60;
181 static const int MIN_PER_HOUR
= 60;
183 static const int HOURS_PER_DAY
= 24;
185 static const long SECONDS_PER_DAY
= 86400l;
187 static const int DAYS_PER_WEEK
= 7;
189 static const long MILLISECONDS_PER_DAY
= 86400000l;
191 // this is the integral part of JDN of the midnight of Jan 1, 1970
192 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
193 static const long EPOCH_JDN
= 2440587l;
195 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
196 // reference date for us) is Nov 24, 4714BC
197 static const int JDN_0_YEAR
= -4713;
198 static const int JDN_0_MONTH
= wxDateTime::Nov
;
199 static const int JDN_0_DAY
= 24;
201 // the constants used for JDN calculations
202 static const long JDN_OFFSET
= 32046l;
203 static const long DAYS_PER_5_MONTHS
= 153l;
204 static const long DAYS_PER_4_YEARS
= 1461l;
205 static const long DAYS_PER_400_YEARS
= 146097l;
207 // this array contains the cumulated number of days in all previous months for
208 // normal and leap years
209 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
211 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
212 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
215 // ----------------------------------------------------------------------------
217 // ----------------------------------------------------------------------------
219 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
220 // indicate an invalid wxDateTime object
221 const wxDateTime wxDefaultDateTime
;
223 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 // debugger helper: shows what the date really is
231 extern const wxChar
*wxDumpDate(const wxDateTime
* dt
)
233 static wxChar buf
[128];
235 wxStrcpy(buf
, dt
->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
241 // get the number of days in the given month of the given year
243 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
245 // the number of days in month in Julian/Gregorian calendar: the first line
246 // is for normal years, the second one is for the leap ones
247 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
249 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
250 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
253 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
256 // returns the time zone in the C sense, i.e. the difference UTC - local
258 static int GetTimeZone()
260 // set to TRUE when the timezone is set
261 static bool s_timezoneSet
= FALSE
;
262 #ifdef WX_GMTOFF_IN_TM
263 static long gmtoffset
= LONG_MAX
; // invalid timezone
266 // ensure that the timezone variable is set by calling localtime
267 if ( !s_timezoneSet
)
269 // just call localtime() instead of figuring out whether this system
270 // supports tzset(), _tzset() or something else
275 s_timezoneSet
= TRUE
;
277 #ifdef WX_GMTOFF_IN_TM
278 // note that GMT offset is the opposite of time zone and so to return
279 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
280 // cases we have to negate it
281 gmtoffset
= -tm
->tm_gmtoff
;
285 #ifdef WX_GMTOFF_IN_TM
286 return (int)gmtoffset
;
288 return (int)WX_TIMEZONE
;
292 // return the integral part of the JDN for the midnight of the given date (to
293 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
294 // noon of the previous day)
295 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
296 wxDateTime::Month mon
,
299 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
301 // check the date validity
303 (year
> JDN_0_YEAR
) ||
304 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
305 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
306 _T("date out of range - can't convert to JDN")
309 // make the year positive to avoid problems with negative numbers division
312 // months are counted from March here
314 if ( mon
>= wxDateTime::Mar
)
324 // now we can simply add all the contributions together
325 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
326 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
327 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
332 // this function is a wrapper around strftime(3) adding error checking
333 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
336 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
338 // buffer is too small?
339 wxFAIL_MSG(_T("strftime() failed"));
342 return wxString(buf
);
347 // Unicode-friendly strptime() wrapper
348 static const wxChar
*
349 CallStrptime(const wxChar
*input
, const char *fmt
, tm
*tm
)
351 // the problem here is that strptime() returns pointer into the string we
352 // passed to it while we're really interested in the pointer into the
353 // original, Unicode, string so we try to transform the pointer back
355 wxCharBuffer
inputMB(wxConvertWX2MB(input
));
357 const char * const inputMB
= input
;
358 #endif // Unicode/Ascii
360 const char *result
= strptime(inputMB
, fmt
, tm
);
365 // FIXME: this is wrong in presence of surrogates &c
366 return input
+ (result
- inputMB
.data());
369 #endif // Unicode/Ascii
372 #endif // HAVE_STRPTIME
374 // if year and/or month have invalid values, replace them with the current ones
375 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
376 wxDateTime::Month
*month
)
378 struct tm
*tmNow
= NULL
;
380 if ( *year
== wxDateTime::Inv_Year
)
382 tmNow
= wxDateTime::GetTmNow();
384 *year
= 1900 + tmNow
->tm_year
;
387 if ( *month
== wxDateTime::Inv_Month
)
390 tmNow
= wxDateTime::GetTmNow();
392 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
396 // fll the struct tm with default values
397 static void InitTm(struct tm
& tm
)
399 // struct tm may have etxra fields (undocumented and with unportable
400 // names) which, nevertheless, must be set to 0
401 memset(&tm
, 0, sizeof(struct tm
));
403 tm
.tm_mday
= 1; // mday 0 is invalid
404 tm
.tm_year
= 76; // any valid year
405 tm
.tm_isdst
= -1; // auto determine
411 // return the month if the string is a month name or Inv_Month otherwise
412 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
414 wxDateTime::Month mon
;
415 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
417 // case-insensitive comparison either one of or with both abbreviated
419 if ( flags
& wxDateTime::Name_Full
)
421 if ( name
.CmpNoCase(wxDateTime::
422 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
428 if ( flags
& wxDateTime::Name_Abbr
)
430 if ( name
.CmpNoCase(wxDateTime::
431 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
441 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
442 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
444 wxDateTime::WeekDay wd
;
445 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
447 // case-insensitive comparison either one of or with both abbreviated
449 if ( flags
& wxDateTime::Name_Full
)
451 if ( name
.CmpNoCase(wxDateTime::
452 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
458 if ( flags
& wxDateTime::Name_Abbr
)
460 if ( name
.CmpNoCase(wxDateTime::
461 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
471 // scans all digits (but no more than len) and returns the resulting number
472 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
476 while ( wxIsdigit(*p
) )
480 if ( len
&& ++n
> len
)
484 return !!s
&& s
.ToULong(number
);
487 // scans all alphabetic characters and returns the resulting string
488 static wxString
GetAlphaToken(const wxChar
*& p
)
491 while ( wxIsalpha(*p
) )
499 // ============================================================================
500 // implementation of wxDateTime
501 // ============================================================================
503 // ----------------------------------------------------------------------------
505 // ----------------------------------------------------------------------------
509 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
510 mon
= wxDateTime::Inv_Month
;
512 hour
= min
= sec
= msec
= 0;
513 wday
= wxDateTime::Inv_WeekDay
;
516 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
524 mon
= (wxDateTime::Month
)tm
.tm_mon
;
525 year
= 1900 + tm
.tm_year
;
530 bool wxDateTime::Tm::IsValid() const
532 // we allow for the leap seconds, although we don't use them (yet)
533 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
534 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
535 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
538 void wxDateTime::Tm::ComputeWeekDay()
540 // compute the week day from day/month/year: we use the dumbest algorithm
541 // possible: just compute our JDN and then use the (simple to derive)
542 // formula: weekday = (JDN + 1.5) % 7
543 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
546 void wxDateTime::Tm::AddMonths(int monDiff
)
548 // normalize the months field
549 while ( monDiff
< -mon
)
553 monDiff
+= MONTHS_IN_YEAR
;
556 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
560 monDiff
-= MONTHS_IN_YEAR
;
563 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
565 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
567 // NB: we don't check here that the resulting date is valid, this function
568 // is private and the caller must check it if needed
571 void wxDateTime::Tm::AddDays(int dayDiff
)
573 // normalize the days field
574 while ( dayDiff
+ mday
< 1 )
578 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
582 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
584 mday
-= GetNumOfDaysInMonth(year
, mon
);
589 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
593 // ----------------------------------------------------------------------------
595 // ----------------------------------------------------------------------------
597 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
601 case wxDateTime::Local
:
602 // get the offset from C RTL: it returns the difference GMT-local
603 // while we want to have the offset _from_ GMT, hence the '-'
604 m_offset
= -GetTimeZone();
607 case wxDateTime::GMT_12
:
608 case wxDateTime::GMT_11
:
609 case wxDateTime::GMT_10
:
610 case wxDateTime::GMT_9
:
611 case wxDateTime::GMT_8
:
612 case wxDateTime::GMT_7
:
613 case wxDateTime::GMT_6
:
614 case wxDateTime::GMT_5
:
615 case wxDateTime::GMT_4
:
616 case wxDateTime::GMT_3
:
617 case wxDateTime::GMT_2
:
618 case wxDateTime::GMT_1
:
619 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
622 case wxDateTime::GMT0
:
623 case wxDateTime::GMT1
:
624 case wxDateTime::GMT2
:
625 case wxDateTime::GMT3
:
626 case wxDateTime::GMT4
:
627 case wxDateTime::GMT5
:
628 case wxDateTime::GMT6
:
629 case wxDateTime::GMT7
:
630 case wxDateTime::GMT8
:
631 case wxDateTime::GMT9
:
632 case wxDateTime::GMT10
:
633 case wxDateTime::GMT11
:
634 case wxDateTime::GMT12
:
635 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
638 case wxDateTime::A_CST
:
639 // Central Standard Time in use in Australia = UTC + 9.5
640 m_offset
= 60l*(9*60 + 30);
644 wxFAIL_MSG( _T("unknown time zone") );
648 // ----------------------------------------------------------------------------
650 // ----------------------------------------------------------------------------
653 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
655 if ( year
== Inv_Year
)
656 year
= GetCurrentYear();
658 if ( cal
== Gregorian
)
660 // in Gregorian calendar leap years are those divisible by 4 except
661 // those divisible by 100 unless they're also divisible by 400
662 // (in some countries, like Russia and Greece, additional corrections
663 // exist, but they won't manifest themselves until 2700)
664 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
666 else if ( cal
== Julian
)
668 // in Julian calendar the rule is simpler
669 return year
% 4 == 0;
673 wxFAIL_MSG(_T("unknown calendar"));
680 int wxDateTime::GetCentury(int year
)
682 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
686 int wxDateTime::ConvertYearToBC(int year
)
689 return year
> 0 ? year
: year
- 1;
693 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
698 return Now().GetYear();
701 wxFAIL_MSG(_T("TODO"));
705 wxFAIL_MSG(_T("unsupported calendar"));
713 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
718 return Now().GetMonth();
721 wxFAIL_MSG(_T("TODO"));
725 wxFAIL_MSG(_T("unsupported calendar"));
733 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
735 if ( year
== Inv_Year
)
737 // take the current year if none given
738 year
= GetCurrentYear();
745 return IsLeapYear(year
) ? 366 : 365;
748 wxFAIL_MSG(_T("unsupported calendar"));
756 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
758 wxDateTime::Calendar cal
)
760 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
762 if ( cal
== Gregorian
|| cal
== Julian
)
764 if ( year
== Inv_Year
)
766 // take the current year if none given
767 year
= GetCurrentYear();
770 return GetNumOfDaysInMonth(year
, month
);
774 wxFAIL_MSG(_T("unsupported calendar"));
781 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
782 wxDateTime::NameFlags flags
)
784 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
786 // notice that we must set all the fields to avoid confusing libc (GNU one
787 // gets confused to a crash if we don't do this)
792 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
796 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
797 wxDateTime::NameFlags flags
)
799 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
801 // take some arbitrary Sunday
808 // and offset it by the number of days needed to get the correct wday
811 // call mktime() to normalize it...
814 // ... and call strftime()
815 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
819 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
825 *am
= CallStrftime(_T("%p"), &tm
);
830 *pm
= CallStrftime(_T("%p"), &tm
);
834 // ----------------------------------------------------------------------------
835 // Country stuff: date calculations depend on the country (DST, work days,
836 // ...), so we need to know which rules to follow.
837 // ----------------------------------------------------------------------------
840 wxDateTime::Country
wxDateTime::GetCountry()
842 // TODO use LOCALE_ICOUNTRY setting under Win32
844 if ( ms_country
== Country_Unknown
)
846 // try to guess from the time zone name
847 time_t t
= time(NULL
);
848 struct tm
*tm
= localtime(&t
);
850 wxString tz
= CallStrftime(_T("%Z"), tm
);
851 if ( tz
== _T("WET") || tz
== _T("WEST") )
855 else if ( tz
== _T("CET") || tz
== _T("CEST") )
857 ms_country
= Country_EEC
;
859 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
863 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
864 tz
== _T("EST") || tz
== _T("EDT") ||
865 tz
== _T("CST") || tz
== _T("CDT") ||
866 tz
== _T("MST") || tz
== _T("MDT") ||
867 tz
== _T("PST") || tz
== _T("PDT") )
873 // well, choose a default one
882 void wxDateTime::SetCountry(wxDateTime::Country country
)
884 ms_country
= country
;
888 bool wxDateTime::IsWestEuropeanCountry(Country country
)
890 if ( country
== Country_Default
)
892 country
= GetCountry();
895 return (Country_WesternEurope_Start
<= country
) &&
896 (country
<= Country_WesternEurope_End
);
899 // ----------------------------------------------------------------------------
900 // DST calculations: we use 3 different rules for the West European countries,
901 // USA and for the rest of the world. This is undoubtedly false for many
902 // countries, but I lack the necessary info (and the time to gather it),
903 // please add the other rules here!
904 // ----------------------------------------------------------------------------
907 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
909 if ( year
== Inv_Year
)
911 // take the current year if none given
912 year
= GetCurrentYear();
915 if ( country
== Country_Default
)
917 country
= GetCountry();
924 // DST was first observed in the US and UK during WWI, reused
925 // during WWII and used again since 1966
926 return year
>= 1966 ||
927 (year
>= 1942 && year
<= 1945) ||
928 (year
== 1918 || year
== 1919);
931 // assume that it started after WWII
937 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
939 if ( year
== Inv_Year
)
941 // take the current year if none given
942 year
= GetCurrentYear();
945 if ( country
== Country_Default
)
947 country
= GetCountry();
950 if ( !IsDSTApplicable(year
, country
) )
952 return wxInvalidDateTime
;
957 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
959 // DST begins at 1 a.m. GMT on the last Sunday of March
960 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
963 wxFAIL_MSG( _T("no last Sunday in March?") );
966 dt
+= wxTimeSpan::Hours(1);
968 // disable DST tests because it could result in an infinite recursion!
971 else switch ( country
)
978 // don't know for sure - assume it was in effect all year
983 dt
.Set(1, Jan
, year
);
987 // DST was installed Feb 2, 1942 by the Congress
988 dt
.Set(2, Feb
, year
);
991 // Oil embargo changed the DST period in the US
993 dt
.Set(6, Jan
, 1974);
997 dt
.Set(23, Feb
, 1975);
1001 // before 1986, DST begun on the last Sunday of April, but
1002 // in 1986 Reagan changed it to begin at 2 a.m. of the
1003 // first Sunday in April
1006 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1009 wxFAIL_MSG( _T("no first Sunday in April?") );
1014 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1017 wxFAIL_MSG( _T("no first Sunday in April?") );
1021 dt
+= wxTimeSpan::Hours(2);
1023 // TODO what about timezone??
1029 // assume Mar 30 as the start of the DST for the rest of the world
1030 // - totally bogus, of course
1031 dt
.Set(30, Mar
, year
);
1038 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1040 if ( year
== Inv_Year
)
1042 // take the current year if none given
1043 year
= GetCurrentYear();
1046 if ( country
== Country_Default
)
1048 country
= GetCountry();
1051 if ( !IsDSTApplicable(year
, country
) )
1053 return wxInvalidDateTime
;
1058 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1060 // DST ends at 1 a.m. GMT on the last Sunday of October
1061 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1063 // weirder and weirder...
1064 wxFAIL_MSG( _T("no last Sunday in October?") );
1067 dt
+= wxTimeSpan::Hours(1);
1069 // disable DST tests because it could result in an infinite recursion!
1072 else switch ( country
)
1079 // don't know for sure - assume it was in effect all year
1083 dt
.Set(31, Dec
, year
);
1087 // the time was reset after the end of the WWII
1088 dt
.Set(30, Sep
, year
);
1092 // DST ends at 2 a.m. on the last Sunday of October
1093 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1095 // weirder and weirder...
1096 wxFAIL_MSG( _T("no last Sunday in October?") );
1099 dt
+= wxTimeSpan::Hours(2);
1101 // TODO what about timezone??
1106 // assume October 26th as the end of the DST - totally bogus too
1107 dt
.Set(26, Oct
, year
);
1113 // ----------------------------------------------------------------------------
1114 // constructors and assignment operators
1115 // ----------------------------------------------------------------------------
1117 // return the current time with ms precision
1118 /* static */ wxDateTime
wxDateTime::UNow()
1120 return wxDateTime(wxGetLocalTimeMillis());
1123 // the values in the tm structure contain the local time
1124 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1127 time_t timet
= mktime(&tm2
);
1129 if ( timet
== (time_t)-1 )
1131 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1132 // less than timezone - try to make it work for this case
1133 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1135 // add timezone to make sure that date is in range
1136 tm2
.tm_sec
-= GetTimeZone();
1138 timet
= mktime(&tm2
);
1139 if ( timet
!= (time_t)-1 )
1141 timet
+= GetTimeZone();
1147 wxFAIL_MSG( _T("mktime() failed") );
1149 *this = wxInvalidDateTime
;
1159 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1160 wxDateTime_t minute
,
1161 wxDateTime_t second
,
1162 wxDateTime_t millisec
)
1164 // we allow seconds to be 61 to account for the leap seconds, even if we
1165 // don't use them really
1166 wxDATETIME_CHECK( hour
< 24 &&
1170 _T("Invalid time in wxDateTime::Set()") );
1172 // get the current date from system
1173 struct tm
*tm
= GetTmNow();
1175 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1179 tm
->tm_min
= minute
;
1180 tm
->tm_sec
= second
;
1184 // and finally adjust milliseconds
1185 return SetMillisecond(millisec
);
1188 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1192 wxDateTime_t minute
,
1193 wxDateTime_t second
,
1194 wxDateTime_t millisec
)
1196 wxDATETIME_CHECK( hour
< 24 &&
1200 _T("Invalid time in wxDateTime::Set()") );
1202 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1204 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1205 _T("Invalid date in wxDateTime::Set()") );
1207 // the range of time_t type (inclusive)
1208 static const int yearMinInRange
= 1970;
1209 static const int yearMaxInRange
= 2037;
1211 // test only the year instead of testing for the exact end of the Unix
1212 // time_t range - it doesn't bring anything to do more precise checks
1213 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1215 // use the standard library version if the date is in range - this is
1216 // probably more efficient than our code
1218 tm
.tm_year
= year
- 1900;
1224 tm
.tm_isdst
= -1; // mktime() will guess it
1228 // and finally adjust milliseconds
1229 return SetMillisecond(millisec
);
1233 // do time calculations ourselves: we want to calculate the number of
1234 // milliseconds between the given date and the epoch
1236 // get the JDN for the midnight of this day
1237 m_time
= GetTruncatedJDN(day
, month
, year
);
1238 m_time
-= EPOCH_JDN
;
1239 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1241 // JDN corresponds to GMT, we take localtime
1242 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1248 wxDateTime
& wxDateTime::Set(double jdn
)
1250 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1252 jdn
-= EPOCH_JDN
+ 0.5;
1254 jdn
*= MILLISECONDS_PER_DAY
;
1261 wxDateTime
& wxDateTime::ResetTime()
1265 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1278 // ----------------------------------------------------------------------------
1279 // DOS Date and Time Format functions
1280 // ----------------------------------------------------------------------------
1281 // the dos date and time value is an unsigned 32 bit value in the format:
1282 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1284 // Y = year offset from 1980 (0-127)
1286 // D = day of month (1-31)
1288 // m = minute (0-59)
1289 // s = bisecond (0-29) each bisecond indicates two seconds
1290 // ----------------------------------------------------------------------------
1292 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1296 long year
= ddt
& 0xFE000000;
1301 long month
= ddt
& 0x1E00000;
1306 long day
= ddt
& 0x1F0000;
1310 long hour
= ddt
& 0xF800;
1314 long minute
= ddt
& 0x7E0;
1318 long second
= ddt
& 0x1F;
1319 tm
.tm_sec
= second
* 2;
1321 return Set(mktime(&tm
));
1324 unsigned long wxDateTime::GetAsDOS() const
1327 time_t ticks
= GetTicks();
1328 struct tm
*tm
= localtime(&ticks
);
1330 long year
= tm
->tm_year
;
1334 long month
= tm
->tm_mon
;
1338 long day
= tm
->tm_mday
;
1341 long hour
= tm
->tm_hour
;
1344 long minute
= tm
->tm_min
;
1347 long second
= tm
->tm_sec
;
1350 ddt
= year
| month
| day
| hour
| minute
| second
;
1354 // ----------------------------------------------------------------------------
1355 // time_t <-> broken down time conversions
1356 // ----------------------------------------------------------------------------
1358 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1360 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1362 time_t time
= GetTicks();
1363 if ( time
!= (time_t)-1 )
1365 // use C RTL functions
1367 if ( tz
.GetOffset() == -GetTimeZone() )
1369 // we are working with local time
1370 tm
= localtime(&time
);
1372 // should never happen
1373 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1377 time
+= (time_t)tz
.GetOffset();
1378 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1379 int time2
= (int) time
;
1387 // should never happen
1388 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1392 tm
= (struct tm
*)NULL
;
1398 // adjust the milliseconds
1400 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1401 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1404 //else: use generic code below
1407 // remember the time and do the calculations with the date only - this
1408 // eliminates rounding errors of the floating point arithmetics
1410 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1412 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1414 // we want to always have positive time and timeMidnight to be really
1415 // the midnight before it
1418 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1421 timeMidnight
-= timeOnly
;
1423 // calculate the Gregorian date from JDN for the midnight of our date:
1424 // this will yield day, month (in 1..12 range) and year
1426 // actually, this is the JDN for the noon of the previous day
1427 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1429 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1431 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1433 // calculate the century
1434 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1435 long century
= temp
/ DAYS_PER_400_YEARS
;
1437 // then the year and day of year (1 <= dayOfYear <= 366)
1438 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1439 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1440 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1442 // and finally the month and day of the month
1443 temp
= dayOfYear
* 5 - 3;
1444 long month
= temp
/ DAYS_PER_5_MONTHS
;
1445 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1447 // month is counted from March - convert to normal
1458 // year is offset by 4800
1461 // check that the algorithm gave us something reasonable
1462 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1463 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1465 // construct Tm from these values
1467 tm
.year
= (int)year
;
1468 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1469 tm
.mday
= (wxDateTime_t
)day
;
1470 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1471 timeOnly
-= tm
.msec
;
1472 timeOnly
/= 1000; // now we have time in seconds
1474 tm
.sec
= (wxDateTime_t
)(timeOnly
% 60);
1476 timeOnly
/= 60; // now we have time in minutes
1478 tm
.min
= (wxDateTime_t
)(timeOnly
% 60);
1481 tm
.hour
= (wxDateTime_t
)(timeOnly
/ 60);
1486 wxDateTime
& wxDateTime::SetYear(int year
)
1488 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1497 wxDateTime
& wxDateTime::SetMonth(Month month
)
1499 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1508 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1510 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1519 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1521 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1530 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1532 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1541 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1543 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1552 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1554 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1556 // we don't need to use GetTm() for this one
1557 m_time
-= m_time
% 1000l;
1558 m_time
+= millisecond
;
1563 // ----------------------------------------------------------------------------
1564 // wxDateTime arithmetics
1565 // ----------------------------------------------------------------------------
1567 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1571 tm
.year
+= diff
.GetYears();
1572 tm
.AddMonths(diff
.GetMonths());
1574 // check that the resulting date is valid
1575 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1577 // We suppose that when adding one month to Jan 31 we want to get Feb
1578 // 28 (or 29), i.e. adding a month to the last day of the month should
1579 // give the last day of the next month which is quite logical.
1581 // Unfortunately, there is no logic way to understand what should
1582 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1583 // We make it Feb 28 (last day too), but it is highly questionable.
1584 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1587 tm
.AddDays(diff
.GetTotalDays());
1591 wxASSERT_MSG( IsSameTime(tm
),
1592 _T("Add(wxDateSpan) shouldn't modify time") );
1597 // ----------------------------------------------------------------------------
1598 // Weekday and monthday stuff
1599 // ----------------------------------------------------------------------------
1601 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1605 wxASSERT_MSG( numWeek
> 0,
1606 _T("invalid week number: weeks are counted from 1") );
1608 int year
= GetYear();
1610 // Jan 4 always lies in the 1st week of the year
1612 SetToWeekDayInSameWeek(weekday
, flags
) += wxDateSpan::Weeks(numWeek
- 1);
1614 if ( GetYear() != year
)
1616 // oops... numWeek was too big
1623 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1626 // take the current month/year if none specified
1627 if ( year
== Inv_Year
)
1629 if ( month
== Inv_Month
)
1632 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1635 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1637 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1639 int wdayThis
= GetWeekDay();
1640 if ( weekday
== wdayThis
)
1646 if ( flags
== Default_First
)
1648 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1651 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1652 // is the first day in the week, but breaks down for Monday_First case so
1653 // we adjust the week days in this case
1654 if( flags
== Monday_First
)
1656 if ( wdayThis
== Sun
)
1659 //else: Sunday_First, nothing to do
1661 // go forward or back in time to the day we want
1662 if ( weekday
< wdayThis
)
1664 return Subtract(wxDateSpan::Days(wdayThis
- weekday
));
1666 else // weekday > wdayThis
1668 return Add(wxDateSpan::Days(weekday
- wdayThis
));
1672 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1674 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1677 WeekDay wdayThis
= GetWeekDay();
1678 if ( weekday
== wdayThis
)
1683 else if ( weekday
< wdayThis
)
1685 // need to advance a week
1686 diff
= 7 - (wdayThis
- weekday
);
1688 else // weekday > wdayThis
1690 diff
= weekday
- wdayThis
;
1693 return Add(wxDateSpan::Days(diff
));
1696 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1698 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1701 WeekDay wdayThis
= GetWeekDay();
1702 if ( weekday
== wdayThis
)
1707 else if ( weekday
> wdayThis
)
1709 // need to go to previous week
1710 diff
= 7 - (weekday
- wdayThis
);
1712 else // weekday < wdayThis
1714 diff
= wdayThis
- weekday
;
1717 return Subtract(wxDateSpan::Days(diff
));
1720 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1725 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1727 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1728 // anyhow in such case - but may be should still give an assert for it?
1730 // take the current month/year if none specified
1731 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1735 // TODO this probably could be optimised somehow...
1739 // get the first day of the month
1740 dt
.Set(1, month
, year
);
1743 WeekDay wdayFirst
= dt
.GetWeekDay();
1745 // go to the first weekday of the month
1746 int diff
= weekday
- wdayFirst
;
1750 // add advance n-1 weeks more
1753 dt
+= wxDateSpan::Days(diff
);
1755 else // count from the end of the month
1757 // get the last day of the month
1758 dt
.SetToLastMonthDay(month
, year
);
1761 WeekDay wdayLast
= dt
.GetWeekDay();
1763 // go to the last weekday of the month
1764 int diff
= wdayLast
- weekday
;
1768 // and rewind n-1 weeks from there
1771 dt
-= wxDateSpan::Days(diff
);
1774 // check that it is still in the same month
1775 if ( dt
.GetMonth() == month
)
1783 // no such day in this month
1788 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1792 return gs_cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1795 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
,
1796 const TimeZone
& tz
) const
1798 if ( flags
== Default_First
)
1800 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1803 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1806 WeekDay wd
= GetWeekDay(tz
);
1807 if ( flags
== Sunday_First
)
1809 week
= (nDayInYear
- wd
+ 7) / 7;
1813 // have to shift the week days values
1814 week
= (nDayInYear
- (wd
- 1 + 7) % 7 + 7) / 7;
1817 // FIXME some more elegant way??
1818 WeekDay wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1819 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1827 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1828 const TimeZone
& tz
) const
1831 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
1832 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
1835 // this may happen for January when Jan, 1 is the last week of the
1837 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
1840 return (wxDateTime::wxDateTime_t
)nWeek
;
1843 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
1845 int year
= GetYear();
1846 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
1847 _T("invalid year day") );
1849 bool isLeap
= IsLeapYear(year
);
1850 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
1852 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1853 // don't need it neither - because of the CHECK above we know that
1854 // yday lies in December then
1855 if ( (mon
== Dec
) || (yday
< gs_cumulatedDays
[isLeap
][mon
+ 1]) )
1857 Set(yday
- gs_cumulatedDays
[isLeap
][mon
], mon
, year
);
1866 // ----------------------------------------------------------------------------
1867 // Julian day number conversion and related stuff
1868 // ----------------------------------------------------------------------------
1870 double wxDateTime::GetJulianDayNumber() const
1872 // JDN are always expressed for the GMT dates
1873 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1875 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1877 // add the part GetTruncatedJDN() neglected
1880 // and now add the time: 86400 sec = 1 JDN
1881 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1884 double wxDateTime::GetRataDie() const
1886 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1887 return GetJulianDayNumber() - 1721119.5 - 306;
1890 // ----------------------------------------------------------------------------
1891 // timezone and DST stuff
1892 // ----------------------------------------------------------------------------
1894 int wxDateTime::IsDST(wxDateTime::Country country
) const
1896 wxCHECK_MSG( country
== Country_Default
, -1,
1897 _T("country support not implemented") );
1899 // use the C RTL for the dates in the standard range
1900 time_t timet
= GetTicks();
1901 if ( timet
!= (time_t)-1 )
1903 tm
*tm
= localtime(&timet
);
1905 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1907 return tm
->tm_isdst
;
1911 int year
= GetYear();
1913 if ( !IsDSTApplicable(year
, country
) )
1915 // no DST time in this year in this country
1919 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1923 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
1925 long secDiff
= GetTimeZone() + tz
.GetOffset();
1927 // we need to know whether DST is or not in effect for this date unless
1928 // the test disabled by the caller
1929 if ( !noDST
&& (IsDST() == 1) )
1931 // FIXME we assume that the DST is always shifted by 1 hour
1935 return Subtract(wxTimeSpan::Seconds(secDiff
));
1938 // ----------------------------------------------------------------------------
1939 // wxDateTime to/from text representations
1940 // ----------------------------------------------------------------------------
1942 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1944 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1946 // we have to use our own implementation if the date is out of range of
1947 // strftime() or if we use non standard specificators
1948 time_t time
= GetTicks();
1949 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
1953 if ( tz
.GetOffset() == -GetTimeZone() )
1955 // we are working with local time
1956 tm
= localtime(&time
);
1958 // should never happen
1959 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1963 time
+= (int)tz
.GetOffset();
1965 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1966 int time2
= (int) time
;
1974 // should never happen
1975 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1979 tm
= (struct tm
*)NULL
;
1985 return CallStrftime(format
, tm
);
1987 //else: use generic code below
1990 // we only parse ANSI C format specifications here, no POSIX 2
1991 // complications, no GNU extensions but we do add support for a "%l" format
1992 // specifier allowing to get the number of milliseconds
1995 // used for calls to strftime() when we only deal with time
1996 struct tm tmTimeOnly
;
1997 tmTimeOnly
.tm_hour
= tm
.hour
;
1998 tmTimeOnly
.tm_min
= tm
.min
;
1999 tmTimeOnly
.tm_sec
= tm
.sec
;
2000 tmTimeOnly
.tm_wday
= 0;
2001 tmTimeOnly
.tm_yday
= 0;
2002 tmTimeOnly
.tm_mday
= 1; // any date will do
2003 tmTimeOnly
.tm_mon
= 0;
2004 tmTimeOnly
.tm_year
= 76;
2005 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
2007 wxString tmp
, res
, fmt
;
2008 for ( const wxChar
*p
= format
; *p
; p
++ )
2010 if ( *p
!= _T('%') )
2018 // set the default format
2021 case _T('Y'): // year has 4 digits
2025 case _T('j'): // day of year has 3 digits
2026 case _T('l'): // milliseconds have 3 digits
2030 case _T('w'): // week day as number has only one
2035 // it's either another valid format specifier in which case
2036 // the format is "%02d" (for all the rest) or we have the
2037 // field width preceding the format in which case it will
2038 // override the default format anyhow
2042 bool restart
= TRUE
;
2047 // start of the format specification
2050 case _T('a'): // a weekday name
2052 // second parameter should be TRUE for abbreviated names
2053 res
+= GetWeekDayName(tm
.GetWeekDay(),
2054 *p
== _T('a') ? Name_Abbr
: Name_Full
);
2057 case _T('b'): // a month name
2059 res
+= GetMonthName(tm
.mon
,
2060 *p
== _T('b') ? Name_Abbr
: Name_Full
);
2063 case _T('c'): // locale default date and time representation
2064 case _T('x'): // locale default date representation
2066 // the problem: there is no way to know what do these format
2067 // specifications correspond to for the current locale.
2069 // the solution: use a hack and still use strftime(): first
2070 // find the YEAR which is a year in the strftime() range (1970
2071 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
2072 // of the real year. Then make a copy of the format and
2073 // replace all occurences of YEAR in it with some unique
2074 // string not appearing anywhere else in it, then use
2075 // strftime() to format the date in year YEAR and then replace
2076 // YEAR back by the real year and the unique replacement
2077 // string back with YEAR. Notice that "all occurences of YEAR"
2078 // means all occurences of 4 digit as well as 2 digit form!
2080 // the bugs: we assume that neither of %c nor %x contains any
2081 // fields which may change between the YEAR and real year. For
2082 // example, the week number (%U, %W) and the day number (%j)
2083 // will change if one of these years is leap and the other one
2086 // find the YEAR: normally, for any year X, Jan 1 or the
2087 // year X + 28 is the same weekday as Jan 1 of X (because
2088 // the weekday advances by 1 for each normal X and by 2
2089 // for each leap X, hence by 5 every 4 years or by 35
2090 // which is 0 mod 7 every 28 years) but this rule breaks
2091 // down if there are years between X and Y which are
2092 // divisible by 4 but not leap (i.e. divisible by 100 but
2093 // not 400), hence the correction.
2095 int yearReal
= GetYear(tz
);
2096 int mod28
= yearReal
% 28;
2098 // be careful to not go too far - we risk to leave the
2103 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
2107 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
2110 int nCentury
= year
/ 100,
2111 nCenturyReal
= yearReal
/ 100;
2113 // need to adjust for the years divisble by 400 which are
2114 // not leap but are counted like leap ones if we just take
2115 // the number of centuries in between for nLostWeekDays
2116 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
2117 (nCentury
/ 4 - nCenturyReal
/ 4);
2119 // we have to gain back the "lost" weekdays: note that the
2120 // effect of this loop is to not do anything to
2121 // nLostWeekDays (which we won't use any more), but to
2122 // (indirectly) set the year correctly
2123 while ( (nLostWeekDays
% 7) != 0 )
2125 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
2128 // at any rate, we couldn't go further than 1988 + 9 + 28!
2129 wxASSERT_MSG( year
< 2030,
2130 _T("logic error in wxDateTime::Format") );
2132 wxString strYear
, strYear2
;
2133 strYear
.Printf(_T("%d"), year
);
2134 strYear2
.Printf(_T("%d"), year
% 100);
2136 // find two strings not occuring in format (this is surely
2137 // not optimal way of doing it... improvements welcome!)
2138 wxString fmt
= format
;
2139 wxString replacement
= (wxChar
)-1;
2140 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2142 replacement
<< (wxChar
)-1;
2145 wxString replacement2
= (wxChar
)-2;
2146 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2148 replacement
<< (wxChar
)-2;
2151 // replace all occurences of year with it
2152 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
2154 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
2156 // use strftime() to format the same date but in supported
2159 // NB: we assume that strftime() doesn't check for the
2160 // date validity and will happily format the date
2161 // corresponding to Feb 29 of a non leap year (which
2162 // may happen if yearReal was leap and year is not)
2163 struct tm tmAdjusted
;
2165 tmAdjusted
.tm_hour
= tm
.hour
;
2166 tmAdjusted
.tm_min
= tm
.min
;
2167 tmAdjusted
.tm_sec
= tm
.sec
;
2168 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
2169 tmAdjusted
.tm_yday
= GetDayOfYear();
2170 tmAdjusted
.tm_mday
= tm
.mday
;
2171 tmAdjusted
.tm_mon
= tm
.mon
;
2172 tmAdjusted
.tm_year
= year
- 1900;
2173 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
2174 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
2178 // now replace the occurence of 1999 with the real year
2179 wxString strYearReal
, strYearReal2
;
2180 strYearReal
.Printf(_T("%04d"), yearReal
);
2181 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
2182 str
.Replace(strYear
, strYearReal
);
2183 str
.Replace(strYear2
, strYearReal2
);
2185 // and replace back all occurences of replacement string
2188 str
.Replace(replacement2
, strYear2
);
2189 str
.Replace(replacement
, strYear
);
2196 case _T('d'): // day of a month (01-31)
2197 res
+= wxString::Format(fmt
, tm
.mday
);
2200 case _T('H'): // hour in 24h format (00-23)
2201 res
+= wxString::Format(fmt
, tm
.hour
);
2204 case _T('I'): // hour in 12h format (01-12)
2206 // 24h -> 12h, 0h -> 12h too
2207 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
2208 : tm
.hour
? tm
.hour
: 12;
2209 res
+= wxString::Format(fmt
, hour12
);
2213 case _T('j'): // day of the year
2214 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
2217 case _T('l'): // milliseconds (NOT STANDARD)
2218 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
2221 case _T('m'): // month as a number (01-12)
2222 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
2225 case _T('M'): // minute as a decimal number (00-59)
2226 res
+= wxString::Format(fmt
, tm
.min
);
2229 case _T('p'): // AM or PM string
2230 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
2233 case _T('S'): // second as a decimal number (00-61)
2234 res
+= wxString::Format(fmt
, tm
.sec
);
2237 case _T('U'): // week number in the year (Sunday 1st week day)
2238 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
2241 case _T('W'): // week number in the year (Monday 1st week day)
2242 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
2245 case _T('w'): // weekday as a number (0-6), Sunday = 0
2246 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
2249 // case _T('x'): -- handled with "%c"
2251 case _T('X'): // locale default time representation
2252 // just use strftime() to format the time for us
2253 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
2256 case _T('y'): // year without century (00-99)
2257 res
+= wxString::Format(fmt
, tm
.year
% 100);
2260 case _T('Y'): // year with century
2261 res
+= wxString::Format(fmt
, tm
.year
);
2264 case _T('Z'): // timezone name
2265 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
2269 // is it the format width?
2271 while ( *p
== _T('-') || *p
== _T('+') ||
2272 *p
== _T(' ') || wxIsdigit(*p
) )
2277 if ( !fmt
.IsEmpty() )
2279 // we've only got the flags and width so far in fmt
2280 fmt
.Prepend(_T('%'));
2281 fmt
.Append(_T('d'));
2288 // no, it wasn't the width
2289 wxFAIL_MSG(_T("unknown format specificator"));
2291 // fall through and just copy it nevertheless
2293 case _T('%'): // a percent sign
2297 case 0: // the end of string
2298 wxFAIL_MSG(_T("missing format at the end of string"));
2300 // just put the '%' which was the last char in format
2310 // this function parses a string in (strict) RFC 822 format: see the section 5
2311 // of the RFC for the detailed description, but briefly it's something of the
2312 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2314 // this function is "strict" by design - it must reject anything except true
2315 // RFC822 time specs.
2317 // TODO a great candidate for using reg exps
2318 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
2320 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2322 const wxChar
*p
= date
;
2323 const wxChar
*comma
= wxStrchr(p
, _T(','));
2326 // the part before comma is the weekday
2328 // skip it for now - we don't use but might check that it really
2329 // corresponds to the specfied date
2332 if ( *p
!= _T(' ') )
2334 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2336 return (wxChar
*)NULL
;
2342 // the following 1 or 2 digits are the day number
2343 if ( !wxIsdigit(*p
) )
2345 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2347 return (wxChar
*)NULL
;
2350 wxDateTime_t day
= *p
++ - _T('0');
2351 if ( wxIsdigit(*p
) )
2354 day
+= *p
++ - _T('0');
2357 if ( *p
++ != _T(' ') )
2359 return (wxChar
*)NULL
;
2362 // the following 3 letters specify the month
2363 wxString
monName(p
, 3);
2365 if ( monName
== _T("Jan") )
2367 else if ( monName
== _T("Feb") )
2369 else if ( monName
== _T("Mar") )
2371 else if ( monName
== _T("Apr") )
2373 else if ( monName
== _T("May") )
2375 else if ( monName
== _T("Jun") )
2377 else if ( monName
== _T("Jul") )
2379 else if ( monName
== _T("Aug") )
2381 else if ( monName
== _T("Sep") )
2383 else if ( monName
== _T("Oct") )
2385 else if ( monName
== _T("Nov") )
2387 else if ( monName
== _T("Dec") )
2391 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
2393 return (wxChar
*)NULL
;
2398 if ( *p
++ != _T(' ') )
2400 return (wxChar
*)NULL
;
2404 if ( !wxIsdigit(*p
) )
2407 return (wxChar
*)NULL
;
2410 int year
= *p
++ - _T('0');
2412 if ( !wxIsdigit(*p
) )
2414 // should have at least 2 digits in the year
2415 return (wxChar
*)NULL
;
2419 year
+= *p
++ - _T('0');
2421 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2422 if ( wxIsdigit(*p
) )
2425 year
+= *p
++ - _T('0');
2427 if ( !wxIsdigit(*p
) )
2429 // no 3 digit years please
2430 return (wxChar
*)NULL
;
2434 year
+= *p
++ - _T('0');
2437 if ( *p
++ != _T(' ') )
2439 return (wxChar
*)NULL
;
2442 // time is in the format hh:mm:ss and seconds are optional
2443 if ( !wxIsdigit(*p
) )
2445 return (wxChar
*)NULL
;
2448 wxDateTime_t hour
= *p
++ - _T('0');
2450 if ( !wxIsdigit(*p
) )
2452 return (wxChar
*)NULL
;
2456 hour
+= *p
++ - _T('0');
2458 if ( *p
++ != _T(':') )
2460 return (wxChar
*)NULL
;
2463 if ( !wxIsdigit(*p
) )
2465 return (wxChar
*)NULL
;
2468 wxDateTime_t min
= *p
++ - _T('0');
2470 if ( !wxIsdigit(*p
) )
2472 return (wxChar
*)NULL
;
2476 min
+= *p
++ - _T('0');
2478 wxDateTime_t sec
= 0;
2479 if ( *p
++ == _T(':') )
2481 if ( !wxIsdigit(*p
) )
2483 return (wxChar
*)NULL
;
2486 sec
= *p
++ - _T('0');
2488 if ( !wxIsdigit(*p
) )
2490 return (wxChar
*)NULL
;
2494 sec
+= *p
++ - _T('0');
2497 if ( *p
++ != _T(' ') )
2499 return (wxChar
*)NULL
;
2502 // and now the interesting part: the timezone
2504 if ( *p
== _T('-') || *p
== _T('+') )
2506 // the explicit offset given: it has the form of hhmm
2507 bool plus
= *p
++ == _T('+');
2509 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2511 return (wxChar
*)NULL
;
2515 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
2519 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2521 return (wxChar
*)NULL
;
2525 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
2536 // the symbolic timezone given: may be either military timezone or one
2537 // of standard abbreviations
2540 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2541 static const int offsets
[26] =
2543 //A B C D E F G H I J K L M
2544 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2545 //N O P R Q S T U V W Z Y Z
2546 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2549 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
2551 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
2553 return (wxChar
*)NULL
;
2556 offset
= offsets
[*p
++ - _T('A')];
2562 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
2564 else if ( tz
== _T("AST") )
2565 offset
= AST
- GMT0
;
2566 else if ( tz
== _T("ADT") )
2567 offset
= ADT
- GMT0
;
2568 else if ( tz
== _T("EST") )
2569 offset
= EST
- GMT0
;
2570 else if ( tz
== _T("EDT") )
2571 offset
= EDT
- GMT0
;
2572 else if ( tz
== _T("CST") )
2573 offset
= CST
- GMT0
;
2574 else if ( tz
== _T("CDT") )
2575 offset
= CDT
- GMT0
;
2576 else if ( tz
== _T("MST") )
2577 offset
= MST
- GMT0
;
2578 else if ( tz
== _T("MDT") )
2579 offset
= MDT
- GMT0
;
2580 else if ( tz
== _T("PST") )
2581 offset
= PST
- GMT0
;
2582 else if ( tz
== _T("PDT") )
2583 offset
= PDT
- GMT0
;
2586 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
2588 return (wxChar
*)NULL
;
2598 // the spec was correct
2599 Set(day
, mon
, year
, hour
, min
, sec
);
2600 MakeTimezone((wxDateTime_t
)(60*offset
));
2605 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
,
2606 const wxChar
*format
,
2607 const wxDateTime
& dateDef
)
2609 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
2610 _T("NULL pointer in wxDateTime::ParseFormat()") );
2615 // what fields have we found?
2616 bool haveWDay
= FALSE
,
2625 bool hourIsIn12hFormat
= FALSE
, // or in 24h one?
2626 isPM
= FALSE
; // AM by default
2628 // and the value of the items we have (init them to get rid of warnings)
2629 wxDateTime_t sec
= 0,
2632 WeekDay wday
= Inv_WeekDay
;
2633 wxDateTime_t yday
= 0,
2635 wxDateTime::Month mon
= Inv_Month
;
2638 const wxChar
*input
= date
;
2639 for ( const wxChar
*fmt
= format
; *fmt
; fmt
++ )
2641 if ( *fmt
!= _T('%') )
2643 if ( wxIsspace(*fmt
) )
2645 // a white space in the format string matches 0 or more white
2646 // spaces in the input
2647 while ( wxIsspace(*input
) )
2654 // any other character (not whitespace, not '%') must be
2655 // matched by itself in the input
2656 if ( *input
++ != *fmt
)
2659 return (wxChar
*)NULL
;
2663 // done with this format char
2667 // start of a format specification
2669 // parse the optional width
2671 while ( wxIsdigit(*++fmt
) )
2674 width
+= *fmt
- _T('0');
2677 // the default widths for the various fields
2682 case _T('Y'): // year has 4 digits
2686 case _T('j'): // day of year has 3 digits
2687 case _T('l'): // milliseconds have 3 digits
2691 case _T('w'): // week day as number has only one
2696 // default for all other fields
2701 // then the format itself
2704 case _T('a'): // a weekday name
2707 int flag
= *fmt
== _T('a') ? Name_Abbr
: Name_Full
;
2708 wday
= GetWeekDayFromName(GetAlphaToken(input
), flag
);
2709 if ( wday
== Inv_WeekDay
)
2712 return (wxChar
*)NULL
;
2718 case _T('b'): // a month name
2721 int flag
= *fmt
== _T('b') ? Name_Abbr
: Name_Full
;
2722 mon
= GetMonthFromName(GetAlphaToken(input
), flag
);
2723 if ( mon
== Inv_Month
)
2726 return (wxChar
*)NULL
;
2732 case _T('c'): // locale default date and time representation
2736 // this is the format which corresponds to ctime() output
2737 // and strptime("%c") should parse it, so try it first
2738 static const wxChar
*fmtCtime
= _T("%a %b %d %H:%M:%S %Y");
2740 const wxChar
*result
= dt
.ParseFormat(input
, fmtCtime
);
2743 result
= dt
.ParseFormat(input
, _T("%x %X"));
2748 result
= dt
.ParseFormat(input
, _T("%X %x"));
2753 // we've tried everything and still no match
2754 return (wxChar
*)NULL
;
2759 haveDay
= haveMon
= haveYear
=
2760 haveHour
= haveMin
= haveSec
= TRUE
;
2774 case _T('d'): // day of a month (01-31)
2775 if ( !GetNumericToken(width
, input
, &num
) ||
2776 (num
> 31) || (num
< 1) )
2779 return (wxChar
*)NULL
;
2782 // we can't check whether the day range is correct yet, will
2783 // do it later - assume ok for now
2785 mday
= (wxDateTime_t
)num
;
2788 case _T('H'): // hour in 24h format (00-23)
2789 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
2792 return (wxChar
*)NULL
;
2796 hour
= (wxDateTime_t
)num
;
2799 case _T('I'): // hour in 12h format (01-12)
2800 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2803 return (wxChar
*)NULL
;
2807 hourIsIn12hFormat
= TRUE
;
2808 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
2811 case _T('j'): // day of the year
2812 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
2815 return (wxChar
*)NULL
;
2819 yday
= (wxDateTime_t
)num
;
2822 case _T('m'): // month as a number (01-12)
2823 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2826 return (wxChar
*)NULL
;
2830 mon
= (Month
)(num
- 1);
2833 case _T('M'): // minute as a decimal number (00-59)
2834 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
2837 return (wxChar
*)NULL
;
2841 min
= (wxDateTime_t
)num
;
2844 case _T('p'): // AM or PM string
2846 wxString am
, pm
, token
= GetAlphaToken(input
);
2848 GetAmPmStrings(&am
, &pm
);
2849 if ( token
.CmpNoCase(pm
) == 0 )
2853 else if ( token
.CmpNoCase(am
) != 0 )
2856 return (wxChar
*)NULL
;
2861 case _T('r'): // time as %I:%M:%S %p
2864 input
= dt
.ParseFormat(input
, _T("%I:%M:%S %p"));
2868 return (wxChar
*)NULL
;
2871 haveHour
= haveMin
= haveSec
= TRUE
;
2880 case _T('R'): // time as %H:%M
2883 input
= dt
.ParseFormat(input
, _T("%H:%M"));
2887 return (wxChar
*)NULL
;
2890 haveHour
= haveMin
= TRUE
;
2897 case _T('S'): // second as a decimal number (00-61)
2898 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
2901 return (wxChar
*)NULL
;
2905 sec
= (wxDateTime_t
)num
;
2908 case _T('T'): // time as %H:%M:%S
2911 input
= dt
.ParseFormat(input
, _T("%H:%M:%S"));
2915 return (wxChar
*)NULL
;
2918 haveHour
= haveMin
= haveSec
= TRUE
;
2927 case _T('w'): // weekday as a number (0-6), Sunday = 0
2928 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
2931 return (wxChar
*)NULL
;
2935 wday
= (WeekDay
)num
;
2938 case _T('x'): // locale default date representation
2939 #ifdef HAVE_STRPTIME
2940 // try using strptime() -- it may fail even if the input is
2941 // correct but the date is out of range, so we will fall back
2942 // to our generic code anyhow
2946 const wxChar
*result
= CallStrptime(input
, "%x", &tm
);
2951 haveDay
= haveMon
= haveYear
= TRUE
;
2953 year
= 1900 + tm
.tm_year
;
2954 mon
= (Month
)tm
.tm_mon
;
2960 #endif // HAVE_STRPTIME
2962 // TODO query the LOCALE_IDATE setting under Win32
2966 wxString fmtDate
, fmtDateAlt
;
2967 if ( IsWestEuropeanCountry(GetCountry()) ||
2968 GetCountry() == Russia
)
2970 fmtDate
= _T("%d/%m/%y");
2971 fmtDateAlt
= _T("%m/%d/%y");
2975 fmtDate
= _T("%m/%d/%y");
2976 fmtDateAlt
= _T("%d/%m/%y");
2979 const wxChar
*result
= dt
.ParseFormat(input
, fmtDate
);
2983 // ok, be nice and try another one
2984 result
= dt
.ParseFormat(input
, fmtDateAlt
);
2990 return (wxChar
*)NULL
;
2995 haveDay
= haveMon
= haveYear
= TRUE
;
3006 case _T('X'): // locale default time representation
3007 #ifdef HAVE_STRPTIME
3009 // use strptime() to do it for us (FIXME !Unicode friendly)
3011 input
= CallStrptime(input
, "%X", &tm
);
3014 return (wxChar
*)NULL
;
3017 haveHour
= haveMin
= haveSec
= TRUE
;
3023 #else // !HAVE_STRPTIME
3024 // TODO under Win32 we can query the LOCALE_ITIME system
3025 // setting which says whether the default time format is
3028 // try to parse what follows as "%H:%M:%S" and, if this
3029 // fails, as "%I:%M:%S %p" - this should catch the most
3033 const wxChar
*result
= dt
.ParseFormat(input
, _T("%T"));
3036 result
= dt
.ParseFormat(input
, _T("%r"));
3042 return (wxChar
*)NULL
;
3045 haveHour
= haveMin
= haveSec
= TRUE
;
3054 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3057 case _T('y'): // year without century (00-99)
3058 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
3061 return (wxChar
*)NULL
;
3066 // TODO should have an option for roll over date instead of
3067 // hard coding it here
3068 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
3071 case _T('Y'): // year with century
3072 if ( !GetNumericToken(width
, input
, &num
) )
3075 return (wxChar
*)NULL
;
3079 year
= (wxDateTime_t
)num
;
3082 case _T('Z'): // timezone name
3083 wxFAIL_MSG(_T("TODO"));
3086 case _T('%'): // a percent sign
3087 if ( *input
++ != _T('%') )
3090 return (wxChar
*)NULL
;
3094 case 0: // the end of string
3095 wxFAIL_MSG(_T("unexpected format end"));
3099 default: // not a known format spec
3100 return (wxChar
*)NULL
;
3104 // format matched, try to construct a date from what we have now
3106 if ( dateDef
.IsValid() )
3108 // take this date as default
3109 tmDef
= dateDef
.GetTm();
3111 else if ( IsValid() )
3113 // if this date is valid, don't change it
3118 // no default and this date is invalid - fall back to Today()
3119 tmDef
= Today().GetTm();
3130 // TODO we don't check here that the values are consistent, if both year
3131 // day and month/day were found, we just ignore the year day and we
3132 // also always ignore the week day
3133 if ( haveMon
&& haveDay
)
3135 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
3137 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3139 return (wxChar
*)NULL
;
3145 else if ( haveYDay
)
3147 if ( yday
> GetNumberOfDays(tm
.year
) )
3149 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3151 return (wxChar
*)NULL
;
3154 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
3161 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
3163 // translate to 24hour format
3166 //else: either already in 24h format or no translation needed
3189 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3191 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3193 // there is a public domain version of getdate.y, but it only works for
3195 wxFAIL_MSG(_T("TODO"));
3197 return (wxChar
*)NULL
;
3200 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3202 // this is a simplified version of ParseDateTime() which understands only
3203 // "today" (for wxDate compatibility) and digits only otherwise (and not
3204 // all esoteric constructions ParseDateTime() knows about)
3206 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3208 const wxChar
*p
= date
;
3209 while ( wxIsspace(*p
) )
3212 // some special cases
3216 int dayDiffFromToday
;
3219 { wxTRANSLATE("today"), 0 },
3220 { wxTRANSLATE("yesterday"), -1 },
3221 { wxTRANSLATE("tomorrow"), 1 },
3224 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3226 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3227 size_t len
= date
.length();
3228 if ( wxStrlen(p
) >= len
&& (wxString(p
, len
).CmpNoCase(date
) == 0) )
3230 // nothing can follow this, so stop here
3233 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3235 if ( dayDiffFromToday
)
3237 *this += wxDateSpan::Days(dayDiffFromToday
);
3244 // We try to guess what we have here: for each new (numeric) token, we
3245 // determine if it can be a month, day or a year. Of course, there is an
3246 // ambiguity as some numbers may be days as well as months, so we also
3247 // have the ability to back track.
3250 bool haveDay
= FALSE
, // the months day?
3251 haveWDay
= FALSE
, // the day of week?
3252 haveMon
= FALSE
, // the month?
3253 haveYear
= FALSE
; // the year?
3255 // and the value of the items we have (init them to get rid of warnings)
3256 WeekDay wday
= Inv_WeekDay
;
3257 wxDateTime_t day
= 0;
3258 wxDateTime::Month mon
= Inv_Month
;
3261 // tokenize the string
3263 static const wxChar
*dateDelimiters
= _T(".,/-\t\r\n ");
3264 wxStringTokenizer
tok(p
, dateDelimiters
);
3265 while ( tok
.HasMoreTokens() )
3267 wxString token
= tok
.GetNextToken();
3273 if ( token
.ToULong(&val
) )
3275 // guess what this number is
3281 if ( !haveMon
&& val
> 0 && val
<= 12 )
3283 // assume it is month
3286 else // not the month
3288 wxDateTime_t maxDays
= haveMon
3289 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3293 if ( (val
== 0) || (val
> (unsigned long)maxDays
) ) // cast to shut up compiler warning in BCC
3310 year
= (wxDateTime_t
)val
;
3319 day
= (wxDateTime_t
)val
;
3325 mon
= (Month
)(val
- 1);
3328 else // not a number
3330 // be careful not to overwrite the current mon value
3331 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3332 if ( mon2
!= Inv_Month
)
3337 // but we already have a month - maybe we guessed wrong?
3340 // no need to check in month range as always < 12, but
3341 // the days are counted from 1 unlike the months
3342 day
= (wxDateTime_t
)mon
+ 1;
3347 // could possible be the year (doesn't the year come
3348 // before the month in the japanese format?) (FIXME)
3357 else // not a valid month name
3359 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3360 if ( wday
!= Inv_WeekDay
)
3370 else // not a valid weekday name
3373 static const wxChar
*ordinals
[] =
3375 wxTRANSLATE("first"),
3376 wxTRANSLATE("second"),
3377 wxTRANSLATE("third"),
3378 wxTRANSLATE("fourth"),
3379 wxTRANSLATE("fifth"),
3380 wxTRANSLATE("sixth"),
3381 wxTRANSLATE("seventh"),
3382 wxTRANSLATE("eighth"),
3383 wxTRANSLATE("ninth"),
3384 wxTRANSLATE("tenth"),
3385 wxTRANSLATE("eleventh"),
3386 wxTRANSLATE("twelfth"),
3387 wxTRANSLATE("thirteenth"),
3388 wxTRANSLATE("fourteenth"),
3389 wxTRANSLATE("fifteenth"),
3390 wxTRANSLATE("sixteenth"),
3391 wxTRANSLATE("seventeenth"),
3392 wxTRANSLATE("eighteenth"),
3393 wxTRANSLATE("nineteenth"),
3394 wxTRANSLATE("twentieth"),
3395 // that's enough - otherwise we'd have problems with
3396 // composite (or not) ordinals
3400 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3402 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3408 if ( n
== WXSIZEOF(ordinals
) )
3410 // stop here - something unknown
3417 // don't try anything here (as in case of numeric day
3418 // above) - the symbolic day spec should always
3419 // precede the month/year
3425 day
= (wxDateTime_t
)(n
+ 1);
3430 nPosCur
= tok
.GetPosition();
3433 // either no more tokens or the scan was stopped by something we couldn't
3434 // parse - in any case, see if we can construct a date from what we have
3435 if ( !haveDay
&& !haveWDay
)
3437 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3439 return (wxChar
*)NULL
;
3442 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3443 !(haveDay
&& haveMon
&& haveYear
) )
3445 // without adjectives (which we don't support here) the week day only
3446 // makes sense completely separately or with the full date
3447 // specification (what would "Wed 1999" mean?)
3448 return (wxChar
*)NULL
;
3451 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3453 // may be we have month and day instead of day and year?
3454 if ( haveDay
&& !haveMon
)
3458 // exchange day and month
3459 mon
= (wxDateTime::Month
)(day
- 1);
3461 // we're in the current year then
3463 (unsigned)year
<= GetNumOfDaysInMonth(Inv_Year
, mon
) )
3470 //else: no, can't exchange, leave haveMon == FALSE
3476 // if we give the year, month and day must be given too
3477 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3479 return (wxChar
*)NULL
;
3485 mon
= GetCurrentMonth();
3490 year
= GetCurrentYear();
3495 Set(day
, mon
, year
);
3499 // check that it is really the same
3500 if ( GetWeekDay() != wday
)
3502 // inconsistency detected
3503 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3505 return (wxChar
*)NULL
;
3513 SetToWeekDayInSameWeek(wday
);
3516 // return the pointer to the first unparsed char
3518 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3520 // if we couldn't parse the token after the delimiter, put back the
3521 // delimiter as well
3528 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3530 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3532 // first try some extra things
3539 { wxTRANSLATE("noon"), 12 },
3540 { wxTRANSLATE("midnight"), 00 },
3544 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3546 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3547 size_t len
= timeString
.length();
3548 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3550 // casts required by DigitalMars
3551 Set(stdTimes
[n
].hour
, wxDateTime_t(0), wxDateTime_t(0));
3557 // try all time formats we may think about in the order from longest to
3560 // 12hour with AM/PM?
3561 const wxChar
*result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3565 // normally, it's the same, but why not try it?
3566 result
= ParseFormat(time
, _T("%H:%M:%S"));
3571 // 12hour with AM/PM but without seconds?
3572 result
= ParseFormat(time
, _T("%I:%M %p"));
3578 result
= ParseFormat(time
, _T("%H:%M"));
3583 // just the hour and AM/PM?
3584 result
= ParseFormat(time
, _T("%I %p"));
3590 result
= ParseFormat(time
, _T("%H"));
3595 // parse the standard format: normally it is one of the formats above
3596 // but it may be set to something completely different by the user
3597 result
= ParseFormat(time
, _T("%X"));
3600 // TODO: parse timezones
3605 // ----------------------------------------------------------------------------
3606 // Workdays and holidays support
3607 // ----------------------------------------------------------------------------
3609 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3611 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3614 // ============================================================================
3616 // ============================================================================
3618 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3619 // it locally to the method as it provokes an internal compiler error in egcs
3620 // 2.91.60 when building with -O2
3631 // not all strftime(3) format specifiers make sense here because, for example,
3632 // a time span doesn't have a year nor a timezone
3634 // Here are the ones which are supported (all of them are supported by strftime
3636 // %H hour in 24 hour format
3637 // %M minute (00 - 59)
3638 // %S second (00 - 59)
3641 // Also, for MFC CTimeSpan compatibility, we support
3642 // %D number of days
3644 // And, to be better than MFC :-), we also have
3645 // %E number of wEeks
3646 // %l milliseconds (000 - 999)
3647 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3649 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
3652 str
.Alloc(wxStrlen(format
));
3654 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3656 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3657 // question is what should ts.Format("%S") do? The code here returns "3273"
3658 // in this case (i.e. the total number of seconds, not just seconds % 60)
3659 // because, for me, this call means "give me entire time interval in
3660 // seconds" and not "give me the seconds part of the time interval"
3662 // If we agree that it should behave like this, it is clear that the
3663 // interpretation of each format specifier depends on the presence of the
3664 // other format specs in the string: if there was "%H" before "%M", we
3665 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3667 // we remember the most important unit found so far
3668 TimeSpanPart partBiggest
= Part_MSec
;
3670 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3674 if ( ch
== _T('%') )
3676 // the start of the format specification of the printf() below
3677 wxString fmtPrefix
= _T('%');
3682 ch
= *++pch
; // get the format spec char
3686 wxFAIL_MSG( _T("invalid format character") );
3692 // skip the part below switch
3697 if ( partBiggest
< Part_Day
)
3703 partBiggest
= Part_Day
;
3708 partBiggest
= Part_Week
;
3714 if ( partBiggest
< Part_Hour
)
3720 partBiggest
= Part_Hour
;
3723 fmtPrefix
+= _T("02");
3727 n
= GetMilliseconds().ToLong();
3728 if ( partBiggest
< Part_MSec
)
3732 //else: no need to reset partBiggest to Part_MSec, it is
3733 // the least significant one anyhow
3735 fmtPrefix
+= _T("03");
3740 if ( partBiggest
< Part_Min
)
3746 partBiggest
= Part_Min
;
3749 fmtPrefix
+= _T("02");
3753 n
= GetSeconds().ToLong();
3754 if ( partBiggest
< Part_Sec
)
3760 partBiggest
= Part_Sec
;
3763 fmtPrefix
+= _T("02");
3767 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
3771 // normal character, just copy
3779 // ============================================================================
3780 // wxDateTimeHolidayAuthority and related classes
3781 // ============================================================================
3783 #include "wx/arrimpl.cpp"
3785 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
3787 static int wxCMPFUNC_CONV
3788 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
3790 wxDateTime dt1
= **first
,
3793 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
3796 // ----------------------------------------------------------------------------
3797 // wxDateTimeHolidayAuthority
3798 // ----------------------------------------------------------------------------
3800 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
3803 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
3805 size_t count
= ms_authorities
.size();
3806 for ( size_t n
= 0; n
< count
; n
++ )
3808 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
3819 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
3820 const wxDateTime
& dtEnd
,
3821 wxDateTimeArray
& holidays
)
3823 wxDateTimeArray hol
;
3827 size_t count
= ms_authorities
.size();
3828 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
3830 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
3832 WX_APPEND_ARRAY(holidays
, hol
);
3835 holidays
.Sort(wxDateTimeCompareFunc
);
3837 return holidays
.size();
3841 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3843 WX_CLEAR_ARRAY(ms_authorities
);
3847 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
3849 ms_authorities
.push_back(auth
);
3852 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
3854 // nothing to do here
3857 // ----------------------------------------------------------------------------
3858 // wxDateTimeWorkDays
3859 // ----------------------------------------------------------------------------
3861 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
3863 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
3865 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
3868 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
3869 const wxDateTime
& dtEnd
,
3870 wxDateTimeArray
& holidays
) const
3872 if ( dtStart
> dtEnd
)
3874 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3881 // instead of checking all days, start with the first Sat after dtStart and
3882 // end with the last Sun before dtEnd
3883 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
3884 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
3885 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
3886 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
3889 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
3894 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
3899 return holidays
.GetCount();
3902 #endif // wxUSE_DATETIME