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"
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"
78 #define wxDEFINE_TIME_CONSTANTS // before including datetime.h
82 #include "wx/datetime.h"
83 #include "wx/timer.h" // for wxGetLocalTimeMillis()
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 #if defined(HAVE_STRPTIME) && defined(__LINUX__)
90 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
91 // crash (instead of just failing):
93 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
94 // strptime(buf, "%x", &tm);
98 #endif // broken strptime()
101 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
102 #define WX_TIMEZONE _timezone
103 #elif defined(__MWERKS__)
104 long wxmw_timezone
= 28800;
105 #define WX_TIMEZONE wxmw_timezone;
106 #elif defined(__DJGPP__)
107 #include <sys/timeb.h>
108 static long wxGetTimeZone()
114 #define WX_TIMEZONE wxGetTimeZone()
115 #else // unknown platform - try timezone
116 #define WX_TIMEZONE timezone
118 #endif // !WX_TIMEZONE
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 // debugging helper: just a convenient replacement of wxCHECK()
125 #define wxDATETIME_CHECK(expr, msg) \
129 *this = wxInvalidDateTime; \
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 class wxDateTimeHolidaysModule
: public wxModule
140 virtual bool OnInit()
142 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
147 virtual void OnExit()
149 wxDateTimeHolidayAuthority::ClearAllAuthorities();
150 wxDateTimeHolidayAuthority::ms_authorities
.Clear();
154 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
157 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
164 static const int MONTHS_IN_YEAR
= 12;
166 static const int SEC_PER_MIN
= 60;
168 static const int MIN_PER_HOUR
= 60;
170 static const int HOURS_PER_DAY
= 24;
172 static const long SECONDS_PER_DAY
= 86400l;
174 static const int DAYS_PER_WEEK
= 7;
176 static const long MILLISECONDS_PER_DAY
= 86400000l;
178 // this is the integral part of JDN of the midnight of Jan 1, 1970
179 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
180 static const long EPOCH_JDN
= 2440587l;
182 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
183 // reference date for us) is Nov 24, 4714BC
184 static const int JDN_0_YEAR
= -4713;
185 static const int JDN_0_MONTH
= wxDateTime::Nov
;
186 static const int JDN_0_DAY
= 24;
188 // the constants used for JDN calculations
189 static const long JDN_OFFSET
= 32046l;
190 static const long DAYS_PER_5_MONTHS
= 153l;
191 static const long DAYS_PER_4_YEARS
= 1461l;
192 static const long DAYS_PER_400_YEARS
= 146097l;
194 // this array contains the cumulated number of days in all previous months for
195 // normal and leap years
196 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
198 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
199 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
202 // ----------------------------------------------------------------------------
204 // ----------------------------------------------------------------------------
206 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
207 // indicate an invalid wxDateTime object
209 static const wxDateTime gs_dtDefault
;
211 const wxDateTime
& wxDefaultDateTime
= gs_dtDefault
;
213 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
215 // ----------------------------------------------------------------------------
217 // ----------------------------------------------------------------------------
219 // a critical section is needed to protect GetTimeZone() static
220 // variable in MT case
222 static wxCriticalSection gs_critsectTimezone
;
223 #endif // wxUSE_THREADS
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 // ensure that the timezone variable is set by calling localtime
257 static int GetTimeZone()
259 // set to TRUE when the timezone is set
260 static bool s_timezoneSet
= FALSE
;
262 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
264 if ( !s_timezoneSet
)
266 // just call localtime() instead of figuring out whether this system
267 // supports tzset(), _tzset() or something else
271 s_timezoneSet
= TRUE
;
274 return (int)WX_TIMEZONE
;
277 // return the integral part of the JDN for the midnight of the given date (to
278 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
279 // noon of the previous day)
280 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
281 wxDateTime::Month mon
,
284 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
286 // check the date validity
288 (year
> JDN_0_YEAR
) ||
289 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
290 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
291 _T("date out of range - can't convert to JDN")
294 // make the year positive to avoid problems with negative numbers division
297 // months are counted from March here
299 if ( mon
>= wxDateTime::Mar
)
309 // now we can simply add all the contributions together
310 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
311 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
312 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
317 // this function is a wrapper around strftime(3)
318 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
321 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
323 // buffer is too small?
324 wxFAIL_MSG(_T("strftime() failed"));
327 return wxString(buf
);
330 // if year and/or month have invalid values, replace them with the current ones
331 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
332 wxDateTime::Month
*month
)
334 struct tm
*tmNow
= NULL
;
336 if ( *year
== wxDateTime::Inv_Year
)
338 tmNow
= wxDateTime::GetTmNow();
340 *year
= 1900 + tmNow
->tm_year
;
343 if ( *month
== wxDateTime::Inv_Month
)
346 tmNow
= wxDateTime::GetTmNow();
348 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
352 // fll the struct tm with default values
353 static void InitTm(struct tm
& tm
)
355 // struct tm may have etxra fields (undocumented and with unportable
356 // names) which, nevertheless, must be set to 0
357 memset(&tm
, 0, sizeof(struct tm
));
359 tm
.tm_mday
= 1; // mday 0 is invalid
360 tm
.tm_year
= 76; // any valid year
361 tm
.tm_isdst
= -1; // auto determine
367 // return the month if the string is a month name or Inv_Month otherwise
368 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
370 wxDateTime::Month mon
;
371 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
373 // case-insensitive comparison either one of or with both abbreviated
375 if ( flags
& wxDateTime::Name_Full
)
377 if ( name
.CmpNoCase(wxDateTime::
378 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
384 if ( flags
& wxDateTime::Name_Abbr
)
386 if ( name
.CmpNoCase(wxDateTime::
387 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
397 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
398 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
400 wxDateTime::WeekDay wd
;
401 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
403 // case-insensitive comparison either one of or with both abbreviated
405 if ( flags
& wxDateTime::Name_Full
)
407 if ( name
.CmpNoCase(wxDateTime::
408 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
414 if ( flags
& wxDateTime::Name_Abbr
)
416 if ( name
.CmpNoCase(wxDateTime::
417 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
427 // scans all digits (but no more than len) and returns the resulting number
428 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
432 while ( wxIsdigit(*p
) )
436 if ( len
&& ++n
> len
)
440 return !!s
&& s
.ToULong(number
);
443 // scans all alphabetic characters and returns the resulting string
444 static wxString
GetAlphaToken(const wxChar
*& p
)
447 while ( wxIsalpha(*p
) )
455 // ============================================================================
456 // implementation of wxDateTime
457 // ============================================================================
459 // ----------------------------------------------------------------------------
461 // ----------------------------------------------------------------------------
465 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
466 mon
= wxDateTime::Inv_Month
;
468 hour
= min
= sec
= msec
= 0;
469 wday
= wxDateTime::Inv_WeekDay
;
472 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
480 mon
= (wxDateTime::Month
)tm
.tm_mon
;
481 year
= 1900 + tm
.tm_year
;
486 bool wxDateTime::Tm::IsValid() const
488 // we allow for the leap seconds, although we don't use them (yet)
489 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
490 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
491 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
494 void wxDateTime::Tm::ComputeWeekDay()
496 // compute the week day from day/month/year: we use the dumbest algorithm
497 // possible: just compute our JDN and then use the (simple to derive)
498 // formula: weekday = (JDN + 1.5) % 7
499 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
502 void wxDateTime::Tm::AddMonths(int monDiff
)
504 // normalize the months field
505 while ( monDiff
< -mon
)
509 monDiff
+= MONTHS_IN_YEAR
;
512 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
516 monDiff
-= MONTHS_IN_YEAR
;
519 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
521 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
523 // NB: we don't check here that the resulting date is valid, this function
524 // is private and the caller must check it if needed
527 void wxDateTime::Tm::AddDays(int dayDiff
)
529 // normalize the days field
530 while ( dayDiff
+ mday
< 1 )
534 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
538 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
540 mday
-= GetNumOfDaysInMonth(year
, mon
);
545 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
549 // ----------------------------------------------------------------------------
551 // ----------------------------------------------------------------------------
553 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
557 case wxDateTime::Local
:
558 // get the offset from C RTL: it returns the difference GMT-local
559 // while we want to have the offset _from_ GMT, hence the '-'
560 m_offset
= -GetTimeZone();
563 case wxDateTime::GMT_12
:
564 case wxDateTime::GMT_11
:
565 case wxDateTime::GMT_10
:
566 case wxDateTime::GMT_9
:
567 case wxDateTime::GMT_8
:
568 case wxDateTime::GMT_7
:
569 case wxDateTime::GMT_6
:
570 case wxDateTime::GMT_5
:
571 case wxDateTime::GMT_4
:
572 case wxDateTime::GMT_3
:
573 case wxDateTime::GMT_2
:
574 case wxDateTime::GMT_1
:
575 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
578 case wxDateTime::GMT0
:
579 case wxDateTime::GMT1
:
580 case wxDateTime::GMT2
:
581 case wxDateTime::GMT3
:
582 case wxDateTime::GMT4
:
583 case wxDateTime::GMT5
:
584 case wxDateTime::GMT6
:
585 case wxDateTime::GMT7
:
586 case wxDateTime::GMT8
:
587 case wxDateTime::GMT9
:
588 case wxDateTime::GMT10
:
589 case wxDateTime::GMT11
:
590 case wxDateTime::GMT12
:
591 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
594 case wxDateTime::A_CST
:
595 // Central Standard Time in use in Australia = UTC + 9.5
596 m_offset
= 60l*(9*60 + 30);
600 wxFAIL_MSG( _T("unknown time zone") );
604 // ----------------------------------------------------------------------------
606 // ----------------------------------------------------------------------------
609 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
611 if ( year
== Inv_Year
)
612 year
= GetCurrentYear();
614 if ( cal
== Gregorian
)
616 // in Gregorian calendar leap years are those divisible by 4 except
617 // those divisible by 100 unless they're also divisible by 400
618 // (in some countries, like Russia and Greece, additional corrections
619 // exist, but they won't manifest themselves until 2700)
620 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
622 else if ( cal
== Julian
)
624 // in Julian calendar the rule is simpler
625 return year
% 4 == 0;
629 wxFAIL_MSG(_T("unknown calendar"));
636 int wxDateTime::GetCentury(int year
)
638 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
642 int wxDateTime::ConvertYearToBC(int year
)
645 return year
> 0 ? year
: year
- 1;
649 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
654 return Now().GetYear();
657 wxFAIL_MSG(_T("TODO"));
661 wxFAIL_MSG(_T("unsupported calendar"));
669 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
674 return Now().GetMonth();
677 wxFAIL_MSG(_T("TODO"));
681 wxFAIL_MSG(_T("unsupported calendar"));
689 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
691 if ( year
== Inv_Year
)
693 // take the current year if none given
694 year
= GetCurrentYear();
701 return IsLeapYear(year
) ? 366 : 365;
704 wxFAIL_MSG(_T("unsupported calendar"));
712 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
714 wxDateTime::Calendar cal
)
716 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
718 if ( cal
== Gregorian
|| cal
== Julian
)
720 if ( year
== Inv_Year
)
722 // take the current year if none given
723 year
= GetCurrentYear();
726 return GetNumOfDaysInMonth(year
, month
);
730 wxFAIL_MSG(_T("unsupported calendar"));
737 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
738 wxDateTime::NameFlags flags
)
740 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
742 // notice that we must set all the fields to avoid confusing libc (GNU one
743 // gets confused to a crash if we don't do this)
748 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
752 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
753 wxDateTime::NameFlags flags
)
755 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
757 // take some arbitrary Sunday
764 // and offset it by the number of days needed to get the correct wday
767 // call mktime() to normalize it...
770 // ... and call strftime()
771 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
775 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
781 *am
= CallStrftime(_T("%p"), &tm
);
786 *pm
= CallStrftime(_T("%p"), &tm
);
790 // ----------------------------------------------------------------------------
791 // Country stuff: date calculations depend on the country (DST, work days,
792 // ...), so we need to know which rules to follow.
793 // ----------------------------------------------------------------------------
796 wxDateTime::Country
wxDateTime::GetCountry()
798 // TODO use LOCALE_ICOUNTRY setting under Win32
800 if ( ms_country
== Country_Unknown
)
802 // try to guess from the time zone name
803 time_t t
= time(NULL
);
804 struct tm
*tm
= localtime(&t
);
806 wxString tz
= CallStrftime(_T("%Z"), tm
);
807 if ( tz
== _T("WET") || tz
== _T("WEST") )
811 else if ( tz
== _T("CET") || tz
== _T("CEST") )
813 ms_country
= Country_EEC
;
815 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
819 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
820 tz
== _T("EST") || tz
== _T("EDT") ||
821 tz
== _T("CST") || tz
== _T("CDT") ||
822 tz
== _T("MST") || tz
== _T("MDT") ||
823 tz
== _T("PST") || tz
== _T("PDT") )
829 // well, choose a default one
838 void wxDateTime::SetCountry(wxDateTime::Country country
)
840 ms_country
= country
;
844 bool wxDateTime::IsWestEuropeanCountry(Country country
)
846 if ( country
== Country_Default
)
848 country
= GetCountry();
851 return (Country_WesternEurope_Start
<= country
) &&
852 (country
<= Country_WesternEurope_End
);
855 // ----------------------------------------------------------------------------
856 // DST calculations: we use 3 different rules for the West European countries,
857 // USA and for the rest of the world. This is undoubtedly false for many
858 // countries, but I lack the necessary info (and the time to gather it),
859 // please add the other rules here!
860 // ----------------------------------------------------------------------------
863 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
865 if ( year
== Inv_Year
)
867 // take the current year if none given
868 year
= GetCurrentYear();
871 if ( country
== Country_Default
)
873 country
= GetCountry();
880 // DST was first observed in the US and UK during WWI, reused
881 // during WWII and used again since 1966
882 return year
>= 1966 ||
883 (year
>= 1942 && year
<= 1945) ||
884 (year
== 1918 || year
== 1919);
887 // assume that it started after WWII
893 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
895 if ( year
== Inv_Year
)
897 // take the current year if none given
898 year
= GetCurrentYear();
901 if ( country
== Country_Default
)
903 country
= GetCountry();
906 if ( !IsDSTApplicable(year
, country
) )
908 return wxInvalidDateTime
;
913 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
915 // DST begins at 1 a.m. GMT on the last Sunday of March
916 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
919 wxFAIL_MSG( _T("no last Sunday in March?") );
922 dt
+= wxTimeSpan::Hours(1);
924 // disable DST tests because it could result in an infinite recursion!
927 else switch ( country
)
934 // don't know for sure - assume it was in effect all year
939 dt
.Set(1, Jan
, year
);
943 // DST was installed Feb 2, 1942 by the Congress
944 dt
.Set(2, Feb
, year
);
947 // Oil embargo changed the DST period in the US
949 dt
.Set(6, Jan
, 1974);
953 dt
.Set(23, Feb
, 1975);
957 // before 1986, DST begun on the last Sunday of April, but
958 // in 1986 Reagan changed it to begin at 2 a.m. of the
959 // first Sunday in April
962 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
965 wxFAIL_MSG( _T("no first Sunday in April?") );
970 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
973 wxFAIL_MSG( _T("no first Sunday in April?") );
977 dt
+= wxTimeSpan::Hours(2);
979 // TODO what about timezone??
985 // assume Mar 30 as the start of the DST for the rest of the world
986 // - totally bogus, of course
987 dt
.Set(30, Mar
, year
);
994 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
996 if ( year
== Inv_Year
)
998 // take the current year if none given
999 year
= GetCurrentYear();
1002 if ( country
== Country_Default
)
1004 country
= GetCountry();
1007 if ( !IsDSTApplicable(year
, country
) )
1009 return wxInvalidDateTime
;
1014 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1016 // DST ends at 1 a.m. GMT on the last Sunday of October
1017 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1019 // weirder and weirder...
1020 wxFAIL_MSG( _T("no last Sunday in October?") );
1023 dt
+= wxTimeSpan::Hours(1);
1025 // disable DST tests because it could result in an infinite recursion!
1028 else switch ( country
)
1035 // don't know for sure - assume it was in effect all year
1039 dt
.Set(31, Dec
, year
);
1043 // the time was reset after the end of the WWII
1044 dt
.Set(30, Sep
, year
);
1048 // DST ends at 2 a.m. on the last Sunday of October
1049 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1051 // weirder and weirder...
1052 wxFAIL_MSG( _T("no last Sunday in October?") );
1055 dt
+= wxTimeSpan::Hours(2);
1057 // TODO what about timezone??
1062 // assume October 26th as the end of the DST - totally bogus too
1063 dt
.Set(26, Oct
, year
);
1069 // ----------------------------------------------------------------------------
1070 // constructors and assignment operators
1071 // ----------------------------------------------------------------------------
1073 // return the current time with ms precision
1074 /* static */ wxDateTime
wxDateTime::UNow()
1076 return wxDateTime(wxGetLocalTimeMillis());
1079 // the values in the tm structure contain the local time
1080 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1083 time_t timet
= mktime(&tm2
);
1085 if ( timet
== (time_t)-1 )
1087 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1088 // less than timezone - try to make it work for this case
1089 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1091 // add timezone to make sure that date is in range
1092 tm2
.tm_sec
-= GetTimeZone();
1094 timet
= mktime(&tm2
);
1095 if ( timet
!= (time_t)-1 )
1097 timet
+= GetTimeZone();
1103 wxFAIL_MSG( _T("mktime() failed") );
1105 *this = wxInvalidDateTime
;
1115 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1116 wxDateTime_t minute
,
1117 wxDateTime_t second
,
1118 wxDateTime_t millisec
)
1120 // we allow seconds to be 61 to account for the leap seconds, even if we
1121 // don't use them really
1122 wxDATETIME_CHECK( hour
< 24 &&
1126 _T("Invalid time in wxDateTime::Set()") );
1128 // get the current date from system
1129 struct tm
*tm
= GetTmNow();
1131 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1135 tm
->tm_min
= minute
;
1136 tm
->tm_sec
= second
;
1140 // and finally adjust milliseconds
1141 return SetMillisecond(millisec
);
1144 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1148 wxDateTime_t minute
,
1149 wxDateTime_t second
,
1150 wxDateTime_t millisec
)
1152 wxDATETIME_CHECK( hour
< 24 &&
1156 _T("Invalid time in wxDateTime::Set()") );
1158 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1160 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1161 _T("Invalid date in wxDateTime::Set()") );
1163 // the range of time_t type (inclusive)
1164 static const int yearMinInRange
= 1970;
1165 static const int yearMaxInRange
= 2037;
1167 // test only the year instead of testing for the exact end of the Unix
1168 // time_t range - it doesn't bring anything to do more precise checks
1169 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1171 // use the standard library version if the date is in range - this is
1172 // probably more efficient than our code
1174 tm
.tm_year
= year
- 1900;
1180 tm
.tm_isdst
= -1; // mktime() will guess it
1184 // and finally adjust milliseconds
1185 return SetMillisecond(millisec
);
1189 // do time calculations ourselves: we want to calculate the number of
1190 // milliseconds between the given date and the epoch
1192 // get the JDN for the midnight of this day
1193 m_time
= GetTruncatedJDN(day
, month
, year
);
1194 m_time
-= EPOCH_JDN
;
1195 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1197 // JDN corresponds to GMT, we take localtime
1198 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1204 wxDateTime
& wxDateTime::Set(double jdn
)
1206 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1208 jdn
-= EPOCH_JDN
+ 0.5;
1210 jdn
*= MILLISECONDS_PER_DAY
;
1217 wxDateTime
& wxDateTime::ResetTime()
1221 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1234 // ----------------------------------------------------------------------------
1235 // time_t <-> broken down time conversions
1236 // ----------------------------------------------------------------------------
1238 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1240 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1242 time_t time
= GetTicks();
1243 if ( time
!= (time_t)-1 )
1245 // use C RTL functions
1247 if ( tz
.GetOffset() == -GetTimeZone() )
1249 // we are working with local time
1250 tm
= localtime(&time
);
1252 // should never happen
1253 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1257 time
+= (time_t)tz
.GetOffset();
1258 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1259 int time2
= (int) time
;
1267 // should never happen
1268 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1272 tm
= (struct tm
*)NULL
;
1278 // adjust the milliseconds
1280 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1281 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1284 //else: use generic code below
1287 // remember the time and do the calculations with the date only - this
1288 // eliminates rounding errors of the floating point arithmetics
1290 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1292 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1294 // we want to always have positive time and timeMidnight to be really
1295 // the midnight before it
1298 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1301 timeMidnight
-= timeOnly
;
1303 // calculate the Gregorian date from JDN for the midnight of our date:
1304 // this will yield day, month (in 1..12 range) and year
1306 // actually, this is the JDN for the noon of the previous day
1307 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1309 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1311 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1313 // calculate the century
1314 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1315 long century
= temp
/ DAYS_PER_400_YEARS
;
1317 // then the year and day of year (1 <= dayOfYear <= 366)
1318 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1319 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1320 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1322 // and finally the month and day of the month
1323 temp
= dayOfYear
* 5 - 3;
1324 long month
= temp
/ DAYS_PER_5_MONTHS
;
1325 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1327 // month is counted from March - convert to normal
1338 // year is offset by 4800
1341 // check that the algorithm gave us something reasonable
1342 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1343 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
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();
2940 else if ( IsValid() )
2942 // if this date is valid, don't change it
2947 // no default and this date is invalid - fall back to Today()
2948 tmDef
= Today().GetTm();
2959 // TODO we don't check here that the values are consistent, if both year
2960 // day and month/day were found, we just ignore the year day and we
2961 // also always ignore the week day
2962 if ( haveMon
&& haveDay
)
2964 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
2966 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
2968 return (wxChar
*)NULL
;
2974 else if ( haveYDay
)
2976 if ( yday
> GetNumberOfDays(tm
.year
) )
2978 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
2980 return (wxChar
*)NULL
;
2983 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
2990 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
2992 // translate to 24hour format
2995 //else: either already in 24h format or no translation needed
3018 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3020 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3022 // there is a public domain version of getdate.y, but it only works for
3024 wxFAIL_MSG(_T("TODO"));
3026 return (wxChar
*)NULL
;
3029 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3031 // this is a simplified version of ParseDateTime() which understands only
3032 // "today" (for wxDate compatibility) and digits only otherwise (and not
3033 // all esoteric constructions ParseDateTime() knows about)
3035 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3037 const wxChar
*p
= date
;
3038 while ( wxIsspace(*p
) )
3041 // some special cases
3045 int dayDiffFromToday
;
3048 { wxTRANSLATE("today"), 0 },
3049 { wxTRANSLATE("yesterday"), -1 },
3050 { wxTRANSLATE("tomorrow"), 1 },
3053 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3055 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3056 size_t len
= date
.length();
3057 if ( wxStrlen(p
) >= len
&& (wxString(p
, len
).CmpNoCase(date
) == 0) )
3059 // nothing can follow this, so stop here
3062 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3064 if ( dayDiffFromToday
)
3066 *this += wxDateSpan::Days(dayDiffFromToday
);
3073 // We try to guess what we have here: for each new (numeric) token, we
3074 // determine if it can be a month, day or a year. Of course, there is an
3075 // ambiguity as some numbers may be days as well as months, so we also
3076 // have the ability to back track.
3079 bool haveDay
= FALSE
, // the months day?
3080 haveWDay
= FALSE
, // the day of week?
3081 haveMon
= FALSE
, // the month?
3082 haveYear
= FALSE
; // the year?
3084 // and the value of the items we have (init them to get rid of warnings)
3085 WeekDay wday
= Inv_WeekDay
;
3086 wxDateTime_t day
= 0;
3087 wxDateTime::Month mon
= Inv_Month
;
3090 // tokenize the string
3092 static const wxChar
*dateDelimiters
= _T(".,/-\t\n ");
3093 wxStringTokenizer
tok(p
, dateDelimiters
);
3094 while ( tok
.HasMoreTokens() )
3096 wxString token
= tok
.GetNextToken();
3102 if ( token
.ToULong(&val
) )
3104 // guess what this number is
3110 if ( !haveMon
&& val
> 0 && val
<= 12 )
3112 // assume it is month
3115 else // not the month
3117 wxDateTime_t maxDays
= haveMon
3118 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3122 if ( (val
== 0) || (val
> (unsigned long)maxDays
) ) // cast to shut up compiler warning in BCC
3139 year
= (wxDateTime_t
)val
;
3148 day
= (wxDateTime_t
)val
;
3154 mon
= (Month
)(val
- 1);
3157 else // not a number
3159 // be careful not to overwrite the current mon value
3160 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3161 if ( mon2
!= Inv_Month
)
3166 // but we already have a month - maybe we guessed wrong?
3169 // no need to check in month range as always < 12, but
3170 // the days are counted from 1 unlike the months
3171 day
= (wxDateTime_t
)mon
+ 1;
3176 // could possible be the year (doesn't the year come
3177 // before the month in the japanese format?) (FIXME)
3186 else // not a valid month name
3188 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3189 if ( wday
!= Inv_WeekDay
)
3199 else // not a valid weekday name
3202 static const wxChar
*ordinals
[] =
3204 wxTRANSLATE("first"),
3205 wxTRANSLATE("second"),
3206 wxTRANSLATE("third"),
3207 wxTRANSLATE("fourth"),
3208 wxTRANSLATE("fifth"),
3209 wxTRANSLATE("sixth"),
3210 wxTRANSLATE("seventh"),
3211 wxTRANSLATE("eighth"),
3212 wxTRANSLATE("ninth"),
3213 wxTRANSLATE("tenth"),
3214 wxTRANSLATE("eleventh"),
3215 wxTRANSLATE("twelfth"),
3216 wxTRANSLATE("thirteenth"),
3217 wxTRANSLATE("fourteenth"),
3218 wxTRANSLATE("fifteenth"),
3219 wxTRANSLATE("sixteenth"),
3220 wxTRANSLATE("seventeenth"),
3221 wxTRANSLATE("eighteenth"),
3222 wxTRANSLATE("nineteenth"),
3223 wxTRANSLATE("twentieth"),
3224 // that's enough - otherwise we'd have problems with
3225 // composite (or not) ordinals
3229 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3231 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3237 if ( n
== WXSIZEOF(ordinals
) )
3239 // stop here - something unknown
3246 // don't try anything here (as in case of numeric day
3247 // above) - the symbolic day spec should always
3248 // precede the month/year
3254 day
= (wxDateTime_t
)(n
+ 1);
3259 nPosCur
= tok
.GetPosition();
3262 // either no more tokens or the scan was stopped by something we couldn't
3263 // parse - in any case, see if we can construct a date from what we have
3264 if ( !haveDay
&& !haveWDay
)
3266 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3268 return (wxChar
*)NULL
;
3271 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3272 !(haveDay
&& haveMon
&& haveYear
) )
3274 // without adjectives (which we don't support here) the week day only
3275 // makes sense completely separately or with the full date
3276 // specification (what would "Wed 1999" mean?)
3277 return (wxChar
*)NULL
;
3280 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3282 // may be we have month and day instead of day and year?
3283 if ( haveDay
&& !haveMon
)
3287 // exchange day and month
3288 mon
= (wxDateTime::Month
)(day
- 1);
3290 // we're in the current year then
3292 (unsigned)year
<= GetNumOfDaysInMonth(Inv_Year
, mon
) )
3299 //else: no, can't exchange, leave haveMon == FALSE
3305 // if we give the year, month and day must be given too
3306 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3308 return (wxChar
*)NULL
;
3314 mon
= GetCurrentMonth();
3319 year
= GetCurrentYear();
3324 Set(day
, mon
, year
);
3328 // check that it is really the same
3329 if ( GetWeekDay() != wday
)
3331 // inconsistency detected
3332 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3334 return (wxChar
*)NULL
;
3342 SetToWeekDayInSameWeek(wday
);
3345 // return the pointer to the first unparsed char
3347 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3349 // if we couldn't parse the token after the delimiter, put back the
3350 // delimiter as well
3357 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3359 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3361 // first try some extra things
3368 { wxTRANSLATE("noon"), 12 },
3369 { wxTRANSLATE("midnight"), 00 },
3373 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3375 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3376 size_t len
= timeString
.length();
3377 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3379 Set(stdTimes
[n
].hour
, 0, 0);
3385 // try all time formats we may think about in the order from longest to
3388 // 12hour with AM/PM?
3389 const wxChar
*result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3393 // normally, it's the same, but why not try it?
3394 result
= ParseFormat(time
, _T("%H:%M:%S"));
3399 // 12hour with AM/PM but without seconds?
3400 result
= ParseFormat(time
, _T("%I:%M %p"));
3406 result
= ParseFormat(time
, _T("%H:%M"));
3411 // just the hour and AM/PM?
3412 result
= ParseFormat(time
, _T("%I %p"));
3418 result
= ParseFormat(time
, _T("%H"));
3423 // parse the standard format: normally it is one of the formats above
3424 // but it may be set to something completely different by the user
3425 result
= ParseFormat(time
, _T("%X"));
3428 // TODO: parse timezones
3433 // ----------------------------------------------------------------------------
3434 // Workdays and holidays support
3435 // ----------------------------------------------------------------------------
3437 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3439 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3442 // ============================================================================
3444 // ============================================================================
3446 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3447 // it locally to the method as it provokes an internal compiler error in egcs
3448 // 2.91.60 when building with -O2
3459 // not all strftime(3) format specifiers make sense here because, for example,
3460 // a time span doesn't have a year nor a timezone
3462 // Here are the ones which are supported (all of them are supported by strftime
3464 // %H hour in 24 hour format
3465 // %M minute (00 - 59)
3466 // %S second (00 - 59)
3469 // Also, for MFC CTimeSpan compatibility, we support
3470 // %D number of days
3472 // And, to be better than MFC :-), we also have
3473 // %E number of wEeks
3474 // %l milliseconds (000 - 999)
3475 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3477 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
3480 str
.Alloc(wxStrlen(format
));
3482 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3484 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3485 // question is what should ts.Format("%S") do? The code here returns "3273"
3486 // in this case (i.e. the total number of seconds, not just seconds % 60)
3487 // because, for me, this call means "give me entire time interval in
3488 // seconds" and not "give me the seconds part of the time interval"
3490 // If we agree that it should behave like this, it is clear that the
3491 // interpretation of each format specifier depends on the presence of the
3492 // other format specs in the string: if there was "%H" before "%M", we
3493 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3495 // we remember the most important unit found so far
3496 TimeSpanPart partBiggest
= Part_MSec
;
3498 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3502 if ( ch
== _T('%') )
3504 // the start of the format specification of the printf() below
3505 wxString fmtPrefix
= _T('%');
3510 ch
= *++pch
; // get the format spec char
3514 wxFAIL_MSG( _T("invalid format character") );
3520 // skip the part below switch
3525 if ( partBiggest
< Part_Day
)
3531 partBiggest
= Part_Day
;
3536 partBiggest
= Part_Week
;
3542 if ( partBiggest
< Part_Hour
)
3548 partBiggest
= Part_Hour
;
3551 fmtPrefix
+= _T("02");
3555 n
= GetMilliseconds().ToLong();
3556 if ( partBiggest
< Part_MSec
)
3560 //else: no need to reset partBiggest to Part_MSec, it is
3561 // the least significant one anyhow
3563 fmtPrefix
+= _T("03");
3568 if ( partBiggest
< Part_Min
)
3574 partBiggest
= Part_Min
;
3577 fmtPrefix
+= _T("02");
3581 n
= GetSeconds().ToLong();
3582 if ( partBiggest
< Part_Sec
)
3588 partBiggest
= Part_Sec
;
3591 fmtPrefix
+= _T("02");
3595 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
3599 // normal character, just copy
3607 // ============================================================================
3608 // wxDateTimeHolidayAuthority and related classes
3609 // ============================================================================
3611 #include "wx/arrimpl.cpp"
3613 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
3615 static int wxCMPFUNC_CONV
3616 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
3618 wxDateTime dt1
= **first
,
3621 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
3624 // ----------------------------------------------------------------------------
3625 // wxDateTimeHolidayAuthority
3626 // ----------------------------------------------------------------------------
3628 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
3631 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
3633 size_t count
= ms_authorities
.GetCount();
3634 for ( size_t n
= 0; n
< count
; n
++ )
3636 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
3647 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
3648 const wxDateTime
& dtEnd
,
3649 wxDateTimeArray
& holidays
)
3651 wxDateTimeArray hol
;
3655 size_t count
= ms_authorities
.GetCount();
3656 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
3658 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
3660 WX_APPEND_ARRAY(holidays
, hol
);
3663 holidays
.Sort(wxDateTimeCompareFunc
);
3665 return holidays
.GetCount();
3669 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3671 WX_CLEAR_ARRAY(ms_authorities
);
3675 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
3677 ms_authorities
.Add(auth
);
3680 // ----------------------------------------------------------------------------
3681 // wxDateTimeWorkDays
3682 // ----------------------------------------------------------------------------
3684 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
3686 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
3688 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
3691 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
3692 const wxDateTime
& dtEnd
,
3693 wxDateTimeArray
& holidays
) const
3695 if ( dtStart
> dtEnd
)
3697 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3704 // instead of checking all days, start with the first Sat after dtStart and
3705 // end with the last Sun before dtEnd
3706 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
3707 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
3708 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
3709 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
3712 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
3717 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
3722 return holidays
.GetCount();
3725 #endif // wxUSE_DATETIME