1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows licence
17 ///////////////////////////////////////////////////////////////////////////////
20 * Implementation notes:
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
47 // ============================================================================
49 // ============================================================================
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
56 #pragma implementation "datetime.h"
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
66 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
69 #include "wx/string.h"
74 #include "wx/thread.h"
75 #include "wx/tokenzr.h"
76 #include "wx/module.h"
78 #define wxDEFINE_TIME_CONSTANTS // before including datetime.h
82 #include "wx/datetime.h"
83 #include "wx/timer.h" // for wxGetLocalTimeMillis()
85 const long wxDateTime::TIME_T_FACTOR
= 1000l;
87 // ----------------------------------------------------------------------------
88 // conditional compilation
89 // ----------------------------------------------------------------------------
91 #if defined(HAVE_STRPTIME) && defined(__LINUX__)
92 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
93 // crash (instead of just failing):
95 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
96 // strptime(buf, "%x", &tm);
100 #endif // broken strptime()
102 #if defined(__MWERKS__) && wxUSE_UNICODE
106 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
107 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
108 #define WX_TIMEZONE _timezone
109 #elif defined(__MWERKS__)
110 long wxmw_timezone
= 28800;
111 #define WX_TIMEZONE wxmw_timezone
112 #elif defined(__DJGPP__) || defined(__WINE__)
113 #include <sys/timeb.h>
115 static long wxGetTimeZone()
117 static long timezone
= MAXLONG
; // invalid timezone
118 if (timezone
== MAXLONG
)
122 timezone
= tb
.timezone
;
126 #define WX_TIMEZONE wxGetTimeZone()
127 #elif defined(__DARWIN__)
128 #define WX_GMTOFF_IN_TM
129 #else // unknown platform - try timezone
130 #define WX_TIMEZONE timezone
132 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
134 // ----------------------------------------------------------------------------
136 // ----------------------------------------------------------------------------
138 // debugging helper: just a convenient replacement of wxCHECK()
139 #define wxDATETIME_CHECK(expr, msg) \
143 *this = wxInvalidDateTime; \
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
151 class wxDateTimeHolidaysModule
: public wxModule
154 virtual bool OnInit()
156 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
161 virtual void OnExit()
163 wxDateTimeHolidayAuthority::ClearAllAuthorities();
164 wxDateTimeHolidayAuthority::ms_authorities
.Clear();
168 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
171 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
178 static const int MONTHS_IN_YEAR
= 12;
180 static const int SEC_PER_MIN
= 60;
182 static const int MIN_PER_HOUR
= 60;
184 static const int HOURS_PER_DAY
= 24;
186 static const long SECONDS_PER_DAY
= 86400l;
188 static const int DAYS_PER_WEEK
= 7;
190 static const long MILLISECONDS_PER_DAY
= 86400000l;
192 // this is the integral part of JDN of the midnight of Jan 1, 1970
193 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
194 static const long EPOCH_JDN
= 2440587l;
196 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
197 // reference date for us) is Nov 24, 4714BC
198 static const int JDN_0_YEAR
= -4713;
199 static const int JDN_0_MONTH
= wxDateTime::Nov
;
200 static const int JDN_0_DAY
= 24;
202 // the constants used for JDN calculations
203 static const long JDN_OFFSET
= 32046l;
204 static const long DAYS_PER_5_MONTHS
= 153l;
205 static const long DAYS_PER_4_YEARS
= 1461l;
206 static const long DAYS_PER_400_YEARS
= 146097l;
208 // this array contains the cumulated number of days in all previous months for
209 // normal and leap years
210 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
212 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
213 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
216 // ----------------------------------------------------------------------------
218 // ----------------------------------------------------------------------------
220 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
221 // indicate an invalid wxDateTime object
222 const wxDateTime wxDefaultDateTime
;
224 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
226 // ----------------------------------------------------------------------------
228 // ----------------------------------------------------------------------------
230 // a critical section is needed to protect GetTimeZone() static
231 // variable in MT case
233 static wxCriticalSection gs_critsectTimezone
;
234 #endif // wxUSE_THREADS
236 // ----------------------------------------------------------------------------
238 // ----------------------------------------------------------------------------
240 // debugger helper: shows what the date really is
242 extern const wxChar
*wxDumpDate(const wxDateTime
* dt
)
244 static wxChar buf
[128];
246 wxStrcpy(buf
, dt
->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
252 // get the number of days in the given month of the given year
254 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
256 // the number of days in month in Julian/Gregorian calendar: the first line
257 // is for normal years, the second one is for the leap ones
258 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
260 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
261 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
264 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
267 // returns the time zone in the C sense, i.e. the difference UTC - local
269 static int GetTimeZone()
271 // set to TRUE when the timezone is set
272 static bool s_timezoneSet
= FALSE
;
273 #ifdef WX_GMTOFF_IN_TM
274 static long gmtoffset
= LONG_MAX
; // invalid timezone
277 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
279 // ensure that the timezone variable is set by calling localtime
280 if ( !s_timezoneSet
)
282 // just call localtime() instead of figuring out whether this system
283 // supports tzset(), _tzset() or something else
288 s_timezoneSet
= TRUE
;
290 #ifdef WX_GMTOFF_IN_TM
291 // note that GMT offset is the opposite of time zone and so to return
292 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
293 // cases we have to negate it
294 gmtoffset
= -tm
->tm_gmtoff
;
298 #ifdef WX_GMTOFF_IN_TM
299 return (int)gmtoffset
;
301 return (int)WX_TIMEZONE
;
305 // return the integral part of the JDN for the midnight of the given date (to
306 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
307 // noon of the previous day)
308 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
309 wxDateTime::Month mon
,
312 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
314 // check the date validity
316 (year
> JDN_0_YEAR
) ||
317 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
318 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
319 _T("date out of range - can't convert to JDN")
322 // make the year positive to avoid problems with negative numbers division
325 // months are counted from March here
327 if ( mon
>= wxDateTime::Mar
)
337 // now we can simply add all the contributions together
338 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
339 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
340 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
345 // this function is a wrapper around strftime(3)
346 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
349 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
351 // buffer is too small?
352 wxFAIL_MSG(_T("strftime() failed"));
355 return wxString(buf
);
358 // if year and/or month have invalid values, replace them with the current ones
359 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
360 wxDateTime::Month
*month
)
362 struct tm
*tmNow
= NULL
;
364 if ( *year
== wxDateTime::Inv_Year
)
366 tmNow
= wxDateTime::GetTmNow();
368 *year
= 1900 + tmNow
->tm_year
;
371 if ( *month
== wxDateTime::Inv_Month
)
374 tmNow
= wxDateTime::GetTmNow();
376 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
380 // fll the struct tm with default values
381 static void InitTm(struct tm
& tm
)
383 // struct tm may have etxra fields (undocumented and with unportable
384 // names) which, nevertheless, must be set to 0
385 memset(&tm
, 0, sizeof(struct tm
));
387 tm
.tm_mday
= 1; // mday 0 is invalid
388 tm
.tm_year
= 76; // any valid year
389 tm
.tm_isdst
= -1; // auto determine
395 // return the month if the string is a month name or Inv_Month otherwise
396 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
398 wxDateTime::Month mon
;
399 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
401 // case-insensitive comparison either one of or with both abbreviated
403 if ( flags
& wxDateTime::Name_Full
)
405 if ( name
.CmpNoCase(wxDateTime::
406 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
412 if ( flags
& wxDateTime::Name_Abbr
)
414 if ( name
.CmpNoCase(wxDateTime::
415 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
425 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
426 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
428 wxDateTime::WeekDay wd
;
429 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
431 // case-insensitive comparison either one of or with both abbreviated
433 if ( flags
& wxDateTime::Name_Full
)
435 if ( name
.CmpNoCase(wxDateTime::
436 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
442 if ( flags
& wxDateTime::Name_Abbr
)
444 if ( name
.CmpNoCase(wxDateTime::
445 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
455 // scans all digits (but no more than len) and returns the resulting number
456 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
460 while ( wxIsdigit(*p
) )
464 if ( len
&& ++n
> len
)
468 return !!s
&& s
.ToULong(number
);
471 // scans all alphabetic characters and returns the resulting string
472 static wxString
GetAlphaToken(const wxChar
*& p
)
475 while ( wxIsalpha(*p
) )
483 // ============================================================================
484 // implementation of wxDateTime
485 // ============================================================================
487 // ----------------------------------------------------------------------------
489 // ----------------------------------------------------------------------------
493 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
494 mon
= wxDateTime::Inv_Month
;
496 hour
= min
= sec
= msec
= 0;
497 wday
= wxDateTime::Inv_WeekDay
;
500 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
508 mon
= (wxDateTime::Month
)tm
.tm_mon
;
509 year
= 1900 + tm
.tm_year
;
514 bool wxDateTime::Tm::IsValid() const
516 // we allow for the leap seconds, although we don't use them (yet)
517 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
518 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
519 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
522 void wxDateTime::Tm::ComputeWeekDay()
524 // compute the week day from day/month/year: we use the dumbest algorithm
525 // possible: just compute our JDN and then use the (simple to derive)
526 // formula: weekday = (JDN + 1.5) % 7
527 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
530 void wxDateTime::Tm::AddMonths(int monDiff
)
532 // normalize the months field
533 while ( monDiff
< -mon
)
537 monDiff
+= MONTHS_IN_YEAR
;
540 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
544 monDiff
-= MONTHS_IN_YEAR
;
547 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
549 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
551 // NB: we don't check here that the resulting date is valid, this function
552 // is private and the caller must check it if needed
555 void wxDateTime::Tm::AddDays(int dayDiff
)
557 // normalize the days field
558 while ( dayDiff
+ mday
< 1 )
562 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
566 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
568 mday
-= GetNumOfDaysInMonth(year
, mon
);
573 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
581 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
585 case wxDateTime::Local
:
586 // get the offset from C RTL: it returns the difference GMT-local
587 // while we want to have the offset _from_ GMT, hence the '-'
588 m_offset
= -GetTimeZone();
591 case wxDateTime::GMT_12
:
592 case wxDateTime::GMT_11
:
593 case wxDateTime::GMT_10
:
594 case wxDateTime::GMT_9
:
595 case wxDateTime::GMT_8
:
596 case wxDateTime::GMT_7
:
597 case wxDateTime::GMT_6
:
598 case wxDateTime::GMT_5
:
599 case wxDateTime::GMT_4
:
600 case wxDateTime::GMT_3
:
601 case wxDateTime::GMT_2
:
602 case wxDateTime::GMT_1
:
603 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
606 case wxDateTime::GMT0
:
607 case wxDateTime::GMT1
:
608 case wxDateTime::GMT2
:
609 case wxDateTime::GMT3
:
610 case wxDateTime::GMT4
:
611 case wxDateTime::GMT5
:
612 case wxDateTime::GMT6
:
613 case wxDateTime::GMT7
:
614 case wxDateTime::GMT8
:
615 case wxDateTime::GMT9
:
616 case wxDateTime::GMT10
:
617 case wxDateTime::GMT11
:
618 case wxDateTime::GMT12
:
619 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
622 case wxDateTime::A_CST
:
623 // Central Standard Time in use in Australia = UTC + 9.5
624 m_offset
= 60l*(9*60 + 30);
628 wxFAIL_MSG( _T("unknown time zone") );
632 // ----------------------------------------------------------------------------
634 // ----------------------------------------------------------------------------
637 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
639 if ( year
== Inv_Year
)
640 year
= GetCurrentYear();
642 if ( cal
== Gregorian
)
644 // in Gregorian calendar leap years are those divisible by 4 except
645 // those divisible by 100 unless they're also divisible by 400
646 // (in some countries, like Russia and Greece, additional corrections
647 // exist, but they won't manifest themselves until 2700)
648 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
650 else if ( cal
== Julian
)
652 // in Julian calendar the rule is simpler
653 return year
% 4 == 0;
657 wxFAIL_MSG(_T("unknown calendar"));
664 int wxDateTime::GetCentury(int year
)
666 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
670 int wxDateTime::ConvertYearToBC(int year
)
673 return year
> 0 ? year
: year
- 1;
677 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
682 return Now().GetYear();
685 wxFAIL_MSG(_T("TODO"));
689 wxFAIL_MSG(_T("unsupported calendar"));
697 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
702 return Now().GetMonth();
705 wxFAIL_MSG(_T("TODO"));
709 wxFAIL_MSG(_T("unsupported calendar"));
717 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
719 if ( year
== Inv_Year
)
721 // take the current year if none given
722 year
= GetCurrentYear();
729 return IsLeapYear(year
) ? 366 : 365;
732 wxFAIL_MSG(_T("unsupported calendar"));
740 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
742 wxDateTime::Calendar cal
)
744 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
746 if ( cal
== Gregorian
|| cal
== Julian
)
748 if ( year
== Inv_Year
)
750 // take the current year if none given
751 year
= GetCurrentYear();
754 return GetNumOfDaysInMonth(year
, month
);
758 wxFAIL_MSG(_T("unsupported calendar"));
765 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
766 wxDateTime::NameFlags flags
)
768 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
770 // notice that we must set all the fields to avoid confusing libc (GNU one
771 // gets confused to a crash if we don't do this)
776 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
780 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
781 wxDateTime::NameFlags flags
)
783 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
785 // take some arbitrary Sunday
792 // and offset it by the number of days needed to get the correct wday
795 // call mktime() to normalize it...
798 // ... and call strftime()
799 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
803 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
809 *am
= CallStrftime(_T("%p"), &tm
);
814 *pm
= CallStrftime(_T("%p"), &tm
);
818 // ----------------------------------------------------------------------------
819 // Country stuff: date calculations depend on the country (DST, work days,
820 // ...), so we need to know which rules to follow.
821 // ----------------------------------------------------------------------------
824 wxDateTime::Country
wxDateTime::GetCountry()
826 // TODO use LOCALE_ICOUNTRY setting under Win32
828 if ( ms_country
== Country_Unknown
)
830 // try to guess from the time zone name
831 time_t t
= time(NULL
);
832 struct tm
*tm
= localtime(&t
);
834 wxString tz
= CallStrftime(_T("%Z"), tm
);
835 if ( tz
== _T("WET") || tz
== _T("WEST") )
839 else if ( tz
== _T("CET") || tz
== _T("CEST") )
841 ms_country
= Country_EEC
;
843 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
847 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
848 tz
== _T("EST") || tz
== _T("EDT") ||
849 tz
== _T("CST") || tz
== _T("CDT") ||
850 tz
== _T("MST") || tz
== _T("MDT") ||
851 tz
== _T("PST") || tz
== _T("PDT") )
857 // well, choose a default one
866 void wxDateTime::SetCountry(wxDateTime::Country country
)
868 ms_country
= country
;
872 bool wxDateTime::IsWestEuropeanCountry(Country country
)
874 if ( country
== Country_Default
)
876 country
= GetCountry();
879 return (Country_WesternEurope_Start
<= country
) &&
880 (country
<= Country_WesternEurope_End
);
883 // ----------------------------------------------------------------------------
884 // DST calculations: we use 3 different rules for the West European countries,
885 // USA and for the rest of the world. This is undoubtedly false for many
886 // countries, but I lack the necessary info (and the time to gather it),
887 // please add the other rules here!
888 // ----------------------------------------------------------------------------
891 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
893 if ( year
== Inv_Year
)
895 // take the current year if none given
896 year
= GetCurrentYear();
899 if ( country
== Country_Default
)
901 country
= GetCountry();
908 // DST was first observed in the US and UK during WWI, reused
909 // during WWII and used again since 1966
910 return year
>= 1966 ||
911 (year
>= 1942 && year
<= 1945) ||
912 (year
== 1918 || year
== 1919);
915 // assume that it started after WWII
921 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
923 if ( year
== Inv_Year
)
925 // take the current year if none given
926 year
= GetCurrentYear();
929 if ( country
== Country_Default
)
931 country
= GetCountry();
934 if ( !IsDSTApplicable(year
, country
) )
936 return wxInvalidDateTime
;
941 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
943 // DST begins at 1 a.m. GMT on the last Sunday of March
944 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
947 wxFAIL_MSG( _T("no last Sunday in March?") );
950 dt
+= wxTimeSpan::Hours(1);
952 // disable DST tests because it could result in an infinite recursion!
955 else switch ( country
)
962 // don't know for sure - assume it was in effect all year
967 dt
.Set(1, Jan
, year
);
971 // DST was installed Feb 2, 1942 by the Congress
972 dt
.Set(2, Feb
, year
);
975 // Oil embargo changed the DST period in the US
977 dt
.Set(6, Jan
, 1974);
981 dt
.Set(23, Feb
, 1975);
985 // before 1986, DST begun on the last Sunday of April, but
986 // in 1986 Reagan changed it to begin at 2 a.m. of the
987 // first Sunday in April
990 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
993 wxFAIL_MSG( _T("no first Sunday in April?") );
998 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1001 wxFAIL_MSG( _T("no first Sunday in April?") );
1005 dt
+= wxTimeSpan::Hours(2);
1007 // TODO what about timezone??
1013 // assume Mar 30 as the start of the DST for the rest of the world
1014 // - totally bogus, of course
1015 dt
.Set(30, Mar
, year
);
1022 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1024 if ( year
== Inv_Year
)
1026 // take the current year if none given
1027 year
= GetCurrentYear();
1030 if ( country
== Country_Default
)
1032 country
= GetCountry();
1035 if ( !IsDSTApplicable(year
, country
) )
1037 return wxInvalidDateTime
;
1042 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1044 // DST ends at 1 a.m. GMT on the last Sunday of October
1045 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1047 // weirder and weirder...
1048 wxFAIL_MSG( _T("no last Sunday in October?") );
1051 dt
+= wxTimeSpan::Hours(1);
1053 // disable DST tests because it could result in an infinite recursion!
1056 else switch ( country
)
1063 // don't know for sure - assume it was in effect all year
1067 dt
.Set(31, Dec
, year
);
1071 // the time was reset after the end of the WWII
1072 dt
.Set(30, Sep
, year
);
1076 // DST ends at 2 a.m. on the last Sunday of October
1077 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1079 // weirder and weirder...
1080 wxFAIL_MSG( _T("no last Sunday in October?") );
1083 dt
+= wxTimeSpan::Hours(2);
1085 // TODO what about timezone??
1090 // assume October 26th as the end of the DST - totally bogus too
1091 dt
.Set(26, Oct
, year
);
1097 // ----------------------------------------------------------------------------
1098 // constructors and assignment operators
1099 // ----------------------------------------------------------------------------
1101 // return the current time with ms precision
1102 /* static */ wxDateTime
wxDateTime::UNow()
1104 return wxDateTime(wxGetLocalTimeMillis());
1107 // the values in the tm structure contain the local time
1108 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1111 time_t timet
= mktime(&tm2
);
1113 if ( timet
== (time_t)-1 )
1115 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1116 // less than timezone - try to make it work for this case
1117 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1119 // add timezone to make sure that date is in range
1120 tm2
.tm_sec
-= GetTimeZone();
1122 timet
= mktime(&tm2
);
1123 if ( timet
!= (time_t)-1 )
1125 timet
+= GetTimeZone();
1131 wxFAIL_MSG( _T("mktime() failed") );
1133 *this = wxInvalidDateTime
;
1143 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1144 wxDateTime_t minute
,
1145 wxDateTime_t second
,
1146 wxDateTime_t millisec
)
1148 // we allow seconds to be 61 to account for the leap seconds, even if we
1149 // don't use them really
1150 wxDATETIME_CHECK( hour
< 24 &&
1154 _T("Invalid time in wxDateTime::Set()") );
1156 // get the current date from system
1157 struct tm
*tm
= GetTmNow();
1159 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1163 tm
->tm_min
= minute
;
1164 tm
->tm_sec
= second
;
1168 // and finally adjust milliseconds
1169 return SetMillisecond(millisec
);
1172 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1176 wxDateTime_t minute
,
1177 wxDateTime_t second
,
1178 wxDateTime_t millisec
)
1180 wxDATETIME_CHECK( hour
< 24 &&
1184 _T("Invalid time in wxDateTime::Set()") );
1186 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1188 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1189 _T("Invalid date in wxDateTime::Set()") );
1191 // the range of time_t type (inclusive)
1192 static const int yearMinInRange
= 1970;
1193 static const int yearMaxInRange
= 2037;
1195 // test only the year instead of testing for the exact end of the Unix
1196 // time_t range - it doesn't bring anything to do more precise checks
1197 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1199 // use the standard library version if the date is in range - this is
1200 // probably more efficient than our code
1202 tm
.tm_year
= year
- 1900;
1208 tm
.tm_isdst
= -1; // mktime() will guess it
1212 // and finally adjust milliseconds
1213 return SetMillisecond(millisec
);
1217 // do time calculations ourselves: we want to calculate the number of
1218 // milliseconds between the given date and the epoch
1220 // get the JDN for the midnight of this day
1221 m_time
= GetTruncatedJDN(day
, month
, year
);
1222 m_time
-= EPOCH_JDN
;
1223 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1225 // JDN corresponds to GMT, we take localtime
1226 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1232 wxDateTime
& wxDateTime::Set(double jdn
)
1234 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1236 jdn
-= EPOCH_JDN
+ 0.5;
1238 jdn
*= MILLISECONDS_PER_DAY
;
1245 wxDateTime
& wxDateTime::ResetTime()
1249 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1262 // ----------------------------------------------------------------------------
1263 // DOS Date and Time Format functions
1264 // ----------------------------------------------------------------------------
1265 // the dos date and time value is an unsigned 32 bit value in the format:
1266 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1268 // Y = year offset from 1980 (0-127)
1270 // D = day of month (1-31)
1272 // m = minute (0-59)
1273 // s = bisecond (0-29) each bisecond indicates two seconds
1274 // ----------------------------------------------------------------------------
1276 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1280 long year
= ddt
& 0xFE000000;
1285 long month
= ddt
& 0x1E00000;
1290 long day
= ddt
& 0x1F0000;
1294 long hour
= ddt
& 0xF800;
1298 long minute
= ddt
& 0x7E0;
1302 long second
= ddt
& 0x1F;
1303 tm
.tm_sec
= second
* 2;
1305 return Set(mktime(&tm
));
1308 unsigned long wxDateTime::GetAsDOS() const
1311 time_t ticks
= GetTicks();
1312 struct tm
*tm
= localtime(&ticks
);
1314 long year
= tm
->tm_year
;
1318 long month
= tm
->tm_mon
;
1322 long day
= tm
->tm_mday
;
1325 long hour
= tm
->tm_hour
;
1328 long minute
= tm
->tm_min
;
1331 long second
= tm
->tm_sec
;
1334 ddt
= year
| month
| day
| hour
| minute
| second
;
1338 // ----------------------------------------------------------------------------
1339 // time_t <-> broken down time conversions
1340 // ----------------------------------------------------------------------------
1342 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1344 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1346 time_t time
= GetTicks();
1347 if ( time
!= (time_t)-1 )
1349 // use C RTL functions
1351 if ( tz
.GetOffset() == -GetTimeZone() )
1353 // we are working with local time
1354 tm
= localtime(&time
);
1356 // should never happen
1357 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1361 time
+= (time_t)tz
.GetOffset();
1362 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1363 int time2
= (int) time
;
1371 // should never happen
1372 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1376 tm
= (struct tm
*)NULL
;
1382 // adjust the milliseconds
1384 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1385 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1388 //else: use generic code below
1391 // remember the time and do the calculations with the date only - this
1392 // eliminates rounding errors of the floating point arithmetics
1394 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1396 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1398 // we want to always have positive time and timeMidnight to be really
1399 // the midnight before it
1402 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1405 timeMidnight
-= timeOnly
;
1407 // calculate the Gregorian date from JDN for the midnight of our date:
1408 // this will yield day, month (in 1..12 range) and year
1410 // actually, this is the JDN for the noon of the previous day
1411 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1413 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1415 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1417 // calculate the century
1418 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1419 long century
= temp
/ DAYS_PER_400_YEARS
;
1421 // then the year and day of year (1 <= dayOfYear <= 366)
1422 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1423 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1424 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1426 // and finally the month and day of the month
1427 temp
= dayOfYear
* 5 - 3;
1428 long month
= temp
/ DAYS_PER_5_MONTHS
;
1429 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1431 // month is counted from March - convert to normal
1442 // year is offset by 4800
1445 // check that the algorithm gave us something reasonable
1446 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1447 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1449 // construct Tm from these values
1451 tm
.year
= (int)year
;
1452 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1453 tm
.mday
= (wxDateTime_t
)day
;
1454 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1455 timeOnly
-= tm
.msec
;
1456 timeOnly
/= 1000; // now we have time in seconds
1458 tm
.sec
= (wxDateTime_t
)(timeOnly
% 60);
1460 timeOnly
/= 60; // now we have time in minutes
1462 tm
.min
= (wxDateTime_t
)(timeOnly
% 60);
1465 tm
.hour
= (wxDateTime_t
)(timeOnly
/ 60);
1470 wxDateTime
& wxDateTime::SetYear(int year
)
1472 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1481 wxDateTime
& wxDateTime::SetMonth(Month month
)
1483 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1492 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1494 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1503 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1505 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1514 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1516 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1525 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1527 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1536 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1538 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1540 // we don't need to use GetTm() for this one
1541 m_time
-= m_time
% 1000l;
1542 m_time
+= millisecond
;
1547 // ----------------------------------------------------------------------------
1548 // wxDateTime arithmetics
1549 // ----------------------------------------------------------------------------
1551 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1555 tm
.year
+= diff
.GetYears();
1556 tm
.AddMonths(diff
.GetMonths());
1558 // check that the resulting date is valid
1559 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1561 // We suppose that when adding one month to Jan 31 we want to get Feb
1562 // 28 (or 29), i.e. adding a month to the last day of the month should
1563 // give the last day of the next month which is quite logical.
1565 // Unfortunately, there is no logic way to understand what should
1566 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1567 // We make it Feb 28 (last day too), but it is highly questionable.
1568 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1571 tm
.AddDays(diff
.GetTotalDays());
1575 wxASSERT_MSG( IsSameTime(tm
),
1576 _T("Add(wxDateSpan) shouldn't modify time") );
1581 // ----------------------------------------------------------------------------
1582 // Weekday and monthday stuff
1583 // ----------------------------------------------------------------------------
1585 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1589 wxASSERT_MSG( numWeek
> 0,
1590 _T("invalid week number: weeks are counted from 1") );
1592 int year
= GetYear();
1594 // Jan 4 always lies in the 1st week of the year
1596 SetToWeekDayInSameWeek(weekday
, flags
) += wxDateSpan::Weeks(numWeek
- 1);
1598 if ( GetYear() != year
)
1600 // oops... numWeek was too big
1607 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1610 // take the current month/year if none specified
1611 if ( year
== Inv_Year
)
1613 if ( month
== Inv_Month
)
1616 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1619 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1621 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1623 int wdayThis
= GetWeekDay();
1624 if ( weekday
== wdayThis
)
1630 if ( flags
== Default_First
)
1632 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1635 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1636 // is the first day in the week, but breaks down for Monday_First case so
1637 // we adjust the week days in this case
1638 if( flags
== Monday_First
)
1640 if ( wdayThis
== Sun
)
1643 //else: Sunday_First, nothing to do
1645 // go forward or back in time to the day we want
1646 if ( weekday
< wdayThis
)
1648 return Subtract(wxDateSpan::Days(wdayThis
- weekday
));
1650 else // weekday > wdayThis
1652 return Add(wxDateSpan::Days(weekday
- wdayThis
));
1656 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1658 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1661 WeekDay wdayThis
= GetWeekDay();
1662 if ( weekday
== wdayThis
)
1667 else if ( weekday
< wdayThis
)
1669 // need to advance a week
1670 diff
= 7 - (wdayThis
- weekday
);
1672 else // weekday > wdayThis
1674 diff
= weekday
- wdayThis
;
1677 return Add(wxDateSpan::Days(diff
));
1680 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1682 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1685 WeekDay wdayThis
= GetWeekDay();
1686 if ( weekday
== wdayThis
)
1691 else if ( weekday
> wdayThis
)
1693 // need to go to previous week
1694 diff
= 7 - (weekday
- wdayThis
);
1696 else // weekday < wdayThis
1698 diff
= wdayThis
- weekday
;
1701 return Subtract(wxDateSpan::Days(diff
));
1704 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1709 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1711 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1712 // anyhow in such case - but may be should still give an assert for it?
1714 // take the current month/year if none specified
1715 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1719 // TODO this probably could be optimised somehow...
1723 // get the first day of the month
1724 dt
.Set(1, month
, year
);
1727 WeekDay wdayFirst
= dt
.GetWeekDay();
1729 // go to the first weekday of the month
1730 int diff
= weekday
- wdayFirst
;
1734 // add advance n-1 weeks more
1737 dt
+= wxDateSpan::Days(diff
);
1739 else // count from the end of the month
1741 // get the last day of the month
1742 dt
.SetToLastMonthDay(month
, year
);
1745 WeekDay wdayLast
= dt
.GetWeekDay();
1747 // go to the last weekday of the month
1748 int diff
= wdayLast
- weekday
;
1752 // and rewind n-1 weeks from there
1755 dt
-= wxDateSpan::Days(diff
);
1758 // check that it is still in the same month
1759 if ( dt
.GetMonth() == month
)
1767 // no such day in this month
1772 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1776 return gs_cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1779 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
,
1780 const TimeZone
& tz
) const
1782 if ( flags
== Default_First
)
1784 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1787 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1790 WeekDay wd
= GetWeekDay(tz
);
1791 if ( flags
== Sunday_First
)
1793 week
= (nDayInYear
- wd
+ 7) / 7;
1797 // have to shift the week days values
1798 week
= (nDayInYear
- (wd
- 1 + 7) % 7 + 7) / 7;
1801 // FIXME some more elegant way??
1802 WeekDay wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1803 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1811 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1812 const TimeZone
& tz
) const
1815 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
1816 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
1819 // this may happen for January when Jan, 1 is the last week of the
1821 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
1824 return (wxDateTime::wxDateTime_t
)nWeek
;
1827 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
1829 int year
= GetYear();
1830 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
1831 _T("invalid year day") );
1833 bool isLeap
= IsLeapYear(year
);
1834 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
1836 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1837 // don't need it neither - because of the CHECK above we know that
1838 // yday lies in December then
1839 if ( (mon
== Dec
) || (yday
< gs_cumulatedDays
[isLeap
][mon
+ 1]) )
1841 Set(yday
- gs_cumulatedDays
[isLeap
][mon
], mon
, year
);
1850 // ----------------------------------------------------------------------------
1851 // Julian day number conversion and related stuff
1852 // ----------------------------------------------------------------------------
1854 double wxDateTime::GetJulianDayNumber() const
1856 // JDN are always expressed for the GMT dates
1857 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1859 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1861 // add the part GetTruncatedJDN() neglected
1864 // and now add the time: 86400 sec = 1 JDN
1865 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1868 double wxDateTime::GetRataDie() const
1870 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1871 return GetJulianDayNumber() - 1721119.5 - 306;
1874 // ----------------------------------------------------------------------------
1875 // timezone and DST stuff
1876 // ----------------------------------------------------------------------------
1878 int wxDateTime::IsDST(wxDateTime::Country country
) const
1880 wxCHECK_MSG( country
== Country_Default
, -1,
1881 _T("country support not implemented") );
1883 // use the C RTL for the dates in the standard range
1884 time_t timet
= GetTicks();
1885 if ( timet
!= (time_t)-1 )
1887 tm
*tm
= localtime(&timet
);
1889 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1891 return tm
->tm_isdst
;
1895 int year
= GetYear();
1897 if ( !IsDSTApplicable(year
, country
) )
1899 // no DST time in this year in this country
1903 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1907 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
1909 long secDiff
= GetTimeZone() + tz
.GetOffset();
1911 // we need to know whether DST is or not in effect for this date unless
1912 // the test disabled by the caller
1913 if ( !noDST
&& (IsDST() == 1) )
1915 // FIXME we assume that the DST is always shifted by 1 hour
1919 return Subtract(wxTimeSpan::Seconds(secDiff
));
1922 // ----------------------------------------------------------------------------
1923 // wxDateTime to/from text representations
1924 // ----------------------------------------------------------------------------
1926 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1928 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1930 // we have to use our own implementation if the date is out of range of
1931 // strftime() or if we use non standard specificators
1932 time_t time
= GetTicks();
1933 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
1937 if ( tz
.GetOffset() == -GetTimeZone() )
1939 // we are working with local time
1940 tm
= localtime(&time
);
1942 // should never happen
1943 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1947 time
+= (int)tz
.GetOffset();
1949 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1950 int time2
= (int) time
;
1958 // should never happen
1959 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1963 tm
= (struct tm
*)NULL
;
1969 return CallStrftime(format
, tm
);
1971 //else: use generic code below
1974 // we only parse ANSI C format specifications here, no POSIX 2
1975 // complications, no GNU extensions but we do add support for a "%l" format
1976 // specifier allowing to get the number of milliseconds
1979 // used for calls to strftime() when we only deal with time
1980 struct tm tmTimeOnly
;
1981 tmTimeOnly
.tm_hour
= tm
.hour
;
1982 tmTimeOnly
.tm_min
= tm
.min
;
1983 tmTimeOnly
.tm_sec
= tm
.sec
;
1984 tmTimeOnly
.tm_wday
= 0;
1985 tmTimeOnly
.tm_yday
= 0;
1986 tmTimeOnly
.tm_mday
= 1; // any date will do
1987 tmTimeOnly
.tm_mon
= 0;
1988 tmTimeOnly
.tm_year
= 76;
1989 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
1991 wxString tmp
, res
, fmt
;
1992 for ( const wxChar
*p
= format
; *p
; p
++ )
1994 if ( *p
!= _T('%') )
2002 // set the default format
2005 case _T('Y'): // year has 4 digits
2009 case _T('j'): // day of year has 3 digits
2010 case _T('l'): // milliseconds have 3 digits
2014 case _T('w'): // week day as number has only one
2019 // it's either another valid format specifier in which case
2020 // the format is "%02d" (for all the rest) or we have the
2021 // field width preceding the format in which case it will
2022 // override the default format anyhow
2026 bool restart
= TRUE
;
2031 // start of the format specification
2034 case _T('a'): // a weekday name
2036 // second parameter should be TRUE for abbreviated names
2037 res
+= GetWeekDayName(tm
.GetWeekDay(),
2038 *p
== _T('a') ? Name_Abbr
: Name_Full
);
2041 case _T('b'): // a month name
2043 res
+= GetMonthName(tm
.mon
,
2044 *p
== _T('b') ? Name_Abbr
: Name_Full
);
2047 case _T('c'): // locale default date and time representation
2048 case _T('x'): // locale default date representation
2050 // the problem: there is no way to know what do these format
2051 // specifications correspond to for the current locale.
2053 // the solution: use a hack and still use strftime(): first
2054 // find the YEAR which is a year in the strftime() range (1970
2055 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
2056 // of the real year. Then make a copy of the format and
2057 // replace all occurences of YEAR in it with some unique
2058 // string not appearing anywhere else in it, then use
2059 // strftime() to format the date in year YEAR and then replace
2060 // YEAR back by the real year and the unique replacement
2061 // string back with YEAR. Notice that "all occurences of YEAR"
2062 // means all occurences of 4 digit as well as 2 digit form!
2064 // the bugs: we assume that neither of %c nor %x contains any
2065 // fields which may change between the YEAR and real year. For
2066 // example, the week number (%U, %W) and the day number (%j)
2067 // will change if one of these years is leap and the other one
2070 // find the YEAR: normally, for any year X, Jan 1 or the
2071 // year X + 28 is the same weekday as Jan 1 of X (because
2072 // the weekday advances by 1 for each normal X and by 2
2073 // for each leap X, hence by 5 every 4 years or by 35
2074 // which is 0 mod 7 every 28 years) but this rule breaks
2075 // down if there are years between X and Y which are
2076 // divisible by 4 but not leap (i.e. divisible by 100 but
2077 // not 400), hence the correction.
2079 int yearReal
= GetYear(tz
);
2080 int mod28
= yearReal
% 28;
2082 // be careful to not go too far - we risk to leave the
2087 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
2091 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
2094 int nCentury
= year
/ 100,
2095 nCenturyReal
= yearReal
/ 100;
2097 // need to adjust for the years divisble by 400 which are
2098 // not leap but are counted like leap ones if we just take
2099 // the number of centuries in between for nLostWeekDays
2100 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
2101 (nCentury
/ 4 - nCenturyReal
/ 4);
2103 // we have to gain back the "lost" weekdays: note that the
2104 // effect of this loop is to not do anything to
2105 // nLostWeekDays (which we won't use any more), but to
2106 // (indirectly) set the year correctly
2107 while ( (nLostWeekDays
% 7) != 0 )
2109 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
2112 // at any rate, we couldn't go further than 1988 + 9 + 28!
2113 wxASSERT_MSG( year
< 2030,
2114 _T("logic error in wxDateTime::Format") );
2116 wxString strYear
, strYear2
;
2117 strYear
.Printf(_T("%d"), year
);
2118 strYear2
.Printf(_T("%d"), year
% 100);
2120 // find two strings not occuring in format (this is surely
2121 // not optimal way of doing it... improvements welcome!)
2122 wxString fmt
= format
;
2123 wxString replacement
= (wxChar
)-1;
2124 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2126 replacement
<< (wxChar
)-1;
2129 wxString replacement2
= (wxChar
)-2;
2130 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2132 replacement
<< (wxChar
)-2;
2135 // replace all occurences of year with it
2136 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
2138 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
2140 // use strftime() to format the same date but in supported
2143 // NB: we assume that strftime() doesn't check for the
2144 // date validity and will happily format the date
2145 // corresponding to Feb 29 of a non leap year (which
2146 // may happen if yearReal was leap and year is not)
2147 struct tm tmAdjusted
;
2149 tmAdjusted
.tm_hour
= tm
.hour
;
2150 tmAdjusted
.tm_min
= tm
.min
;
2151 tmAdjusted
.tm_sec
= tm
.sec
;
2152 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
2153 tmAdjusted
.tm_yday
= GetDayOfYear();
2154 tmAdjusted
.tm_mday
= tm
.mday
;
2155 tmAdjusted
.tm_mon
= tm
.mon
;
2156 tmAdjusted
.tm_year
= year
- 1900;
2157 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
2158 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
2162 // now replace the occurence of 1999 with the real year
2163 wxString strYearReal
, strYearReal2
;
2164 strYearReal
.Printf(_T("%04d"), yearReal
);
2165 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
2166 str
.Replace(strYear
, strYearReal
);
2167 str
.Replace(strYear2
, strYearReal2
);
2169 // and replace back all occurences of replacement string
2172 str
.Replace(replacement2
, strYear2
);
2173 str
.Replace(replacement
, strYear
);
2180 case _T('d'): // day of a month (01-31)
2181 res
+= wxString::Format(fmt
, tm
.mday
);
2184 case _T('H'): // hour in 24h format (00-23)
2185 res
+= wxString::Format(fmt
, tm
.hour
);
2188 case _T('I'): // hour in 12h format (01-12)
2190 // 24h -> 12h, 0h -> 12h too
2191 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
2192 : tm
.hour
? tm
.hour
: 12;
2193 res
+= wxString::Format(fmt
, hour12
);
2197 case _T('j'): // day of the year
2198 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
2201 case _T('l'): // milliseconds (NOT STANDARD)
2202 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
2205 case _T('m'): // month as a number (01-12)
2206 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
2209 case _T('M'): // minute as a decimal number (00-59)
2210 res
+= wxString::Format(fmt
, tm
.min
);
2213 case _T('p'): // AM or PM string
2214 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
2217 case _T('S'): // second as a decimal number (00-61)
2218 res
+= wxString::Format(fmt
, tm
.sec
);
2221 case _T('U'): // week number in the year (Sunday 1st week day)
2222 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
2225 case _T('W'): // week number in the year (Monday 1st week day)
2226 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
2229 case _T('w'): // weekday as a number (0-6), Sunday = 0
2230 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
2233 // case _T('x'): -- handled with "%c"
2235 case _T('X'): // locale default time representation
2236 // just use strftime() to format the time for us
2237 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
2240 case _T('y'): // year without century (00-99)
2241 res
+= wxString::Format(fmt
, tm
.year
% 100);
2244 case _T('Y'): // year with century
2245 res
+= wxString::Format(fmt
, tm
.year
);
2248 case _T('Z'): // timezone name
2249 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
2253 // is it the format width?
2255 while ( *p
== _T('-') || *p
== _T('+') ||
2256 *p
== _T(' ') || wxIsdigit(*p
) )
2261 if ( !fmt
.IsEmpty() )
2263 // we've only got the flags and width so far in fmt
2264 fmt
.Prepend(_T('%'));
2265 fmt
.Append(_T('d'));
2272 // no, it wasn't the width
2273 wxFAIL_MSG(_T("unknown format specificator"));
2275 // fall through and just copy it nevertheless
2277 case _T('%'): // a percent sign
2281 case 0: // the end of string
2282 wxFAIL_MSG(_T("missing format at the end of string"));
2284 // just put the '%' which was the last char in format
2294 // this function parses a string in (strict) RFC 822 format: see the section 5
2295 // of the RFC for the detailed description, but briefly it's something of the
2296 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2298 // this function is "strict" by design - it must reject anything except true
2299 // RFC822 time specs.
2301 // TODO a great candidate for using reg exps
2302 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
2304 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2306 const wxChar
*p
= date
;
2307 const wxChar
*comma
= wxStrchr(p
, _T(','));
2310 // the part before comma is the weekday
2312 // skip it for now - we don't use but might check that it really
2313 // corresponds to the specfied date
2316 if ( *p
!= _T(' ') )
2318 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2320 return (wxChar
*)NULL
;
2326 // the following 1 or 2 digits are the day number
2327 if ( !wxIsdigit(*p
) )
2329 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2331 return (wxChar
*)NULL
;
2334 wxDateTime_t day
= *p
++ - _T('0');
2335 if ( wxIsdigit(*p
) )
2338 day
+= *p
++ - _T('0');
2341 if ( *p
++ != _T(' ') )
2343 return (wxChar
*)NULL
;
2346 // the following 3 letters specify the month
2347 wxString
monName(p
, 3);
2349 if ( monName
== _T("Jan") )
2351 else if ( monName
== _T("Feb") )
2353 else if ( monName
== _T("Mar") )
2355 else if ( monName
== _T("Apr") )
2357 else if ( monName
== _T("May") )
2359 else if ( monName
== _T("Jun") )
2361 else if ( monName
== _T("Jul") )
2363 else if ( monName
== _T("Aug") )
2365 else if ( monName
== _T("Sep") )
2367 else if ( monName
== _T("Oct") )
2369 else if ( monName
== _T("Nov") )
2371 else if ( monName
== _T("Dec") )
2375 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
2377 return (wxChar
*)NULL
;
2382 if ( *p
++ != _T(' ') )
2384 return (wxChar
*)NULL
;
2388 if ( !wxIsdigit(*p
) )
2391 return (wxChar
*)NULL
;
2394 int year
= *p
++ - _T('0');
2396 if ( !wxIsdigit(*p
) )
2398 // should have at least 2 digits in the year
2399 return (wxChar
*)NULL
;
2403 year
+= *p
++ - _T('0');
2405 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2406 if ( wxIsdigit(*p
) )
2409 year
+= *p
++ - _T('0');
2411 if ( !wxIsdigit(*p
) )
2413 // no 3 digit years please
2414 return (wxChar
*)NULL
;
2418 year
+= *p
++ - _T('0');
2421 if ( *p
++ != _T(' ') )
2423 return (wxChar
*)NULL
;
2426 // time is in the format hh:mm:ss and seconds are optional
2427 if ( !wxIsdigit(*p
) )
2429 return (wxChar
*)NULL
;
2432 wxDateTime_t hour
= *p
++ - _T('0');
2434 if ( !wxIsdigit(*p
) )
2436 return (wxChar
*)NULL
;
2440 hour
+= *p
++ - _T('0');
2442 if ( *p
++ != _T(':') )
2444 return (wxChar
*)NULL
;
2447 if ( !wxIsdigit(*p
) )
2449 return (wxChar
*)NULL
;
2452 wxDateTime_t min
= *p
++ - _T('0');
2454 if ( !wxIsdigit(*p
) )
2456 return (wxChar
*)NULL
;
2460 min
+= *p
++ - _T('0');
2462 wxDateTime_t sec
= 0;
2463 if ( *p
++ == _T(':') )
2465 if ( !wxIsdigit(*p
) )
2467 return (wxChar
*)NULL
;
2470 sec
= *p
++ - _T('0');
2472 if ( !wxIsdigit(*p
) )
2474 return (wxChar
*)NULL
;
2478 sec
+= *p
++ - _T('0');
2481 if ( *p
++ != _T(' ') )
2483 return (wxChar
*)NULL
;
2486 // and now the interesting part: the timezone
2488 if ( *p
== _T('-') || *p
== _T('+') )
2490 // the explicit offset given: it has the form of hhmm
2491 bool plus
= *p
++ == _T('+');
2493 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2495 return (wxChar
*)NULL
;
2499 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
2503 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2505 return (wxChar
*)NULL
;
2509 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
2520 // the symbolic timezone given: may be either military timezone or one
2521 // of standard abbreviations
2524 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2525 static const int offsets
[26] =
2527 //A B C D E F G H I J K L M
2528 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2529 //N O P R Q S T U V W Z Y Z
2530 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2533 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
2535 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
2537 return (wxChar
*)NULL
;
2540 offset
= offsets
[*p
++ - _T('A')];
2546 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
2548 else if ( tz
== _T("AST") )
2549 offset
= AST
- GMT0
;
2550 else if ( tz
== _T("ADT") )
2551 offset
= ADT
- GMT0
;
2552 else if ( tz
== _T("EST") )
2553 offset
= EST
- GMT0
;
2554 else if ( tz
== _T("EDT") )
2555 offset
= EDT
- GMT0
;
2556 else if ( tz
== _T("CST") )
2557 offset
= CST
- GMT0
;
2558 else if ( tz
== _T("CDT") )
2559 offset
= CDT
- GMT0
;
2560 else if ( tz
== _T("MST") )
2561 offset
= MST
- GMT0
;
2562 else if ( tz
== _T("MDT") )
2563 offset
= MDT
- GMT0
;
2564 else if ( tz
== _T("PST") )
2565 offset
= PST
- GMT0
;
2566 else if ( tz
== _T("PDT") )
2567 offset
= PDT
- GMT0
;
2570 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
2572 return (wxChar
*)NULL
;
2582 // the spec was correct
2583 Set(day
, mon
, year
, hour
, min
, sec
);
2584 MakeTimezone((wxDateTime_t
)(60*offset
));
2589 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
,
2590 const wxChar
*format
,
2591 const wxDateTime
& dateDef
)
2593 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
2594 _T("NULL pointer in wxDateTime::ParseFormat()") );
2599 // what fields have we found?
2600 bool haveWDay
= FALSE
,
2609 bool hourIsIn12hFormat
= FALSE
, // or in 24h one?
2610 isPM
= FALSE
; // AM by default
2612 // and the value of the items we have (init them to get rid of warnings)
2613 wxDateTime_t sec
= 0,
2616 WeekDay wday
= Inv_WeekDay
;
2617 wxDateTime_t yday
= 0,
2619 wxDateTime::Month mon
= Inv_Month
;
2622 const wxChar
*input
= date
;
2623 for ( const wxChar
*fmt
= format
; *fmt
; fmt
++ )
2625 if ( *fmt
!= _T('%') )
2627 if ( wxIsspace(*fmt
) )
2629 // a white space in the format string matches 0 or more white
2630 // spaces in the input
2631 while ( wxIsspace(*input
) )
2638 // any other character (not whitespace, not '%') must be
2639 // matched by itself in the input
2640 if ( *input
++ != *fmt
)
2643 return (wxChar
*)NULL
;
2647 // done with this format char
2651 // start of a format specification
2653 // parse the optional width
2655 while ( isdigit(*++fmt
) )
2658 width
+= *fmt
- _T('0');
2661 // the default widths for the various fields
2666 case _T('Y'): // year has 4 digits
2670 case _T('j'): // day of year has 3 digits
2671 case _T('l'): // milliseconds have 3 digits
2675 case _T('w'): // week day as number has only one
2680 // default for all other fields
2685 // then the format itself
2688 case _T('a'): // a weekday name
2691 int flag
= *fmt
== _T('a') ? Name_Abbr
: Name_Full
;
2692 wday
= GetWeekDayFromName(GetAlphaToken(input
), flag
);
2693 if ( wday
== Inv_WeekDay
)
2696 return (wxChar
*)NULL
;
2702 case _T('b'): // a month name
2705 int flag
= *fmt
== _T('b') ? Name_Abbr
: Name_Full
;
2706 mon
= GetMonthFromName(GetAlphaToken(input
), flag
);
2707 if ( mon
== Inv_Month
)
2710 return (wxChar
*)NULL
;
2716 case _T('c'): // locale default date and time representation
2720 // this is the format which corresponds to ctime() output
2721 // and strptime("%c") should parse it, so try it first
2722 static const wxChar
*fmtCtime
= _T("%a %b %d %H:%M:%S %Y");
2724 const wxChar
*result
= dt
.ParseFormat(input
, fmtCtime
);
2727 result
= dt
.ParseFormat(input
, _T("%x %X"));
2732 result
= dt
.ParseFormat(input
, _T("%X %x"));
2737 // we've tried everything and still no match
2738 return (wxChar
*)NULL
;
2743 haveDay
= haveMon
= haveYear
=
2744 haveHour
= haveMin
= haveSec
= TRUE
;
2758 case _T('d'): // day of a month (01-31)
2759 if ( !GetNumericToken(width
, input
, &num
) ||
2760 (num
> 31) || (num
< 1) )
2763 return (wxChar
*)NULL
;
2766 // we can't check whether the day range is correct yet, will
2767 // do it later - assume ok for now
2769 mday
= (wxDateTime_t
)num
;
2772 case _T('H'): // hour in 24h format (00-23)
2773 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
2776 return (wxChar
*)NULL
;
2780 hour
= (wxDateTime_t
)num
;
2783 case _T('I'): // hour in 12h format (01-12)
2784 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2787 return (wxChar
*)NULL
;
2791 hourIsIn12hFormat
= TRUE
;
2792 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
2795 case _T('j'): // day of the year
2796 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
2799 return (wxChar
*)NULL
;
2803 yday
= (wxDateTime_t
)num
;
2806 case _T('m'): // month as a number (01-12)
2807 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2810 return (wxChar
*)NULL
;
2814 mon
= (Month
)(num
- 1);
2817 case _T('M'): // minute as a decimal number (00-59)
2818 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
2821 return (wxChar
*)NULL
;
2825 min
= (wxDateTime_t
)num
;
2828 case _T('p'): // AM or PM string
2830 wxString am
, pm
, token
= GetAlphaToken(input
);
2832 GetAmPmStrings(&am
, &pm
);
2833 if ( token
.CmpNoCase(pm
) == 0 )
2837 else if ( token
.CmpNoCase(am
) != 0 )
2840 return (wxChar
*)NULL
;
2845 case _T('r'): // time as %I:%M:%S %p
2848 input
= dt
.ParseFormat(input
, _T("%I:%M:%S %p"));
2852 return (wxChar
*)NULL
;
2855 haveHour
= haveMin
= haveSec
= TRUE
;
2864 case _T('R'): // time as %H:%M
2867 input
= dt
.ParseFormat(input
, _T("%H:%M"));
2871 return (wxChar
*)NULL
;
2874 haveHour
= haveMin
= TRUE
;
2881 case _T('S'): // second as a decimal number (00-61)
2882 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
2885 return (wxChar
*)NULL
;
2889 sec
= (wxDateTime_t
)num
;
2892 case _T('T'): // time as %H:%M:%S
2895 input
= dt
.ParseFormat(input
, _T("%H:%M:%S"));
2899 return (wxChar
*)NULL
;
2902 haveHour
= haveMin
= haveSec
= TRUE
;
2911 case _T('w'): // weekday as a number (0-6), Sunday = 0
2912 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
2915 return (wxChar
*)NULL
;
2919 wday
= (WeekDay
)num
;
2922 case _T('x'): // locale default date representation
2923 #ifdef HAVE_STRPTIME
2924 // try using strptime() - it may fail even if the input is
2925 // correct but the date is out of range, so we will fall back
2926 // to our generic code anyhow (FIXME !Unicode friendly)
2929 const wxChar
*result
= strptime(input
, "%x", &tm
);
2934 haveDay
= haveMon
= haveYear
= TRUE
;
2936 year
= 1900 + tm
.tm_year
;
2937 mon
= (Month
)tm
.tm_mon
;
2943 #endif // HAVE_STRPTIME
2945 // TODO query the LOCALE_IDATE setting under Win32
2949 wxString fmtDate
, fmtDateAlt
;
2950 if ( IsWestEuropeanCountry(GetCountry()) ||
2951 GetCountry() == Russia
)
2953 fmtDate
= _T("%d/%m/%y");
2954 fmtDateAlt
= _T("%m/%d/%y");
2958 fmtDate
= _T("%m/%d/%y");
2959 fmtDateAlt
= _T("%d/%m/%y");
2962 const wxChar
*result
= dt
.ParseFormat(input
, fmtDate
);
2966 // ok, be nice and try another one
2967 result
= dt
.ParseFormat(input
, fmtDateAlt
);
2973 return (wxChar
*)NULL
;
2978 haveDay
= haveMon
= haveYear
= TRUE
;
2989 case _T('X'): // locale default time representation
2990 #ifdef HAVE_STRPTIME
2992 // use strptime() to do it for us (FIXME !Unicode friendly)
2994 input
= strptime(input
, "%X", &tm
);
2997 return (wxChar
*)NULL
;
3000 haveHour
= haveMin
= haveSec
= TRUE
;
3006 #else // !HAVE_STRPTIME
3007 // TODO under Win32 we can query the LOCALE_ITIME system
3008 // setting which says whether the default time format is
3011 // try to parse what follows as "%H:%M:%S" and, if this
3012 // fails, as "%I:%M:%S %p" - this should catch the most
3016 const wxChar
*result
= dt
.ParseFormat(input
, _T("%T"));
3019 result
= dt
.ParseFormat(input
, _T("%r"));
3025 return (wxChar
*)NULL
;
3028 haveHour
= haveMin
= haveSec
= TRUE
;
3037 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3040 case _T('y'): // year without century (00-99)
3041 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
3044 return (wxChar
*)NULL
;
3049 // TODO should have an option for roll over date instead of
3050 // hard coding it here
3051 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
3054 case _T('Y'): // year with century
3055 if ( !GetNumericToken(width
, input
, &num
) )
3058 return (wxChar
*)NULL
;
3062 year
= (wxDateTime_t
)num
;
3065 case _T('Z'): // timezone name
3066 wxFAIL_MSG(_T("TODO"));
3069 case _T('%'): // a percent sign
3070 if ( *input
++ != _T('%') )
3073 return (wxChar
*)NULL
;
3077 case 0: // the end of string
3078 wxFAIL_MSG(_T("unexpected format end"));
3082 default: // not a known format spec
3083 return (wxChar
*)NULL
;
3087 // format matched, try to construct a date from what we have now
3089 if ( dateDef
.IsValid() )
3091 // take this date as default
3092 tmDef
= dateDef
.GetTm();
3094 else if ( IsValid() )
3096 // if this date is valid, don't change it
3101 // no default and this date is invalid - fall back to Today()
3102 tmDef
= Today().GetTm();
3113 // TODO we don't check here that the values are consistent, if both year
3114 // day and month/day were found, we just ignore the year day and we
3115 // also always ignore the week day
3116 if ( haveMon
&& haveDay
)
3118 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
3120 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3122 return (wxChar
*)NULL
;
3128 else if ( haveYDay
)
3130 if ( yday
> GetNumberOfDays(tm
.year
) )
3132 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3134 return (wxChar
*)NULL
;
3137 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
3144 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
3146 // translate to 24hour format
3149 //else: either already in 24h format or no translation needed
3172 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3174 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3176 // there is a public domain version of getdate.y, but it only works for
3178 wxFAIL_MSG(_T("TODO"));
3180 return (wxChar
*)NULL
;
3183 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3185 // this is a simplified version of ParseDateTime() which understands only
3186 // "today" (for wxDate compatibility) and digits only otherwise (and not
3187 // all esoteric constructions ParseDateTime() knows about)
3189 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3191 const wxChar
*p
= date
;
3192 while ( wxIsspace(*p
) )
3195 // some special cases
3199 int dayDiffFromToday
;
3202 { wxTRANSLATE("today"), 0 },
3203 { wxTRANSLATE("yesterday"), -1 },
3204 { wxTRANSLATE("tomorrow"), 1 },
3207 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3209 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3210 size_t len
= date
.length();
3211 if ( wxStrlen(p
) >= len
&& (wxString(p
, len
).CmpNoCase(date
) == 0) )
3213 // nothing can follow this, so stop here
3216 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3218 if ( dayDiffFromToday
)
3220 *this += wxDateSpan::Days(dayDiffFromToday
);
3227 // We try to guess what we have here: for each new (numeric) token, we
3228 // determine if it can be a month, day or a year. Of course, there is an
3229 // ambiguity as some numbers may be days as well as months, so we also
3230 // have the ability to back track.
3233 bool haveDay
= FALSE
, // the months day?
3234 haveWDay
= FALSE
, // the day of week?
3235 haveMon
= FALSE
, // the month?
3236 haveYear
= FALSE
; // the year?
3238 // and the value of the items we have (init them to get rid of warnings)
3239 WeekDay wday
= Inv_WeekDay
;
3240 wxDateTime_t day
= 0;
3241 wxDateTime::Month mon
= Inv_Month
;
3244 // tokenize the string
3246 static const wxChar
*dateDelimiters
= _T(".,/-\t\r\n ");
3247 wxStringTokenizer
tok(p
, dateDelimiters
);
3248 while ( tok
.HasMoreTokens() )
3250 wxString token
= tok
.GetNextToken();
3256 if ( token
.ToULong(&val
) )
3258 // guess what this number is
3264 if ( !haveMon
&& val
> 0 && val
<= 12 )
3266 // assume it is month
3269 else // not the month
3271 wxDateTime_t maxDays
= haveMon
3272 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3276 if ( (val
== 0) || (val
> (unsigned long)maxDays
) ) // cast to shut up compiler warning in BCC
3293 year
= (wxDateTime_t
)val
;
3302 day
= (wxDateTime_t
)val
;
3308 mon
= (Month
)(val
- 1);
3311 else // not a number
3313 // be careful not to overwrite the current mon value
3314 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3315 if ( mon2
!= Inv_Month
)
3320 // but we already have a month - maybe we guessed wrong?
3323 // no need to check in month range as always < 12, but
3324 // the days are counted from 1 unlike the months
3325 day
= (wxDateTime_t
)mon
+ 1;
3330 // could possible be the year (doesn't the year come
3331 // before the month in the japanese format?) (FIXME)
3340 else // not a valid month name
3342 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3343 if ( wday
!= Inv_WeekDay
)
3353 else // not a valid weekday name
3356 static const wxChar
*ordinals
[] =
3358 wxTRANSLATE("first"),
3359 wxTRANSLATE("second"),
3360 wxTRANSLATE("third"),
3361 wxTRANSLATE("fourth"),
3362 wxTRANSLATE("fifth"),
3363 wxTRANSLATE("sixth"),
3364 wxTRANSLATE("seventh"),
3365 wxTRANSLATE("eighth"),
3366 wxTRANSLATE("ninth"),
3367 wxTRANSLATE("tenth"),
3368 wxTRANSLATE("eleventh"),
3369 wxTRANSLATE("twelfth"),
3370 wxTRANSLATE("thirteenth"),
3371 wxTRANSLATE("fourteenth"),
3372 wxTRANSLATE("fifteenth"),
3373 wxTRANSLATE("sixteenth"),
3374 wxTRANSLATE("seventeenth"),
3375 wxTRANSLATE("eighteenth"),
3376 wxTRANSLATE("nineteenth"),
3377 wxTRANSLATE("twentieth"),
3378 // that's enough - otherwise we'd have problems with
3379 // composite (or not) ordinals
3383 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3385 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3391 if ( n
== WXSIZEOF(ordinals
) )
3393 // stop here - something unknown
3400 // don't try anything here (as in case of numeric day
3401 // above) - the symbolic day spec should always
3402 // precede the month/year
3408 day
= (wxDateTime_t
)(n
+ 1);
3413 nPosCur
= tok
.GetPosition();
3416 // either no more tokens or the scan was stopped by something we couldn't
3417 // parse - in any case, see if we can construct a date from what we have
3418 if ( !haveDay
&& !haveWDay
)
3420 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3422 return (wxChar
*)NULL
;
3425 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3426 !(haveDay
&& haveMon
&& haveYear
) )
3428 // without adjectives (which we don't support here) the week day only
3429 // makes sense completely separately or with the full date
3430 // specification (what would "Wed 1999" mean?)
3431 return (wxChar
*)NULL
;
3434 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3436 // may be we have month and day instead of day and year?
3437 if ( haveDay
&& !haveMon
)
3441 // exchange day and month
3442 mon
= (wxDateTime::Month
)(day
- 1);
3444 // we're in the current year then
3446 (unsigned)year
<= GetNumOfDaysInMonth(Inv_Year
, mon
) )
3453 //else: no, can't exchange, leave haveMon == FALSE
3459 // if we give the year, month and day must be given too
3460 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3462 return (wxChar
*)NULL
;
3468 mon
= GetCurrentMonth();
3473 year
= GetCurrentYear();
3478 Set(day
, mon
, year
);
3482 // check that it is really the same
3483 if ( GetWeekDay() != wday
)
3485 // inconsistency detected
3486 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3488 return (wxChar
*)NULL
;
3496 SetToWeekDayInSameWeek(wday
);
3499 // return the pointer to the first unparsed char
3501 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3503 // if we couldn't parse the token after the delimiter, put back the
3504 // delimiter as well
3511 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3513 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3515 // first try some extra things
3522 { wxTRANSLATE("noon"), 12 },
3523 { wxTRANSLATE("midnight"), 00 },
3527 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3529 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3530 size_t len
= timeString
.length();
3531 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3533 Set(stdTimes
[n
].hour
, 0, 0);
3539 // try all time formats we may think about in the order from longest to
3542 // 12hour with AM/PM?
3543 const wxChar
*result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3547 // normally, it's the same, but why not try it?
3548 result
= ParseFormat(time
, _T("%H:%M:%S"));
3553 // 12hour with AM/PM but without seconds?
3554 result
= ParseFormat(time
, _T("%I:%M %p"));
3560 result
= ParseFormat(time
, _T("%H:%M"));
3565 // just the hour and AM/PM?
3566 result
= ParseFormat(time
, _T("%I %p"));
3572 result
= ParseFormat(time
, _T("%H"));
3577 // parse the standard format: normally it is one of the formats above
3578 // but it may be set to something completely different by the user
3579 result
= ParseFormat(time
, _T("%X"));
3582 // TODO: parse timezones
3587 // ----------------------------------------------------------------------------
3588 // Workdays and holidays support
3589 // ----------------------------------------------------------------------------
3591 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3593 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3596 // ============================================================================
3598 // ============================================================================
3600 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3601 // it locally to the method as it provokes an internal compiler error in egcs
3602 // 2.91.60 when building with -O2
3613 // not all strftime(3) format specifiers make sense here because, for example,
3614 // a time span doesn't have a year nor a timezone
3616 // Here are the ones which are supported (all of them are supported by strftime
3618 // %H hour in 24 hour format
3619 // %M minute (00 - 59)
3620 // %S second (00 - 59)
3623 // Also, for MFC CTimeSpan compatibility, we support
3624 // %D number of days
3626 // And, to be better than MFC :-), we also have
3627 // %E number of wEeks
3628 // %l milliseconds (000 - 999)
3629 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3631 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
3634 str
.Alloc(wxStrlen(format
));
3636 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3638 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3639 // question is what should ts.Format("%S") do? The code here returns "3273"
3640 // in this case (i.e. the total number of seconds, not just seconds % 60)
3641 // because, for me, this call means "give me entire time interval in
3642 // seconds" and not "give me the seconds part of the time interval"
3644 // If we agree that it should behave like this, it is clear that the
3645 // interpretation of each format specifier depends on the presence of the
3646 // other format specs in the string: if there was "%H" before "%M", we
3647 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3649 // we remember the most important unit found so far
3650 TimeSpanPart partBiggest
= Part_MSec
;
3652 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3656 if ( ch
== _T('%') )
3658 // the start of the format specification of the printf() below
3659 wxString fmtPrefix
= _T('%');
3664 ch
= *++pch
; // get the format spec char
3668 wxFAIL_MSG( _T("invalid format character") );
3674 // skip the part below switch
3679 if ( partBiggest
< Part_Day
)
3685 partBiggest
= Part_Day
;
3690 partBiggest
= Part_Week
;
3696 if ( partBiggest
< Part_Hour
)
3702 partBiggest
= Part_Hour
;
3705 fmtPrefix
+= _T("02");
3709 n
= GetMilliseconds().ToLong();
3710 if ( partBiggest
< Part_MSec
)
3714 //else: no need to reset partBiggest to Part_MSec, it is
3715 // the least significant one anyhow
3717 fmtPrefix
+= _T("03");
3722 if ( partBiggest
< Part_Min
)
3728 partBiggest
= Part_Min
;
3731 fmtPrefix
+= _T("02");
3735 n
= GetSeconds().ToLong();
3736 if ( partBiggest
< Part_Sec
)
3742 partBiggest
= Part_Sec
;
3745 fmtPrefix
+= _T("02");
3749 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
3753 // normal character, just copy
3761 // ============================================================================
3762 // wxDateTimeHolidayAuthority and related classes
3763 // ============================================================================
3765 #include "wx/arrimpl.cpp"
3767 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
3769 static int wxCMPFUNC_CONV
3770 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
3772 wxDateTime dt1
= **first
,
3775 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
3778 // ----------------------------------------------------------------------------
3779 // wxDateTimeHolidayAuthority
3780 // ----------------------------------------------------------------------------
3782 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
3785 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
3787 size_t count
= ms_authorities
.GetCount();
3788 for ( size_t n
= 0; n
< count
; n
++ )
3790 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
3801 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
3802 const wxDateTime
& dtEnd
,
3803 wxDateTimeArray
& holidays
)
3805 wxDateTimeArray hol
;
3809 size_t count
= ms_authorities
.GetCount();
3810 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
3812 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
3814 WX_APPEND_ARRAY(holidays
, hol
);
3817 holidays
.Sort(wxDateTimeCompareFunc
);
3819 return holidays
.GetCount();
3823 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3825 WX_CLEAR_ARRAY(ms_authorities
);
3829 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
3831 ms_authorities
.Add(auth
);
3834 // ----------------------------------------------------------------------------
3835 // wxDateTimeWorkDays
3836 // ----------------------------------------------------------------------------
3838 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
3840 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
3842 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
3845 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
3846 const wxDateTime
& dtEnd
,
3847 wxDateTimeArray
& holidays
) const
3849 if ( dtStart
> dtEnd
)
3851 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3858 // instead of checking all days, start with the first Sat after dtStart and
3859 // end with the last Sun before dtEnd
3860 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
3861 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
3862 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
3863 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
3866 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
3871 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
3876 return holidays
.GetCount();
3879 #endif // wxUSE_DATETIME