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 license
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"
67 #include "wx/string.h"
72 #include "wx/thread.h"
73 #include "wx/tokenzr.h"
74 #include "wx/module.h"
76 #define wxDEFINE_TIME_CONSTANTS // before including datetime.h
80 #include "wx/datetime.h"
81 #include "wx/timer.h" // for wxGetLocalTimeMillis()
83 // ----------------------------------------------------------------------------
84 // conditional compilation
85 // ----------------------------------------------------------------------------
87 #if defined(HAVE_STRPTIME) && defined(__LINUX__)
88 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
89 // crash (instead of just failing):
91 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
92 // strptime(buf, "%x", &tm);
96 #endif // broken strptime()
99 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
100 #define WX_TIMEZONE _timezone
101 #elif defined(__MWERKS__)
102 long wxmw_timezone
= 28800;
103 #define WX_TIMEZONE wxmw_timezone;
104 #else // unknown platform - try timezone
105 #define WX_TIMEZONE timezone
107 #endif // !WX_TIMEZONE
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // debugging helper: just a convenient replacement of wxCHECK()
114 #define wxDATETIME_CHECK(expr, msg) \
118 *this = wxInvalidDateTime; \
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 class wxDateTimeHolidaysModule
: public wxModule
129 virtual bool OnInit()
131 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
136 virtual void OnExit()
138 wxDateTimeHolidayAuthority::ClearAllAuthorities();
139 wxDateTimeHolidayAuthority::ms_authorities
.Clear();
143 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
146 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
148 // ----------------------------------------------------------------------------
150 // ----------------------------------------------------------------------------
153 static const int MONTHS_IN_YEAR
= 12;
155 static const int SEC_PER_MIN
= 60;
157 static const int MIN_PER_HOUR
= 60;
159 static const int HOURS_PER_DAY
= 24;
161 static const long SECONDS_PER_DAY
= 86400l;
163 static const int DAYS_PER_WEEK
= 7;
165 static const long MILLISECONDS_PER_DAY
= 86400000l;
167 // this is the integral part of JDN of the midnight of Jan 1, 1970
168 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
169 static const long EPOCH_JDN
= 2440587l;
171 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
172 // reference date for us) is Nov 24, 4714BC
173 static const int JDN_0_YEAR
= -4713;
174 static const int JDN_0_MONTH
= wxDateTime::Nov
;
175 static const int JDN_0_DAY
= 24;
177 // the constants used for JDN calculations
178 static const long JDN_OFFSET
= 32046l;
179 static const long DAYS_PER_5_MONTHS
= 153l;
180 static const long DAYS_PER_4_YEARS
= 1461l;
181 static const long DAYS_PER_400_YEARS
= 146097l;
183 // this array contains the cumulated number of days in all previous months for
184 // normal and leap years
185 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
187 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
188 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
191 // ----------------------------------------------------------------------------
193 // ----------------------------------------------------------------------------
195 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
196 // indicate an invalid wxDateTime object
198 static const wxDateTime gs_dtDefault
;
200 static const wxDateTime gs_dtDefault
= wxLongLong((long)ULONG_MAX
, ULONG_MAX
);
203 const wxDateTime
& wxDefaultDateTime
= gs_dtDefault
;
205 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 // a critical section is needed to protect GetTimeZone() static
212 // variable in MT case
214 static wxCriticalSection gs_critsectTimezone
;
215 #endif // wxUSE_THREADS
217 // ----------------------------------------------------------------------------
219 // ----------------------------------------------------------------------------
221 // debugger helper: shows what the date really is
223 extern const wxChar
*wxDumpDate(const wxDateTime
* dt
)
225 static wxChar buf
[128];
227 wxStrcpy(buf
, dt
->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
233 // get the number of days in the given month of the given year
235 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
237 // the number of days in month in Julian/Gregorian calendar: the first line
238 // is for normal years, the second one is for the leap ones
239 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
241 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
242 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
245 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
248 // ensure that the timezone variable is set by calling localtime
249 static int GetTimeZone()
251 // set to TRUE when the timezone is set
252 static bool s_timezoneSet
= FALSE
;
254 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
256 if ( !s_timezoneSet
)
258 // just call localtime() instead of figuring out whether this system
259 // supports tzset(), _tzset() or something else
263 s_timezoneSet
= TRUE
;
266 return (int)WX_TIMEZONE
;
269 // return the integral part of the JDN for the midnight of the given date (to
270 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
271 // noon of the previous day)
272 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
273 wxDateTime::Month mon
,
276 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
278 // check the date validity
280 (year
> JDN_0_YEAR
) ||
281 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
282 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
283 _T("date out of range - can't convert to JDN")
286 // make the year positive to avoid problems with negative numbers division
289 // months are counted from March here
291 if ( mon
>= wxDateTime::Mar
)
301 // now we can simply add all the contributions together
302 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
303 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
304 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
309 // this function is a wrapper around strftime(3)
310 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
313 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
315 // buffer is too small?
316 wxFAIL_MSG(_T("strftime() failed"));
319 return wxString(buf
);
322 // if year and/or month have invalid values, replace them with the current ones
323 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
324 wxDateTime::Month
*month
)
326 struct tm
*tmNow
= NULL
;
328 if ( *year
== wxDateTime::Inv_Year
)
330 tmNow
= wxDateTime::GetTmNow();
332 *year
= 1900 + tmNow
->tm_year
;
335 if ( *month
== wxDateTime::Inv_Month
)
338 tmNow
= wxDateTime::GetTmNow();
340 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
344 // fll the struct tm with default values
345 static void InitTm(struct tm
& tm
)
347 // struct tm may have etxra fields (undocumented and with unportable
348 // names) which, nevertheless, must be set to 0
349 memset(&tm
, 0, sizeof(struct tm
));
351 tm
.tm_mday
= 1; // mday 0 is invalid
352 tm
.tm_year
= 76; // any valid year
353 tm
.tm_isdst
= -1; // auto determine
359 // return the month if the string is a month name or Inv_Month otherwise
360 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
362 wxDateTime::Month mon
;
363 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
365 // case-insensitive comparison either one of or with both abbreviated
367 if ( flags
& wxDateTime::Name_Full
)
369 if ( name
.CmpNoCase(wxDateTime::
370 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
376 if ( flags
& wxDateTime::Name_Abbr
)
378 if ( name
.CmpNoCase(wxDateTime::
379 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
389 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
390 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
392 wxDateTime::WeekDay wd
;
393 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
395 // case-insensitive comparison either one of or with both abbreviated
397 if ( flags
& wxDateTime::Name_Full
)
399 if ( name
.CmpNoCase(wxDateTime::
400 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
406 if ( flags
& wxDateTime::Name_Abbr
)
408 if ( name
.CmpNoCase(wxDateTime::
409 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
419 // scans all digits (but no more than len) and returns the resulting number
420 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
424 while ( wxIsdigit(*p
) )
428 if ( len
&& ++n
> len
)
432 return !!s
&& s
.ToULong(number
);
435 // scans all alphabetic characters and returns the resulting string
436 static wxString
GetAlphaToken(const wxChar
*& p
)
439 while ( wxIsalpha(*p
) )
447 // ============================================================================
448 // implementation of wxDateTime
449 // ============================================================================
451 // ----------------------------------------------------------------------------
453 // ----------------------------------------------------------------------------
457 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
458 mon
= wxDateTime::Inv_Month
;
460 hour
= min
= sec
= msec
= 0;
461 wday
= wxDateTime::Inv_WeekDay
;
464 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
472 mon
= (wxDateTime::Month
)tm
.tm_mon
;
473 year
= 1900 + tm
.tm_year
;
478 bool wxDateTime::Tm::IsValid() const
480 // we allow for the leap seconds, although we don't use them (yet)
481 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
482 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
483 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
486 void wxDateTime::Tm::ComputeWeekDay()
488 // compute the week day from day/month/year: we use the dumbest algorithm
489 // possible: just compute our JDN and then use the (simple to derive)
490 // formula: weekday = (JDN + 1.5) % 7
491 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
494 void wxDateTime::Tm::AddMonths(int monDiff
)
496 // normalize the months field
497 while ( monDiff
< -mon
)
501 monDiff
+= MONTHS_IN_YEAR
;
504 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
508 monDiff
-= MONTHS_IN_YEAR
;
511 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
513 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
515 // NB: we don't check here that the resulting date is valid, this function
516 // is private and the caller must check it if needed
519 void wxDateTime::Tm::AddDays(int dayDiff
)
521 // normalize the days field
522 while ( dayDiff
+ mday
< 1 )
526 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
530 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
532 mday
-= GetNumOfDaysInMonth(year
, mon
);
537 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
541 // ----------------------------------------------------------------------------
543 // ----------------------------------------------------------------------------
545 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
549 case wxDateTime::Local
:
550 // get the offset from C RTL: it returns the difference GMT-local
551 // while we want to have the offset _from_ GMT, hence the '-'
552 m_offset
= -GetTimeZone();
555 case wxDateTime::GMT_12
:
556 case wxDateTime::GMT_11
:
557 case wxDateTime::GMT_10
:
558 case wxDateTime::GMT_9
:
559 case wxDateTime::GMT_8
:
560 case wxDateTime::GMT_7
:
561 case wxDateTime::GMT_6
:
562 case wxDateTime::GMT_5
:
563 case wxDateTime::GMT_4
:
564 case wxDateTime::GMT_3
:
565 case wxDateTime::GMT_2
:
566 case wxDateTime::GMT_1
:
567 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
570 case wxDateTime::GMT0
:
571 case wxDateTime::GMT1
:
572 case wxDateTime::GMT2
:
573 case wxDateTime::GMT3
:
574 case wxDateTime::GMT4
:
575 case wxDateTime::GMT5
:
576 case wxDateTime::GMT6
:
577 case wxDateTime::GMT7
:
578 case wxDateTime::GMT8
:
579 case wxDateTime::GMT9
:
580 case wxDateTime::GMT10
:
581 case wxDateTime::GMT11
:
582 case wxDateTime::GMT12
:
583 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
586 case wxDateTime::A_CST
:
587 // Central Standard Time in use in Australia = UTC + 9.5
588 m_offset
= 60l*(9*60 + 30);
592 wxFAIL_MSG( _T("unknown time zone") );
596 // ----------------------------------------------------------------------------
598 // ----------------------------------------------------------------------------
601 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
603 if ( year
== Inv_Year
)
604 year
= GetCurrentYear();
606 if ( cal
== Gregorian
)
608 // in Gregorian calendar leap years are those divisible by 4 except
609 // those divisible by 100 unless they're also divisible by 400
610 // (in some countries, like Russia and Greece, additional corrections
611 // exist, but they won't manifest themselves until 2700)
612 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
614 else if ( cal
== Julian
)
616 // in Julian calendar the rule is simpler
617 return year
% 4 == 0;
621 wxFAIL_MSG(_T("unknown calendar"));
628 int wxDateTime::GetCentury(int year
)
630 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
634 int wxDateTime::ConvertYearToBC(int year
)
637 return year
> 0 ? year
: year
- 1;
641 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
646 return Now().GetYear();
649 wxFAIL_MSG(_T("TODO"));
653 wxFAIL_MSG(_T("unsupported calendar"));
661 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
666 return Now().GetMonth();
669 wxFAIL_MSG(_T("TODO"));
673 wxFAIL_MSG(_T("unsupported calendar"));
681 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
683 if ( year
== Inv_Year
)
685 // take the current year if none given
686 year
= GetCurrentYear();
693 return IsLeapYear(year
) ? 366 : 365;
696 wxFAIL_MSG(_T("unsupported calendar"));
704 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
706 wxDateTime::Calendar cal
)
708 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
710 if ( cal
== Gregorian
|| cal
== Julian
)
712 if ( year
== Inv_Year
)
714 // take the current year if none given
715 year
= GetCurrentYear();
718 return GetNumOfDaysInMonth(year
, month
);
722 wxFAIL_MSG(_T("unsupported calendar"));
729 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
730 wxDateTime::NameFlags flags
)
732 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
734 // notice that we must set all the fields to avoid confusing libc (GNU one
735 // gets confused to a crash if we don't do this)
740 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
744 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
745 wxDateTime::NameFlags flags
)
747 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
749 // take some arbitrary Sunday
756 // and offset it by the number of days needed to get the correct wday
759 // call mktime() to normalize it...
762 // ... and call strftime()
763 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
767 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
773 *am
= CallStrftime(_T("%p"), &tm
);
778 *pm
= CallStrftime(_T("%p"), &tm
);
782 // ----------------------------------------------------------------------------
783 // Country stuff: date calculations depend on the country (DST, work days,
784 // ...), so we need to know which rules to follow.
785 // ----------------------------------------------------------------------------
788 wxDateTime::Country
wxDateTime::GetCountry()
790 // TODO use LOCALE_ICOUNTRY setting under Win32
792 if ( ms_country
== Country_Unknown
)
794 // try to guess from the time zone name
795 time_t t
= time(NULL
);
796 struct tm
*tm
= localtime(&t
);
798 wxString tz
= CallStrftime(_T("%Z"), tm
);
799 if ( tz
== _T("WET") || tz
== _T("WEST") )
803 else if ( tz
== _T("CET") || tz
== _T("CEST") )
805 ms_country
= Country_EEC
;
807 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
811 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
812 tz
== _T("EST") || tz
== _T("EDT") ||
813 tz
== _T("CST") || tz
== _T("CDT") ||
814 tz
== _T("MST") || tz
== _T("MDT") ||
815 tz
== _T("PST") || tz
== _T("PDT") )
821 // well, choose a default one
830 void wxDateTime::SetCountry(wxDateTime::Country country
)
832 ms_country
= country
;
836 bool wxDateTime::IsWestEuropeanCountry(Country country
)
838 if ( country
== Country_Default
)
840 country
= GetCountry();
843 return (Country_WesternEurope_Start
<= country
) &&
844 (country
<= Country_WesternEurope_End
);
847 // ----------------------------------------------------------------------------
848 // DST calculations: we use 3 different rules for the West European countries,
849 // USA and for the rest of the world. This is undoubtedly false for many
850 // countries, but I lack the necessary info (and the time to gather it),
851 // please add the other rules here!
852 // ----------------------------------------------------------------------------
855 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
857 if ( year
== Inv_Year
)
859 // take the current year if none given
860 year
= GetCurrentYear();
863 if ( country
== Country_Default
)
865 country
= GetCountry();
872 // DST was first observed in the US and UK during WWI, reused
873 // during WWII and used again since 1966
874 return year
>= 1966 ||
875 (year
>= 1942 && year
<= 1945) ||
876 (year
== 1918 || year
== 1919);
879 // assume that it started after WWII
885 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
887 if ( year
== Inv_Year
)
889 // take the current year if none given
890 year
= GetCurrentYear();
893 if ( country
== Country_Default
)
895 country
= GetCountry();
898 if ( !IsDSTApplicable(year
, country
) )
900 return wxInvalidDateTime
;
905 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
907 // DST begins at 1 a.m. GMT on the last Sunday of March
908 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
911 wxFAIL_MSG( _T("no last Sunday in March?") );
914 dt
+= wxTimeSpan::Hours(1);
916 // disable DST tests because it could result in an infinite recursion!
919 else switch ( country
)
926 // don't know for sure - assume it was in effect all year
931 dt
.Set(1, Jan
, year
);
935 // DST was installed Feb 2, 1942 by the Congress
936 dt
.Set(2, Feb
, year
);
939 // Oil embargo changed the DST period in the US
941 dt
.Set(6, Jan
, 1974);
945 dt
.Set(23, Feb
, 1975);
949 // before 1986, DST begun on the last Sunday of April, but
950 // in 1986 Reagan changed it to begin at 2 a.m. of the
951 // first Sunday in April
954 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
957 wxFAIL_MSG( _T("no first Sunday in April?") );
962 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
965 wxFAIL_MSG( _T("no first Sunday in April?") );
969 dt
+= wxTimeSpan::Hours(2);
971 // TODO what about timezone??
977 // assume Mar 30 as the start of the DST for the rest of the world
978 // - totally bogus, of course
979 dt
.Set(30, Mar
, year
);
986 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
988 if ( year
== Inv_Year
)
990 // take the current year if none given
991 year
= GetCurrentYear();
994 if ( country
== Country_Default
)
996 country
= GetCountry();
999 if ( !IsDSTApplicable(year
, country
) )
1001 return wxInvalidDateTime
;
1006 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1008 // DST ends at 1 a.m. GMT on the last Sunday of October
1009 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1011 // weirder and weirder...
1012 wxFAIL_MSG( _T("no last Sunday in October?") );
1015 dt
+= wxTimeSpan::Hours(1);
1017 // disable DST tests because it could result in an infinite recursion!
1020 else switch ( country
)
1027 // don't know for sure - assume it was in effect all year
1031 dt
.Set(31, Dec
, year
);
1035 // the time was reset after the end of the WWII
1036 dt
.Set(30, Sep
, year
);
1040 // DST ends at 2 a.m. on the last Sunday of October
1041 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1043 // weirder and weirder...
1044 wxFAIL_MSG( _T("no last Sunday in October?") );
1047 dt
+= wxTimeSpan::Hours(2);
1049 // TODO what about timezone??
1054 // assume October 26th as the end of the DST - totally bogus too
1055 dt
.Set(26, Oct
, year
);
1061 // ----------------------------------------------------------------------------
1062 // constructors and assignment operators
1063 // ----------------------------------------------------------------------------
1065 // return the current time with ms precision
1066 /* static */ wxDateTime
wxDateTime::UNow()
1068 return wxDateTime(wxGetLocalTimeMillis());
1071 // the values in the tm structure contain the local time
1072 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1074 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1077 time_t timet
= mktime(&tm2
);
1079 if ( timet
== (time_t)-1 )
1081 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1082 // less than timezone - try to make it work for this case
1083 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1085 // add timezone to make sure that date is in range
1086 tm2
.tm_sec
-= GetTimeZone();
1088 timet
= mktime(&tm2
);
1089 if ( timet
!= (time_t)-1 )
1091 timet
+= GetTimeZone();
1097 wxFAIL_MSG( _T("mktime() failed") );
1099 *this = wxInvalidDateTime
;
1109 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1110 wxDateTime_t minute
,
1111 wxDateTime_t second
,
1112 wxDateTime_t millisec
)
1114 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1116 // we allow seconds to be 61 to account for the leap seconds, even if we
1117 // don't use them really
1118 wxDATETIME_CHECK( hour
< 24 &&
1122 _T("Invalid time in wxDateTime::Set()") );
1124 // get the current date from system
1125 struct tm
*tm
= GetTmNow();
1127 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1131 tm
->tm_min
= minute
;
1132 tm
->tm_sec
= second
;
1136 // and finally adjust milliseconds
1137 return SetMillisecond(millisec
);
1140 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1144 wxDateTime_t minute
,
1145 wxDateTime_t second
,
1146 wxDateTime_t millisec
)
1148 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1150 wxDATETIME_CHECK( hour
< 24 &&
1154 _T("Invalid time in wxDateTime::Set()") );
1156 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1158 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1159 _T("Invalid date in wxDateTime::Set()") );
1161 // the range of time_t type (inclusive)
1162 static const int yearMinInRange
= 1970;
1163 static const int yearMaxInRange
= 2037;
1165 // test only the year instead of testing for the exact end of the Unix
1166 // time_t range - it doesn't bring anything to do more precise checks
1167 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1169 // use the standard library version if the date is in range - this is
1170 // probably more efficient than our code
1172 tm
.tm_year
= year
- 1900;
1178 tm
.tm_isdst
= -1; // mktime() will guess it
1182 // and finally adjust milliseconds
1183 return SetMillisecond(millisec
);
1187 // do time calculations ourselves: we want to calculate the number of
1188 // milliseconds between the given date and the epoch
1190 // get the JDN for the midnight of this day
1191 m_time
= GetTruncatedJDN(day
, month
, year
);
1192 m_time
-= EPOCH_JDN
;
1193 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1195 // JDN corresponds to GMT, we take localtime
1196 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1202 wxDateTime
& wxDateTime::Set(double jdn
)
1204 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1206 jdn
-= EPOCH_JDN
+ 0.5;
1208 jdn
*= MILLISECONDS_PER_DAY
;
1215 wxDateTime
& wxDateTime::ResetTime()
1219 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1232 // ----------------------------------------------------------------------------
1233 // time_t <-> broken down time conversions
1234 // ----------------------------------------------------------------------------
1236 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1238 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1240 time_t time
= GetTicks();
1241 if ( time
!= (time_t)-1 )
1243 // use C RTL functions
1245 if ( tz
.GetOffset() == -GetTimeZone() )
1247 // we are working with local time
1248 tm
= localtime(&time
);
1250 // should never happen
1251 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1255 time
+= (time_t)tz
.GetOffset();
1256 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1257 int time2
= (int) time
;
1265 // should never happen
1266 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1270 tm
= (struct tm
*)NULL
;
1276 // adjust the milliseconds
1278 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1279 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1282 //else: use generic code below
1285 // remember the time and do the calculations with the date only - this
1286 // eliminates rounding errors of the floating point arithmetics
1288 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1290 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1292 // we want to always have positive time and timeMidnight to be really
1293 // the midnight before it
1296 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1299 timeMidnight
-= timeOnly
;
1301 // calculate the Gregorian date from JDN for the midnight of our date:
1302 // this will yield day, month (in 1..12 range) and year
1304 // actually, this is the JDN for the noon of the previous day
1305 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1307 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1309 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1311 // calculate the century
1312 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1313 long century
= temp
/ DAYS_PER_400_YEARS
;
1315 // then the year and day of year (1 <= dayOfYear <= 366)
1316 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1317 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1318 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1320 // and finally the month and day of the month
1321 temp
= dayOfYear
* 5 - 3;
1322 long month
= temp
/ DAYS_PER_5_MONTHS
;
1323 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1325 // month is counted from March - convert to normal
1336 // year is offset by 4800
1339 // check that the algorithm gave us something reasonable
1340 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1341 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1342 wxASSERT_MSG( (INT_MIN
<= year
) && (year
<= INT_MAX
),
1343 _T("year range overflow") );
1345 // construct Tm from these values
1347 tm
.year
= (int)year
;
1348 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1349 tm
.mday
= (wxDateTime_t
)day
;
1350 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1351 timeOnly
-= tm
.msec
;
1352 timeOnly
/= 1000; // now we have time in seconds
1354 tm
.sec
= (wxDateTime_t
)(timeOnly
% 60);
1356 timeOnly
/= 60; // now we have time in minutes
1358 tm
.min
= (wxDateTime_t
)(timeOnly
% 60);
1361 tm
.hour
= (wxDateTime_t
)(timeOnly
/ 60);
1366 wxDateTime
& wxDateTime::SetYear(int year
)
1368 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1377 wxDateTime
& wxDateTime::SetMonth(Month month
)
1379 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1388 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1390 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1399 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1401 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1410 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1412 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1421 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1423 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1432 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1434 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1436 // we don't need to use GetTm() for this one
1437 m_time
-= m_time
% 1000l;
1438 m_time
+= millisecond
;
1443 // ----------------------------------------------------------------------------
1444 // wxDateTime arithmetics
1445 // ----------------------------------------------------------------------------
1447 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1451 tm
.year
+= diff
.GetYears();
1452 tm
.AddMonths(diff
.GetMonths());
1454 // check that the resulting date is valid
1455 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1457 // We suppose that when adding one month to Jan 31 we want to get Feb
1458 // 28 (or 29), i.e. adding a month to the last day of the month should
1459 // give the last day of the next month which is quite logical.
1461 // Unfortunately, there is no logic way to understand what should
1462 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1463 // We make it Feb 28 (last day too), but it is highly questionable.
1464 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1467 tm
.AddDays(diff
.GetTotalDays());
1471 wxASSERT_MSG( IsSameTime(tm
),
1472 _T("Add(wxDateSpan) shouldn't modify time") );
1477 // ----------------------------------------------------------------------------
1478 // Weekday and monthday stuff
1479 // ----------------------------------------------------------------------------
1481 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
, WeekDay weekday
)
1483 int year
= GetYear();
1485 // Jan 4 always lies in the 1st week of the year
1487 SetToWeekDayInSameWeek(weekday
) += wxDateSpan::Weeks(numWeek
);
1489 if ( GetYear() != year
)
1491 // oops... numWeek was too big
1498 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1501 // take the current month/year if none specified
1502 if ( year
== Inv_Year
)
1504 if ( month
== Inv_Month
)
1507 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1510 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
)
1512 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1514 WeekDay wdayThis
= GetWeekDay();
1515 if ( weekday
== wdayThis
)
1520 else if ( weekday
< wdayThis
)
1522 return Subtract(wxDateSpan::Days(wdayThis
- weekday
));
1524 else // weekday > wdayThis
1526 return Add(wxDateSpan::Days(weekday
- wdayThis
));
1530 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1532 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1535 WeekDay wdayThis
= GetWeekDay();
1536 if ( weekday
== wdayThis
)
1541 else if ( weekday
< wdayThis
)
1543 // need to advance a week
1544 diff
= 7 - (wdayThis
- weekday
);
1546 else // weekday > wdayThis
1548 diff
= weekday
- wdayThis
;
1551 return Add(wxDateSpan::Days(diff
));
1554 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1556 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1559 WeekDay wdayThis
= GetWeekDay();
1560 if ( weekday
== wdayThis
)
1565 else if ( weekday
> wdayThis
)
1567 // need to go to previous week
1568 diff
= 7 - (weekday
- wdayThis
);
1570 else // weekday < wdayThis
1572 diff
= wdayThis
- weekday
;
1575 return Subtract(wxDateSpan::Days(diff
));
1578 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1583 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1585 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1586 // anyhow in such case - but may be should still give an assert for it?
1588 // take the current month/year if none specified
1589 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1593 // TODO this probably could be optimised somehow...
1597 // get the first day of the month
1598 dt
.Set(1, month
, year
);
1601 WeekDay wdayFirst
= dt
.GetWeekDay();
1603 // go to the first weekday of the month
1604 int diff
= weekday
- wdayFirst
;
1608 // add advance n-1 weeks more
1611 dt
+= wxDateSpan::Days(diff
);
1613 else // count from the end of the month
1615 // get the last day of the month
1616 dt
.SetToLastMonthDay(month
, year
);
1619 WeekDay wdayLast
= dt
.GetWeekDay();
1621 // go to the last weekday of the month
1622 int diff
= wdayLast
- weekday
;
1626 // and rewind n-1 weeks from there
1629 dt
-= wxDateSpan::Days(diff
);
1632 // check that it is still in the same month
1633 if ( dt
.GetMonth() == month
)
1641 // no such day in this month
1646 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1650 return gs_cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1653 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
,
1654 const TimeZone
& tz
) const
1656 if ( flags
== Default_First
)
1658 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1661 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1664 WeekDay wd
= GetWeekDay(tz
);
1665 if ( flags
== Sunday_First
)
1667 week
= (nDayInYear
- wd
+ 7) / 7;
1671 // have to shift the week days values
1672 week
= (nDayInYear
- (wd
- 1 + 7) % 7 + 7) / 7;
1675 // FIXME some more elegant way??
1676 WeekDay wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1677 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1685 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1686 const TimeZone
& tz
) const
1689 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
1690 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
1693 // this may happen for January when Jan, 1 is the last week of the
1695 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
1698 return (wxDateTime::wxDateTime_t
)nWeek
;
1701 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
1703 int year
= GetYear();
1704 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
1705 _T("invalid year day") );
1707 bool isLeap
= IsLeapYear(year
);
1708 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
1710 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1711 // don't need it neither - because of the CHECK above we know that
1712 // yday lies in December then
1713 if ( (mon
== Dec
) || (yday
< gs_cumulatedDays
[isLeap
][mon
+ 1]) )
1715 Set(yday
- gs_cumulatedDays
[isLeap
][mon
], mon
, year
);
1724 // ----------------------------------------------------------------------------
1725 // Julian day number conversion and related stuff
1726 // ----------------------------------------------------------------------------
1728 double wxDateTime::GetJulianDayNumber() const
1730 // JDN are always expressed for the GMT dates
1731 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1733 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1735 // add the part GetTruncatedJDN() neglected
1738 // and now add the time: 86400 sec = 1 JDN
1739 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1742 double wxDateTime::GetRataDie() const
1744 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1745 return GetJulianDayNumber() - 1721119.5 - 306;
1748 // ----------------------------------------------------------------------------
1749 // timezone and DST stuff
1750 // ----------------------------------------------------------------------------
1752 int wxDateTime::IsDST(wxDateTime::Country country
) const
1754 wxCHECK_MSG( country
== Country_Default
, -1,
1755 _T("country support not implemented") );
1757 // use the C RTL for the dates in the standard range
1758 time_t timet
= GetTicks();
1759 if ( timet
!= (time_t)-1 )
1761 tm
*tm
= localtime(&timet
);
1763 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1765 return tm
->tm_isdst
;
1769 int year
= GetYear();
1771 if ( !IsDSTApplicable(year
, country
) )
1773 // no DST time in this year in this country
1777 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1781 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
1783 long secDiff
= GetTimeZone() + tz
.GetOffset();
1785 // we need to know whether DST is or not in effect for this date unless
1786 // the test disabled by the caller
1787 if ( !noDST
&& (IsDST() == 1) )
1789 // FIXME we assume that the DST is always shifted by 1 hour
1793 return Subtract(wxTimeSpan::Seconds(secDiff
));
1796 // ----------------------------------------------------------------------------
1797 // wxDateTime to/from text representations
1798 // ----------------------------------------------------------------------------
1800 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1802 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1804 // we have to use our own implementation if the date is out of range of
1805 // strftime() or if we use non standard specificators
1806 time_t time
= GetTicks();
1807 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
1811 if ( tz
.GetOffset() == -GetTimeZone() )
1813 // we are working with local time
1814 tm
= localtime(&time
);
1816 // should never happen
1817 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1821 time
+= (int)tz
.GetOffset();
1823 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1824 int time2
= (int) time
;
1832 // should never happen
1833 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1837 tm
= (struct tm
*)NULL
;
1843 return CallStrftime(format
, tm
);
1845 //else: use generic code below
1848 // we only parse ANSI C format specifications here, no POSIX 2
1849 // complications, no GNU extensions but we do add support for a "%l" format
1850 // specifier allowing to get the number of milliseconds
1853 // used for calls to strftime() when we only deal with time
1854 struct tm tmTimeOnly
;
1855 tmTimeOnly
.tm_hour
= tm
.hour
;
1856 tmTimeOnly
.tm_min
= tm
.min
;
1857 tmTimeOnly
.tm_sec
= tm
.sec
;
1858 tmTimeOnly
.tm_wday
= 0;
1859 tmTimeOnly
.tm_yday
= 0;
1860 tmTimeOnly
.tm_mday
= 1; // any date will do
1861 tmTimeOnly
.tm_mon
= 0;
1862 tmTimeOnly
.tm_year
= 76;
1863 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
1865 wxString tmp
, res
, fmt
;
1866 for ( const wxChar
*p
= format
; *p
; p
++ )
1868 if ( *p
!= _T('%') )
1876 // set the default format
1879 case _T('Y'): // year has 4 digits
1883 case _T('j'): // day of year has 3 digits
1884 case _T('l'): // milliseconds have 3 digits
1889 // it's either another valid format specifier in which case
1890 // the format is "%02d" (for all the rest) or we have the
1891 // field width preceding the format in which case it will
1892 // override the default format anyhow
1896 bool restart
= TRUE
;
1901 // start of the format specification
1904 case _T('a'): // a weekday name
1906 // second parameter should be TRUE for abbreviated names
1907 res
+= GetWeekDayName(tm
.GetWeekDay(),
1908 *p
== _T('a') ? Name_Abbr
: Name_Full
);
1911 case _T('b'): // a month name
1913 res
+= GetMonthName(tm
.mon
,
1914 *p
== _T('b') ? Name_Abbr
: Name_Full
);
1917 case _T('c'): // locale default date and time representation
1918 case _T('x'): // locale default date representation
1920 // the problem: there is no way to know what do these format
1921 // specifications correspond to for the current locale.
1923 // the solution: use a hack and still use strftime(): first
1924 // find the YEAR which is a year in the strftime() range (1970
1925 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
1926 // of the real year. Then make a copy of the format and
1927 // replace all occurences of YEAR in it with some unique
1928 // string not appearing anywhere else in it, then use
1929 // strftime() to format the date in year YEAR and then replace
1930 // YEAR back by the real year and the unique replacement
1931 // string back with YEAR. Notice that "all occurences of YEAR"
1932 // means all occurences of 4 digit as well as 2 digit form!
1934 // the bugs: we assume that neither of %c nor %x contains any
1935 // fields which may change between the YEAR and real year. For
1936 // example, the week number (%U, %W) and the day number (%j)
1937 // will change if one of these years is leap and the other one
1940 // find the YEAR: normally, for any year X, Jan 1 or the
1941 // year X + 28 is the same weekday as Jan 1 of X (because
1942 // the weekday advances by 1 for each normal X and by 2
1943 // for each leap X, hence by 5 every 4 years or by 35
1944 // which is 0 mod 7 every 28 years) but this rule breaks
1945 // down if there are years between X and Y which are
1946 // divisible by 4 but not leap (i.e. divisible by 100 but
1947 // not 400), hence the correction.
1949 int yearReal
= GetYear(tz
);
1950 int mod28
= yearReal
% 28;
1952 // be careful to not go too far - we risk to leave the
1957 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
1961 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
1964 int nCentury
= year
/ 100,
1965 nCenturyReal
= yearReal
/ 100;
1967 // need to adjust for the years divisble by 400 which are
1968 // not leap but are counted like leap ones if we just take
1969 // the number of centuries in between for nLostWeekDays
1970 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
1971 (nCentury
/ 4 - nCenturyReal
/ 4);
1973 // we have to gain back the "lost" weekdays: note that the
1974 // effect of this loop is to not do anything to
1975 // nLostWeekDays (which we won't use any more), but to
1976 // (indirectly) set the year correctly
1977 while ( (nLostWeekDays
% 7) != 0 )
1979 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
1982 // at any rate, we couldn't go further than 1988 + 9 + 28!
1983 wxASSERT_MSG( year
< 2030,
1984 _T("logic error in wxDateTime::Format") );
1986 wxString strYear
, strYear2
;
1987 strYear
.Printf(_T("%d"), year
);
1988 strYear2
.Printf(_T("%d"), year
% 100);
1990 // find two strings not occuring in format (this is surely
1991 // not optimal way of doing it... improvements welcome!)
1992 wxString fmt
= format
;
1993 wxString replacement
= (wxChar
)-1;
1994 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1996 replacement
<< (wxChar
)-1;
1999 wxString replacement2
= (wxChar
)-2;
2000 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2002 replacement
<< (wxChar
)-2;
2005 // replace all occurences of year with it
2006 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
2008 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
2010 // use strftime() to format the same date but in supported
2013 // NB: we assume that strftime() doesn't check for the
2014 // date validity and will happily format the date
2015 // corresponding to Feb 29 of a non leap year (which
2016 // may happen if yearReal was leap and year is not)
2017 struct tm tmAdjusted
;
2019 tmAdjusted
.tm_hour
= tm
.hour
;
2020 tmAdjusted
.tm_min
= tm
.min
;
2021 tmAdjusted
.tm_sec
= tm
.sec
;
2022 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
2023 tmAdjusted
.tm_yday
= GetDayOfYear();
2024 tmAdjusted
.tm_mday
= tm
.mday
;
2025 tmAdjusted
.tm_mon
= tm
.mon
;
2026 tmAdjusted
.tm_year
= year
- 1900;
2027 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
2028 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
2032 // now replace the occurence of 1999 with the real year
2033 wxString strYearReal
, strYearReal2
;
2034 strYearReal
.Printf(_T("%04d"), yearReal
);
2035 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
2036 str
.Replace(strYear
, strYearReal
);
2037 str
.Replace(strYear2
, strYearReal2
);
2039 // and replace back all occurences of replacement string
2042 str
.Replace(replacement2
, strYear2
);
2043 str
.Replace(replacement
, strYear
);
2050 case _T('d'): // day of a month (01-31)
2051 res
+= wxString::Format(fmt
, tm
.mday
);
2054 case _T('H'): // hour in 24h format (00-23)
2055 res
+= wxString::Format(fmt
, tm
.hour
);
2058 case _T('I'): // hour in 12h format (01-12)
2060 // 24h -> 12h, 0h -> 12h too
2061 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
2062 : tm
.hour
? tm
.hour
: 12;
2063 res
+= wxString::Format(fmt
, hour12
);
2067 case _T('j'): // day of the year
2068 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
2071 case _T('l'): // milliseconds (NOT STANDARD)
2072 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
2075 case _T('m'): // month as a number (01-12)
2076 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
2079 case _T('M'): // minute as a decimal number (00-59)
2080 res
+= wxString::Format(fmt
, tm
.min
);
2083 case _T('p'): // AM or PM string
2084 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
2087 case _T('S'): // second as a decimal number (00-61)
2088 res
+= wxString::Format(fmt
, tm
.sec
);
2091 case _T('U'): // week number in the year (Sunday 1st week day)
2092 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
2095 case _T('W'): // week number in the year (Monday 1st week day)
2096 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
2099 case _T('w'): // weekday as a number (0-6), Sunday = 0
2100 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
2103 // case _T('x'): -- handled with "%c"
2105 case _T('X'): // locale default time representation
2106 // just use strftime() to format the time for us
2107 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
2110 case _T('y'): // year without century (00-99)
2111 res
+= wxString::Format(fmt
, tm
.year
% 100);
2114 case _T('Y'): // year with century
2115 res
+= wxString::Format(fmt
, tm
.year
);
2118 case _T('Z'): // timezone name
2119 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
2123 // is it the format width?
2125 while ( *p
== _T('-') || *p
== _T('+') ||
2126 *p
== _T(' ') || wxIsdigit(*p
) )
2131 if ( !fmt
.IsEmpty() )
2133 // we've only got the flags and width so far in fmt
2134 fmt
.Prepend(_T('%'));
2135 fmt
.Append(_T('d'));
2142 // no, it wasn't the width
2143 wxFAIL_MSG(_T("unknown format specificator"));
2145 // fall through and just copy it nevertheless
2147 case _T('%'): // a percent sign
2151 case 0: // the end of string
2152 wxFAIL_MSG(_T("missing format at the end of string"));
2154 // just put the '%' which was the last char in format
2164 // this function parses a string in (strict) RFC 822 format: see the section 5
2165 // of the RFC for the detailed description, but briefly it's something of the
2166 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2168 // this function is "strict" by design - it must reject anything except true
2169 // RFC822 time specs.
2171 // TODO a great candidate for using reg exps
2172 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
2174 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2176 const wxChar
*p
= date
;
2177 const wxChar
*comma
= wxStrchr(p
, _T(','));
2180 // the part before comma is the weekday
2182 // skip it for now - we don't use but might check that it really
2183 // corresponds to the specfied date
2186 if ( *p
!= _T(' ') )
2188 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2190 return (wxChar
*)NULL
;
2196 // the following 1 or 2 digits are the day number
2197 if ( !wxIsdigit(*p
) )
2199 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2201 return (wxChar
*)NULL
;
2204 wxDateTime_t day
= *p
++ - _T('0');
2205 if ( wxIsdigit(*p
) )
2208 day
+= *p
++ - _T('0');
2211 if ( *p
++ != _T(' ') )
2213 return (wxChar
*)NULL
;
2216 // the following 3 letters specify the month
2217 wxString
monName(p
, 3);
2219 if ( monName
== _T("Jan") )
2221 else if ( monName
== _T("Feb") )
2223 else if ( monName
== _T("Mar") )
2225 else if ( monName
== _T("Apr") )
2227 else if ( monName
== _T("May") )
2229 else if ( monName
== _T("Jun") )
2231 else if ( monName
== _T("Jul") )
2233 else if ( monName
== _T("Aug") )
2235 else if ( monName
== _T("Sep") )
2237 else if ( monName
== _T("Oct") )
2239 else if ( monName
== _T("Nov") )
2241 else if ( monName
== _T("Dec") )
2245 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
2247 return (wxChar
*)NULL
;
2252 if ( *p
++ != _T(' ') )
2254 return (wxChar
*)NULL
;
2258 if ( !wxIsdigit(*p
) )
2261 return (wxChar
*)NULL
;
2264 int year
= *p
++ - _T('0');
2266 if ( !wxIsdigit(*p
) )
2268 // should have at least 2 digits in the year
2269 return (wxChar
*)NULL
;
2273 year
+= *p
++ - _T('0');
2275 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2276 if ( wxIsdigit(*p
) )
2279 year
+= *p
++ - _T('0');
2281 if ( !wxIsdigit(*p
) )
2283 // no 3 digit years please
2284 return (wxChar
*)NULL
;
2288 year
+= *p
++ - _T('0');
2291 if ( *p
++ != _T(' ') )
2293 return (wxChar
*)NULL
;
2296 // time is in the format hh:mm:ss and seconds are optional
2297 if ( !wxIsdigit(*p
) )
2299 return (wxChar
*)NULL
;
2302 wxDateTime_t hour
= *p
++ - _T('0');
2304 if ( !wxIsdigit(*p
) )
2306 return (wxChar
*)NULL
;
2310 hour
+= *p
++ - _T('0');
2312 if ( *p
++ != _T(':') )
2314 return (wxChar
*)NULL
;
2317 if ( !wxIsdigit(*p
) )
2319 return (wxChar
*)NULL
;
2322 wxDateTime_t min
= *p
++ - _T('0');
2324 if ( !wxIsdigit(*p
) )
2326 return (wxChar
*)NULL
;
2330 min
+= *p
++ - _T('0');
2332 wxDateTime_t sec
= 0;
2333 if ( *p
++ == _T(':') )
2335 if ( !wxIsdigit(*p
) )
2337 return (wxChar
*)NULL
;
2340 sec
= *p
++ - _T('0');
2342 if ( !wxIsdigit(*p
) )
2344 return (wxChar
*)NULL
;
2348 sec
+= *p
++ - _T('0');
2351 if ( *p
++ != _T(' ') )
2353 return (wxChar
*)NULL
;
2356 // and now the interesting part: the timezone
2358 if ( *p
== _T('-') || *p
== _T('+') )
2360 // the explicit offset given: it has the form of hhmm
2361 bool plus
= *p
++ == _T('+');
2363 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2365 return (wxChar
*)NULL
;
2369 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
2373 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2375 return (wxChar
*)NULL
;
2379 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
2390 // the symbolic timezone given: may be either military timezone or one
2391 // of standard abbreviations
2394 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2395 static const int offsets
[26] =
2397 //A B C D E F G H I J K L M
2398 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2399 //N O P R Q S T U V W Z Y Z
2400 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2403 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
2405 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
2407 return (wxChar
*)NULL
;
2410 offset
= offsets
[*p
++ - _T('A')];
2416 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
2418 else if ( tz
== _T("AST") )
2419 offset
= AST
- GMT0
;
2420 else if ( tz
== _T("ADT") )
2421 offset
= ADT
- GMT0
;
2422 else if ( tz
== _T("EST") )
2423 offset
= EST
- GMT0
;
2424 else if ( tz
== _T("EDT") )
2425 offset
= EDT
- GMT0
;
2426 else if ( tz
== _T("CST") )
2427 offset
= CST
- GMT0
;
2428 else if ( tz
== _T("CDT") )
2429 offset
= CDT
- GMT0
;
2430 else if ( tz
== _T("MST") )
2431 offset
= MST
- GMT0
;
2432 else if ( tz
== _T("MDT") )
2433 offset
= MDT
- GMT0
;
2434 else if ( tz
== _T("PST") )
2435 offset
= PST
- GMT0
;
2436 else if ( tz
== _T("PDT") )
2437 offset
= PDT
- GMT0
;
2440 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
2442 return (wxChar
*)NULL
;
2452 // the spec was correct
2453 Set(day
, mon
, year
, hour
, min
, sec
);
2454 MakeTimezone((wxDateTime_t
)(60*offset
));
2459 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
,
2460 const wxChar
*format
,
2461 const wxDateTime
& dateDef
)
2463 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
2464 _T("NULL pointer in wxDateTime::ParseFormat()") );
2469 // what fields have we found?
2470 bool haveWDay
= FALSE
,
2479 bool hourIsIn12hFormat
= FALSE
, // or in 24h one?
2480 isPM
= FALSE
; // AM by default
2482 // and the value of the items we have (init them to get rid of warnings)
2483 wxDateTime_t sec
= 0,
2486 WeekDay wday
= Inv_WeekDay
;
2487 wxDateTime_t yday
= 0,
2489 wxDateTime::Month mon
= Inv_Month
;
2492 const wxChar
*input
= date
;
2493 for ( const wxChar
*fmt
= format
; *fmt
; fmt
++ )
2495 if ( *fmt
!= _T('%') )
2497 if ( wxIsspace(*fmt
) )
2499 // a white space in the format string matches 0 or more white
2500 // spaces in the input
2501 while ( wxIsspace(*input
) )
2508 // any other character (not whitespace, not '%') must be
2509 // matched by itself in the input
2510 if ( *input
++ != *fmt
)
2513 return (wxChar
*)NULL
;
2517 // done with this format char
2521 // start of a format specification
2523 // parse the optional width
2525 while ( isdigit(*++fmt
) )
2528 width
+= *fmt
- _T('0');
2531 // then the format itself
2534 case _T('a'): // a weekday name
2537 int flag
= *fmt
== _T('a') ? Name_Abbr
: Name_Full
;
2538 wday
= GetWeekDayFromName(GetAlphaToken(input
), flag
);
2539 if ( wday
== Inv_WeekDay
)
2542 return (wxChar
*)NULL
;
2548 case _T('b'): // a month name
2551 int flag
= *fmt
== _T('b') ? Name_Abbr
: Name_Full
;
2552 mon
= GetMonthFromName(GetAlphaToken(input
), flag
);
2553 if ( mon
== Inv_Month
)
2556 return (wxChar
*)NULL
;
2562 case _T('c'): // locale default date and time representation
2566 // this is the format which corresponds to ctime() output
2567 // and strptime("%c") should parse it, so try it first
2568 static const wxChar
*fmtCtime
= _T("%a %b %d %H:%M:%S %Y");
2570 const wxChar
*result
= dt
.ParseFormat(input
, fmtCtime
);
2573 result
= dt
.ParseFormat(input
, _T("%x %X"));
2578 result
= dt
.ParseFormat(input
, _T("%X %x"));
2583 // we've tried everything and still no match
2584 return (wxChar
*)NULL
;
2589 haveDay
= haveMon
= haveYear
=
2590 haveHour
= haveMin
= haveSec
= TRUE
;
2604 case _T('d'): // day of a month (01-31)
2605 if ( !GetNumericToken(width
, input
, &num
) ||
2606 (num
> 31) || (num
< 1) )
2609 return (wxChar
*)NULL
;
2612 // we can't check whether the day range is correct yet, will
2613 // do it later - assume ok for now
2615 mday
= (wxDateTime_t
)num
;
2618 case _T('H'): // hour in 24h format (00-23)
2619 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
2622 return (wxChar
*)NULL
;
2626 hour
= (wxDateTime_t
)num
;
2629 case _T('I'): // hour in 12h format (01-12)
2630 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2633 return (wxChar
*)NULL
;
2637 hourIsIn12hFormat
= TRUE
;
2638 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
2641 case _T('j'): // day of the year
2642 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
2645 return (wxChar
*)NULL
;
2649 yday
= (wxDateTime_t
)num
;
2652 case _T('m'): // month as a number (01-12)
2653 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2656 return (wxChar
*)NULL
;
2660 mon
= (Month
)(num
- 1);
2663 case _T('M'): // minute as a decimal number (00-59)
2664 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
2667 return (wxChar
*)NULL
;
2671 min
= (wxDateTime_t
)num
;
2674 case _T('p'): // AM or PM string
2676 wxString am
, pm
, token
= GetAlphaToken(input
);
2678 GetAmPmStrings(&am
, &pm
);
2679 if ( token
.CmpNoCase(pm
) == 0 )
2683 else if ( token
.CmpNoCase(am
) != 0 )
2686 return (wxChar
*)NULL
;
2691 case _T('r'): // time as %I:%M:%S %p
2694 input
= dt
.ParseFormat(input
, _T("%I:%M:%S %p"));
2698 return (wxChar
*)NULL
;
2701 haveHour
= haveMin
= haveSec
= TRUE
;
2710 case _T('R'): // time as %H:%M
2713 input
= dt
.ParseFormat(input
, _T("%H:%M"));
2717 return (wxChar
*)NULL
;
2720 haveHour
= haveMin
= TRUE
;
2727 case _T('S'): // second as a decimal number (00-61)
2728 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
2731 return (wxChar
*)NULL
;
2735 sec
= (wxDateTime_t
)num
;
2738 case _T('T'): // time as %H:%M:%S
2741 input
= dt
.ParseFormat(input
, _T("%H:%M:%S"));
2745 return (wxChar
*)NULL
;
2748 haveHour
= haveMin
= haveSec
= TRUE
;
2757 case _T('w'): // weekday as a number (0-6), Sunday = 0
2758 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
2761 return (wxChar
*)NULL
;
2765 wday
= (WeekDay
)num
;
2768 case _T('x'): // locale default date representation
2769 #ifdef HAVE_STRPTIME
2770 // try using strptime() - it may fail even if the input is
2771 // correct but the date is out of range, so we will fall back
2772 // to our generic code anyhow (FIXME !Unicode friendly)
2775 const wxChar
*result
= strptime(input
, "%x", &tm
);
2780 haveDay
= haveMon
= haveYear
= TRUE
;
2782 year
= 1900 + tm
.tm_year
;
2783 mon
= (Month
)tm
.tm_mon
;
2789 #endif // HAVE_STRPTIME
2791 // TODO query the LOCALE_IDATE setting under Win32
2795 wxString fmtDate
, fmtDateAlt
;
2796 if ( IsWestEuropeanCountry(GetCountry()) ||
2797 GetCountry() == Russia
)
2799 fmtDate
= _T("%d/%m/%y");
2800 fmtDateAlt
= _T("%m/%d/%y");
2804 fmtDate
= _T("%m/%d/%y");
2805 fmtDateAlt
= _T("%d/%m/%y");
2808 const wxChar
*result
= dt
.ParseFormat(input
, fmtDate
);
2812 // ok, be nice and try another one
2813 result
= dt
.ParseFormat(input
, fmtDateAlt
);
2819 return (wxChar
*)NULL
;
2824 haveDay
= haveMon
= haveYear
= TRUE
;
2835 case _T('X'): // locale default time representation
2836 #ifdef HAVE_STRPTIME
2838 // use strptime() to do it for us (FIXME !Unicode friendly)
2840 input
= strptime(input
, "%X", &tm
);
2843 return (wxChar
*)NULL
;
2846 haveHour
= haveMin
= haveSec
= TRUE
;
2852 #else // !HAVE_STRPTIME
2853 // TODO under Win32 we can query the LOCALE_ITIME system
2854 // setting which says whether the default time format is
2857 // try to parse what follows as "%H:%M:%S" and, if this
2858 // fails, as "%I:%M:%S %p" - this should catch the most
2862 const wxChar
*result
= dt
.ParseFormat(input
, _T("%T"));
2865 result
= dt
.ParseFormat(input
, _T("%r"));
2871 return (wxChar
*)NULL
;
2874 haveHour
= haveMin
= haveSec
= TRUE
;
2883 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
2886 case _T('y'): // year without century (00-99)
2887 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
2890 return (wxChar
*)NULL
;
2895 // TODO should have an option for roll over date instead of
2896 // hard coding it here
2897 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
2900 case _T('Y'): // year with century
2901 if ( !GetNumericToken(width
, input
, &num
) )
2904 return (wxChar
*)NULL
;
2908 year
= (wxDateTime_t
)num
;
2911 case _T('Z'): // timezone name
2912 wxFAIL_MSG(_T("TODO"));
2915 case _T('%'): // a percent sign
2916 if ( *input
++ != _T('%') )
2919 return (wxChar
*)NULL
;
2923 case 0: // the end of string
2924 wxFAIL_MSG(_T("unexpected format end"));
2928 default: // not a known format spec
2929 return (wxChar
*)NULL
;
2933 // format matched, try to construct a date from what we have now
2935 if ( dateDef
.IsValid() )
2937 // take this date as default
2938 tmDef
= dateDef
.GetTm();
2941 else if ( m_time
!= 0 )
2943 else if ( m_time
!= wxLongLong(0) )
2946 // if this date is valid, don't change it
2951 // no default and this date is invalid - fall back to Today()
2952 tmDef
= Today().GetTm();
2963 // TODO we don't check here that the values are consistent, if both year
2964 // day and month/day were found, we just ignore the year day and we
2965 // also always ignore the week day
2966 if ( haveMon
&& haveDay
)
2968 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
2970 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
2972 return (wxChar
*)NULL
;
2978 else if ( haveYDay
)
2980 if ( yday
> GetNumberOfDays(tm
.year
) )
2982 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
2984 return (wxChar
*)NULL
;
2987 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
2994 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
2996 // translate to 24hour format
2999 //else: either already in 24h format or no translation needed
3022 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3024 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3026 // there is a public domain version of getdate.y, but it only works for
3028 wxFAIL_MSG(_T("TODO"));
3030 return (wxChar
*)NULL
;
3033 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3035 // this is a simplified version of ParseDateTime() which understands only
3036 // "today" (for wxDate compatibility) and digits only otherwise (and not
3037 // all esoteric constructions ParseDateTime() knows about)
3039 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3041 const wxChar
*p
= date
;
3042 while ( wxIsspace(*p
) )
3045 // some special cases
3049 int dayDiffFromToday
;
3052 { wxTRANSLATE("today"), 0 },
3053 { wxTRANSLATE("yesterday"), -1 },
3054 { wxTRANSLATE("tomorrow"), 1 },
3057 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3059 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3060 size_t len
= date
.length();
3061 if ( wxStrlen(p
) >= len
&& (wxString(p
, len
).CmpNoCase(date
) == 0) )
3063 // nothing can follow this, so stop here
3066 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3068 if ( dayDiffFromToday
)
3070 *this += wxDateSpan::Days(dayDiffFromToday
);
3077 // We try to guess what we have here: for each new (numeric) token, we
3078 // determine if it can be a month, day or a year. Of course, there is an
3079 // ambiguity as some numbers may be days as well as months, so we also
3080 // have the ability to back track.
3083 bool haveDay
= FALSE
, // the months day?
3084 haveWDay
= FALSE
, // the day of week?
3085 haveMon
= FALSE
, // the month?
3086 haveYear
= FALSE
; // the year?
3088 // and the value of the items we have (init them to get rid of warnings)
3089 WeekDay wday
= Inv_WeekDay
;
3090 wxDateTime_t day
= 0;
3091 wxDateTime::Month mon
= Inv_Month
;
3094 // tokenize the string
3096 static const wxChar
*dateDelimiters
= _T(".,/-\t\n ");
3097 wxStringTokenizer
tok(p
, dateDelimiters
);
3098 while ( tok
.HasMoreTokens() )
3100 wxString token
= tok
.GetNextToken();
3106 if ( token
.ToULong(&val
) )
3108 // guess what this number is
3114 if ( !haveMon
&& val
> 0 && val
<= 12 )
3116 // assume it is month
3119 else // not the month
3121 wxDateTime_t maxDays
= haveMon
3122 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3126 if ( (val
== 0) || (val
> (unsigned long)maxDays
) ) // cast to shut up compiler warning in BCC
3143 year
= (wxDateTime_t
)val
;
3152 day
= (wxDateTime_t
)val
;
3158 mon
= (Month
)(val
- 1);
3161 else // not a number
3163 // be careful not to overwrite the current mon value
3164 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3165 if ( mon2
!= Inv_Month
)
3170 // but we already have a month - maybe we guessed wrong?
3173 // no need to check in month range as always < 12, but
3174 // the days are counted from 1 unlike the months
3175 day
= (wxDateTime_t
)mon
+ 1;
3180 // could possible be the year (doesn't the year come
3181 // before the month in the japanese format?) (FIXME)
3190 else // not a valid month name
3192 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3193 if ( wday
!= Inv_WeekDay
)
3203 else // not a valid weekday name
3206 static const wxChar
*ordinals
[] =
3208 wxTRANSLATE("first"),
3209 wxTRANSLATE("second"),
3210 wxTRANSLATE("third"),
3211 wxTRANSLATE("fourth"),
3212 wxTRANSLATE("fifth"),
3213 wxTRANSLATE("sixth"),
3214 wxTRANSLATE("seventh"),
3215 wxTRANSLATE("eighth"),
3216 wxTRANSLATE("ninth"),
3217 wxTRANSLATE("tenth"),
3218 wxTRANSLATE("eleventh"),
3219 wxTRANSLATE("twelfth"),
3220 wxTRANSLATE("thirteenth"),
3221 wxTRANSLATE("fourteenth"),
3222 wxTRANSLATE("fifteenth"),
3223 wxTRANSLATE("sixteenth"),
3224 wxTRANSLATE("seventeenth"),
3225 wxTRANSLATE("eighteenth"),
3226 wxTRANSLATE("nineteenth"),
3227 wxTRANSLATE("twentieth"),
3228 // that's enough - otherwise we'd have problems with
3229 // composite (or not) ordinals
3233 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3235 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3241 if ( n
== WXSIZEOF(ordinals
) )
3243 // stop here - something unknown
3250 // don't try anything here (as in case of numeric day
3251 // above) - the symbolic day spec should always
3252 // precede the month/year
3258 day
= (wxDateTime_t
)(n
+ 1);
3263 nPosCur
= tok
.GetPosition();
3266 // either no more tokens or the scan was stopped by something we couldn't
3267 // parse - in any case, see if we can construct a date from what we have
3268 if ( !haveDay
&& !haveWDay
)
3270 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3272 return (wxChar
*)NULL
;
3275 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3276 !(haveDay
&& haveMon
&& haveYear
) )
3278 // without adjectives (which we don't support here) the week day only
3279 // makes sense completely separately or with the full date
3280 // specification (what would "Wed 1999" mean?)
3281 return (wxChar
*)NULL
;
3284 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3286 // may be we have month and day instead of day and year?
3287 if ( haveDay
&& !haveMon
)
3291 // exchange day and month
3292 mon
= (wxDateTime::Month
)(day
- 1);
3294 // we're in the current year then
3296 (unsigned)year
<= GetNumOfDaysInMonth(Inv_Year
, mon
) )
3303 //else: no, can't exchange, leave haveMon == FALSE
3309 // if we give the year, month and day must be given too
3310 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3312 return (wxChar
*)NULL
;
3318 mon
= GetCurrentMonth();
3323 year
= GetCurrentYear();
3328 Set(day
, mon
, year
);
3332 // check that it is really the same
3333 if ( GetWeekDay() != wday
)
3335 // inconsistency detected
3336 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3338 return (wxChar
*)NULL
;
3346 SetToWeekDayInSameWeek(wday
);
3349 // return the pointer to the first unparsed char
3351 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3353 // if we couldn't parse the token after the delimiter, put back the
3354 // delimiter as well
3361 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3363 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3365 // first try some extra things
3372 { wxTRANSLATE("noon"), 12 },
3373 { wxTRANSLATE("midnight"), 00 },
3377 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3379 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3380 size_t len
= timeString
.length();
3381 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3383 Set(stdTimes
[n
].hour
, 0, 0);
3389 // try all time formats we may think about starting with the standard one
3390 const wxChar
*result
= ParseFormat(time
, _T("%X"));
3393 // normally, it's the same, but why not try it?
3394 result
= ParseFormat(time
, _T("%H:%M:%S"));
3399 // 12hour with AM/PM?
3400 result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3406 result
= ParseFormat(time
, _T("%H:%M"));
3411 // 12hour with AM/PM but without seconds?
3412 result
= ParseFormat(time
, _T("%I:%M %p"));
3418 result
= ParseFormat(time
, _T("%H"));
3423 // just the hour and AM/PM?
3424 result
= ParseFormat(time
, _T("%I %p"));
3427 // TODO: parse timezones
3432 // ----------------------------------------------------------------------------
3433 // Workdays and holidays support
3434 // ----------------------------------------------------------------------------
3436 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3438 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3441 // ============================================================================
3443 // ============================================================================
3445 // not all strftime(3) format specifiers make sense here because, for example,
3446 // a time span doesn't have a year nor a timezone
3448 // Here are the ones which are supported (all of them are supported by strftime
3450 // %H hour in 24 hour format
3451 // %M minute (00 - 59)
3452 // %S second (00 - 59)
3455 // Also, for MFC CTimeSpan compatibility, we support
3456 // %D number of days
3458 // And, to be better than MFC :-), we also have
3459 // %E number of wEeks
3460 // %l milliseconds (000 - 999)
3461 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3463 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
3466 str
.Alloc(wxStrlen(format
));
3468 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3470 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3471 // question is what should ts.Format("%S") do? The code here returns "3273"
3472 // in this case (i.e. the total number of seconds, not just seconds % 60)
3473 // because, for me, this call means "give me entire time interval in
3474 // seconds" and not "give me the seconds part of the time interval"
3476 // If we agree that it should behave like this, it is clear that the
3477 // interpretation of each format specifier depends on the presence of the
3478 // other format specs in the string: if there was "%H" before "%M", we
3479 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3481 // we remember the most important unit found so far
3490 } partBiggest
= Part_MSec
;
3492 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3496 if ( ch
== _T('%') )
3498 // the start of the format specification of the printf() below
3499 wxString fmtPrefix
= _T('%');
3504 ch
= *++pch
; // get the format spec char
3508 wxFAIL_MSG( _T("invalid format character") );
3514 // skip the part below switch
3519 if ( partBiggest
< Part_Day
)
3525 partBiggest
= Part_Day
;
3530 partBiggest
= Part_Week
;
3536 if ( partBiggest
< Part_Hour
)
3542 partBiggest
= Part_Hour
;
3545 fmtPrefix
+= _T("02");
3549 n
= GetMilliseconds().ToLong();
3550 if ( partBiggest
< Part_MSec
)
3554 //else: no need to reset partBiggest to Part_MSec, it is
3555 // the least significant one anyhow
3557 fmtPrefix
+= _T("03");
3562 if ( partBiggest
< Part_Min
)
3568 partBiggest
= Part_Min
;
3571 fmtPrefix
+= _T("02");
3575 n
= GetSeconds().ToLong();
3576 if ( partBiggest
< Part_Sec
)
3582 partBiggest
= Part_Sec
;
3585 fmtPrefix
+= _T("02");
3589 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
3593 // normal character, just copy
3601 // ============================================================================
3602 // wxDateTimeHolidayAuthority and related classes
3603 // ============================================================================
3605 #include "wx/arrimpl.cpp"
3607 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
3609 static int wxCMPFUNC_CONV
3610 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
3612 wxDateTime dt1
= **first
,
3615 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
3618 // ----------------------------------------------------------------------------
3619 // wxDateTimeHolidayAuthority
3620 // ----------------------------------------------------------------------------
3622 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
3625 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
3627 size_t count
= ms_authorities
.GetCount();
3628 for ( size_t n
= 0; n
< count
; n
++ )
3630 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
3641 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
3642 const wxDateTime
& dtEnd
,
3643 wxDateTimeArray
& holidays
)
3645 wxDateTimeArray hol
;
3649 size_t count
= ms_authorities
.GetCount();
3650 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
3652 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
3654 WX_APPEND_ARRAY(holidays
, hol
);
3657 holidays
.Sort(wxDateTimeCompareFunc
);
3659 return holidays
.GetCount();
3663 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3665 WX_CLEAR_ARRAY(ms_authorities
);
3669 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
3671 ms_authorities
.Add(auth
);
3674 // ----------------------------------------------------------------------------
3675 // wxDateTimeWorkDays
3676 // ----------------------------------------------------------------------------
3678 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
3680 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
3682 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
3685 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
3686 const wxDateTime
& dtEnd
,
3687 wxDateTimeArray
& holidays
) const
3689 if ( dtStart
> dtEnd
)
3691 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3698 // instead of checking all days, start with the first Sat after dtStart and
3699 // end with the last Sun before dtEnd
3700 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
3701 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
3702 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
3703 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
3706 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
3711 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
3716 return holidays
.GetCount();