1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows licence
17 ///////////////////////////////////////////////////////////////////////////////
20 * Implementation notes:
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
47 // ============================================================================
49 // ============================================================================
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
56 #pragma implementation "datetime.h"
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
66 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
69 #include "wx/string.h"
74 #include "wx/thread.h"
75 #include "wx/tokenzr.h"
76 #include "wx/module.h"
80 #include "wx/datetime.h"
81 #include "wx/timer.h" // for wxGetLocalTimeMillis()
83 const long wxDateTime::TIME_T_FACTOR
= 1000l;
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 #if defined(HAVE_STRPTIME) && defined(__GLIBC__) && \
90 ((__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
91 // glibc 2.0.7 strptime() is broken - the following snippet causes it to
92 // crash (instead of just failing):
94 // strncpy(buf, "Tue Dec 21 20:25:40 1999", 128);
95 // strptime(buf, "%x", &tm);
99 #endif // broken strptime()
101 #if defined(__MWERKS__) && wxUSE_UNICODE
105 #if !defined(WX_TIMEZONE) && !defined(WX_GMTOFF_IN_TM)
106 #if defined(__BORLANDC__) || defined(__MINGW32__) || defined(__VISAGECPP__)
107 #define WX_TIMEZONE _timezone
108 #elif defined(__MWERKS__)
109 long wxmw_timezone
= 28800;
110 #define WX_TIMEZONE wxmw_timezone
111 #elif defined(__DJGPP__) || defined(__WINE__)
112 #include <sys/timeb.h>
114 static long wxGetTimeZone()
116 static long timezone
= MAXLONG
; // invalid timezone
117 if (timezone
== MAXLONG
)
121 timezone
= tb
.timezone
;
125 #define WX_TIMEZONE wxGetTimeZone()
126 #elif defined(__DARWIN__)
127 #define WX_GMTOFF_IN_TM
128 #else // unknown platform - try timezone
129 #define WX_TIMEZONE timezone
131 #endif // !WX_TIMEZONE && !WX_GMTOFF_IN_TM
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 // debugging helper: just a convenient replacement of wxCHECK()
138 #define wxDATETIME_CHECK(expr, msg) \
142 *this = wxInvalidDateTime; \
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
150 class wxDateTimeHolidaysModule
: public wxModule
153 virtual bool OnInit()
155 wxDateTimeHolidayAuthority::AddAuthority(new wxDateTimeWorkDays
);
160 virtual void OnExit()
162 wxDateTimeHolidayAuthority::ClearAllAuthorities();
163 wxDateTimeHolidayAuthority::ms_authorities
.clear();
167 DECLARE_DYNAMIC_CLASS(wxDateTimeHolidaysModule
)
170 IMPLEMENT_DYNAMIC_CLASS(wxDateTimeHolidaysModule
, wxModule
)
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
177 static const int MONTHS_IN_YEAR
= 12;
179 static const int SEC_PER_MIN
= 60;
181 static const int MIN_PER_HOUR
= 60;
183 static const int HOURS_PER_DAY
= 24;
185 static const long SECONDS_PER_DAY
= 86400l;
187 static const int DAYS_PER_WEEK
= 7;
189 static const long MILLISECONDS_PER_DAY
= 86400000l;
191 // this is the integral part of JDN of the midnight of Jan 1, 1970
192 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
193 static const long EPOCH_JDN
= 2440587l;
195 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
196 // reference date for us) is Nov 24, 4714BC
197 static const int JDN_0_YEAR
= -4713;
198 static const int JDN_0_MONTH
= wxDateTime::Nov
;
199 static const int JDN_0_DAY
= 24;
201 // the constants used for JDN calculations
202 static const long JDN_OFFSET
= 32046l;
203 static const long DAYS_PER_5_MONTHS
= 153l;
204 static const long DAYS_PER_4_YEARS
= 1461l;
205 static const long DAYS_PER_400_YEARS
= 146097l;
207 // this array contains the cumulated number of days in all previous months for
208 // normal and leap years
209 static const wxDateTime::wxDateTime_t gs_cumulatedDays
[2][MONTHS_IN_YEAR
] =
211 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
212 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
215 // ----------------------------------------------------------------------------
217 // ----------------------------------------------------------------------------
219 // in the fine tradition of ANSI C we use our equivalent of (time_t)-1 to
220 // indicate an invalid wxDateTime object
221 const wxDateTime wxDefaultDateTime
;
223 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 // a critical section is needed to protect GetTimeZone() static
230 // variable in MT case
232 static wxCriticalSection gs_critsectTimezone
;
233 #endif // wxUSE_THREADS
235 // ----------------------------------------------------------------------------
237 // ----------------------------------------------------------------------------
239 // debugger helper: shows what the date really is
241 extern const wxChar
*wxDumpDate(const wxDateTime
* dt
)
243 static wxChar buf
[128];
245 wxStrcpy(buf
, dt
->Format(_T("%Y-%m-%d (%a) %H:%M:%S")));
251 // get the number of days in the given month of the given year
253 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
255 // the number of days in month in Julian/Gregorian calendar: the first line
256 // is for normal years, the second one is for the leap ones
257 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
259 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
260 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
263 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
266 // returns the time zone in the C sense, i.e. the difference UTC - local
268 static int GetTimeZone()
270 // set to TRUE when the timezone is set
271 static bool s_timezoneSet
= FALSE
;
272 #ifdef WX_GMTOFF_IN_TM
273 static long gmtoffset
= LONG_MAX
; // invalid timezone
276 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
278 // ensure that the timezone variable is set by calling localtime
279 if ( !s_timezoneSet
)
281 // just call localtime() instead of figuring out whether this system
282 // supports tzset(), _tzset() or something else
287 s_timezoneSet
= TRUE
;
289 #ifdef WX_GMTOFF_IN_TM
290 // note that GMT offset is the opposite of time zone and so to return
291 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
292 // cases we have to negate it
293 gmtoffset
= -tm
->tm_gmtoff
;
297 #ifdef WX_GMTOFF_IN_TM
298 return (int)gmtoffset
;
300 return (int)WX_TIMEZONE
;
304 // return the integral part of the JDN for the midnight of the given date (to
305 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
306 // noon of the previous day)
307 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
308 wxDateTime::Month mon
,
311 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
313 // check the date validity
315 (year
> JDN_0_YEAR
) ||
316 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
317 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
318 _T("date out of range - can't convert to JDN")
321 // make the year positive to avoid problems with negative numbers division
324 // months are counted from March here
326 if ( mon
>= wxDateTime::Mar
)
336 // now we can simply add all the contributions together
337 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
338 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
339 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
344 // this function is a wrapper around strftime(3) adding error checking
345 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
348 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
350 // buffer is too small?
351 wxFAIL_MSG(_T("strftime() failed"));
354 return wxString(buf
);
359 // Unicode-friendly strptime() wrapper
360 static const wxChar
*
361 CallStrptime(const wxChar
*input
, const char *fmt
, tm
*tm
)
363 // the problem here is that strptime() returns pointer into the string we
364 // passed to it while we're really interested in the pointer into the
365 // original, Unicode, string so we try to transform the pointer back
367 wxCharBuffer
inputMB(wxConvertWX2MB(input
));
369 const char * const inputMB
= input
;
370 #endif // Unicode/Ascii
372 const char *result
= strptime(inputMB
, fmt
, tm
);
377 // FIXME: this is wrong in presence of surrogates &c
378 return input
+ (result
- inputMB
.data());
381 #endif // Unicode/Ascii
384 #endif // HAVE_STRPTIME
386 // if year and/or month have invalid values, replace them with the current ones
387 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
388 wxDateTime::Month
*month
)
390 struct tm
*tmNow
= NULL
;
392 if ( *year
== wxDateTime::Inv_Year
)
394 tmNow
= wxDateTime::GetTmNow();
396 *year
= 1900 + tmNow
->tm_year
;
399 if ( *month
== wxDateTime::Inv_Month
)
402 tmNow
= wxDateTime::GetTmNow();
404 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
408 // fll the struct tm with default values
409 static void InitTm(struct tm
& tm
)
411 // struct tm may have etxra fields (undocumented and with unportable
412 // names) which, nevertheless, must be set to 0
413 memset(&tm
, 0, sizeof(struct tm
));
415 tm
.tm_mday
= 1; // mday 0 is invalid
416 tm
.tm_year
= 76; // any valid year
417 tm
.tm_isdst
= -1; // auto determine
423 // return the month if the string is a month name or Inv_Month otherwise
424 static wxDateTime::Month
GetMonthFromName(const wxString
& name
, int flags
)
426 wxDateTime::Month mon
;
427 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
429 // case-insensitive comparison either one of or with both abbreviated
431 if ( flags
& wxDateTime::Name_Full
)
433 if ( name
.CmpNoCase(wxDateTime::
434 GetMonthName(mon
, wxDateTime::Name_Full
)) == 0 )
440 if ( flags
& wxDateTime::Name_Abbr
)
442 if ( name
.CmpNoCase(wxDateTime::
443 GetMonthName(mon
, wxDateTime::Name_Abbr
)) == 0 )
453 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
454 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
, int flags
)
456 wxDateTime::WeekDay wd
;
457 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
459 // case-insensitive comparison either one of or with both abbreviated
461 if ( flags
& wxDateTime::Name_Full
)
463 if ( name
.CmpNoCase(wxDateTime::
464 GetWeekDayName(wd
, wxDateTime::Name_Full
)) == 0 )
470 if ( flags
& wxDateTime::Name_Abbr
)
472 if ( name
.CmpNoCase(wxDateTime::
473 GetWeekDayName(wd
, wxDateTime::Name_Abbr
)) == 0 )
483 // scans all digits (but no more than len) and returns the resulting number
484 static bool GetNumericToken(size_t len
, const wxChar
*& p
, unsigned long *number
)
488 while ( wxIsdigit(*p
) )
492 if ( len
&& ++n
> len
)
496 return !!s
&& s
.ToULong(number
);
499 // scans all alphabetic characters and returns the resulting string
500 static wxString
GetAlphaToken(const wxChar
*& p
)
503 while ( wxIsalpha(*p
) )
511 // ============================================================================
512 // implementation of wxDateTime
513 // ============================================================================
515 // ----------------------------------------------------------------------------
517 // ----------------------------------------------------------------------------
521 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
522 mon
= wxDateTime::Inv_Month
;
524 hour
= min
= sec
= msec
= 0;
525 wday
= wxDateTime::Inv_WeekDay
;
528 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
536 mon
= (wxDateTime::Month
)tm
.tm_mon
;
537 year
= 1900 + tm
.tm_year
;
542 bool wxDateTime::Tm::IsValid() const
544 // we allow for the leap seconds, although we don't use them (yet)
545 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
546 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
547 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
550 void wxDateTime::Tm::ComputeWeekDay()
552 // compute the week day from day/month/year: we use the dumbest algorithm
553 // possible: just compute our JDN and then use the (simple to derive)
554 // formula: weekday = (JDN + 1.5) % 7
555 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
558 void wxDateTime::Tm::AddMonths(int monDiff
)
560 // normalize the months field
561 while ( monDiff
< -mon
)
565 monDiff
+= MONTHS_IN_YEAR
;
568 while ( monDiff
+ mon
>= MONTHS_IN_YEAR
)
572 monDiff
-= MONTHS_IN_YEAR
;
575 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
577 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
579 // NB: we don't check here that the resulting date is valid, this function
580 // is private and the caller must check it if needed
583 void wxDateTime::Tm::AddDays(int dayDiff
)
585 // normalize the days field
586 while ( dayDiff
+ mday
< 1 )
590 dayDiff
+= GetNumOfDaysInMonth(year
, mon
);
594 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
596 mday
-= GetNumOfDaysInMonth(year
, mon
);
601 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
605 // ----------------------------------------------------------------------------
607 // ----------------------------------------------------------------------------
609 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
613 case wxDateTime::Local
:
614 // get the offset from C RTL: it returns the difference GMT-local
615 // while we want to have the offset _from_ GMT, hence the '-'
616 m_offset
= -GetTimeZone();
619 case wxDateTime::GMT_12
:
620 case wxDateTime::GMT_11
:
621 case wxDateTime::GMT_10
:
622 case wxDateTime::GMT_9
:
623 case wxDateTime::GMT_8
:
624 case wxDateTime::GMT_7
:
625 case wxDateTime::GMT_6
:
626 case wxDateTime::GMT_5
:
627 case wxDateTime::GMT_4
:
628 case wxDateTime::GMT_3
:
629 case wxDateTime::GMT_2
:
630 case wxDateTime::GMT_1
:
631 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
634 case wxDateTime::GMT0
:
635 case wxDateTime::GMT1
:
636 case wxDateTime::GMT2
:
637 case wxDateTime::GMT3
:
638 case wxDateTime::GMT4
:
639 case wxDateTime::GMT5
:
640 case wxDateTime::GMT6
:
641 case wxDateTime::GMT7
:
642 case wxDateTime::GMT8
:
643 case wxDateTime::GMT9
:
644 case wxDateTime::GMT10
:
645 case wxDateTime::GMT11
:
646 case wxDateTime::GMT12
:
647 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
650 case wxDateTime::A_CST
:
651 // Central Standard Time in use in Australia = UTC + 9.5
652 m_offset
= 60l*(9*60 + 30);
656 wxFAIL_MSG( _T("unknown time zone") );
660 // ----------------------------------------------------------------------------
662 // ----------------------------------------------------------------------------
665 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
667 if ( year
== Inv_Year
)
668 year
= GetCurrentYear();
670 if ( cal
== Gregorian
)
672 // in Gregorian calendar leap years are those divisible by 4 except
673 // those divisible by 100 unless they're also divisible by 400
674 // (in some countries, like Russia and Greece, additional corrections
675 // exist, but they won't manifest themselves until 2700)
676 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
678 else if ( cal
== Julian
)
680 // in Julian calendar the rule is simpler
681 return year
% 4 == 0;
685 wxFAIL_MSG(_T("unknown calendar"));
692 int wxDateTime::GetCentury(int year
)
694 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
698 int wxDateTime::ConvertYearToBC(int year
)
701 return year
> 0 ? year
: year
- 1;
705 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
710 return Now().GetYear();
713 wxFAIL_MSG(_T("TODO"));
717 wxFAIL_MSG(_T("unsupported calendar"));
725 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
730 return Now().GetMonth();
733 wxFAIL_MSG(_T("TODO"));
737 wxFAIL_MSG(_T("unsupported calendar"));
745 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
747 if ( year
== Inv_Year
)
749 // take the current year if none given
750 year
= GetCurrentYear();
757 return IsLeapYear(year
) ? 366 : 365;
760 wxFAIL_MSG(_T("unsupported calendar"));
768 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
770 wxDateTime::Calendar cal
)
772 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
774 if ( cal
== Gregorian
|| cal
== Julian
)
776 if ( year
== Inv_Year
)
778 // take the current year if none given
779 year
= GetCurrentYear();
782 return GetNumOfDaysInMonth(year
, month
);
786 wxFAIL_MSG(_T("unsupported calendar"));
793 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
,
794 wxDateTime::NameFlags flags
)
796 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
798 // notice that we must set all the fields to avoid confusing libc (GNU one
799 // gets confused to a crash if we don't do this)
804 return CallStrftime(flags
== Name_Abbr
? _T("%b") : _T("%B"), &tm
);
808 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
,
809 wxDateTime::NameFlags flags
)
811 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
813 // take some arbitrary Sunday
820 // and offset it by the number of days needed to get the correct wday
823 // call mktime() to normalize it...
826 // ... and call strftime()
827 return CallStrftime(flags
== Name_Abbr
? _T("%a") : _T("%A"), &tm
);
831 void wxDateTime::GetAmPmStrings(wxString
*am
, wxString
*pm
)
837 *am
= CallStrftime(_T("%p"), &tm
);
842 *pm
= CallStrftime(_T("%p"), &tm
);
846 // ----------------------------------------------------------------------------
847 // Country stuff: date calculations depend on the country (DST, work days,
848 // ...), so we need to know which rules to follow.
849 // ----------------------------------------------------------------------------
852 wxDateTime::Country
wxDateTime::GetCountry()
854 // TODO use LOCALE_ICOUNTRY setting under Win32
856 if ( ms_country
== Country_Unknown
)
858 // try to guess from the time zone name
859 time_t t
= time(NULL
);
860 struct tm
*tm
= localtime(&t
);
862 wxString tz
= CallStrftime(_T("%Z"), tm
);
863 if ( tz
== _T("WET") || tz
== _T("WEST") )
867 else if ( tz
== _T("CET") || tz
== _T("CEST") )
869 ms_country
= Country_EEC
;
871 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
875 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
876 tz
== _T("EST") || tz
== _T("EDT") ||
877 tz
== _T("CST") || tz
== _T("CDT") ||
878 tz
== _T("MST") || tz
== _T("MDT") ||
879 tz
== _T("PST") || tz
== _T("PDT") )
885 // well, choose a default one
894 void wxDateTime::SetCountry(wxDateTime::Country country
)
896 ms_country
= country
;
900 bool wxDateTime::IsWestEuropeanCountry(Country country
)
902 if ( country
== Country_Default
)
904 country
= GetCountry();
907 return (Country_WesternEurope_Start
<= country
) &&
908 (country
<= Country_WesternEurope_End
);
911 // ----------------------------------------------------------------------------
912 // DST calculations: we use 3 different rules for the West European countries,
913 // USA and for the rest of the world. This is undoubtedly false for many
914 // countries, but I lack the necessary info (and the time to gather it),
915 // please add the other rules here!
916 // ----------------------------------------------------------------------------
919 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
921 if ( year
== Inv_Year
)
923 // take the current year if none given
924 year
= GetCurrentYear();
927 if ( country
== Country_Default
)
929 country
= GetCountry();
936 // DST was first observed in the US and UK during WWI, reused
937 // during WWII and used again since 1966
938 return year
>= 1966 ||
939 (year
>= 1942 && year
<= 1945) ||
940 (year
== 1918 || year
== 1919);
943 // assume that it started after WWII
949 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
951 if ( year
== Inv_Year
)
953 // take the current year if none given
954 year
= GetCurrentYear();
957 if ( country
== Country_Default
)
959 country
= GetCountry();
962 if ( !IsDSTApplicable(year
, country
) )
964 return wxInvalidDateTime
;
969 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
971 // DST begins at 1 a.m. GMT on the last Sunday of March
972 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
975 wxFAIL_MSG( _T("no last Sunday in March?") );
978 dt
+= wxTimeSpan::Hours(1);
980 // disable DST tests because it could result in an infinite recursion!
983 else switch ( country
)
990 // don't know for sure - assume it was in effect all year
995 dt
.Set(1, Jan
, year
);
999 // DST was installed Feb 2, 1942 by the Congress
1000 dt
.Set(2, Feb
, year
);
1003 // Oil embargo changed the DST period in the US
1005 dt
.Set(6, Jan
, 1974);
1009 dt
.Set(23, Feb
, 1975);
1013 // before 1986, DST begun on the last Sunday of April, but
1014 // in 1986 Reagan changed it to begin at 2 a.m. of the
1015 // first Sunday in April
1018 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
1021 wxFAIL_MSG( _T("no first Sunday in April?") );
1026 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
1029 wxFAIL_MSG( _T("no first Sunday in April?") );
1033 dt
+= wxTimeSpan::Hours(2);
1035 // TODO what about timezone??
1041 // assume Mar 30 as the start of the DST for the rest of the world
1042 // - totally bogus, of course
1043 dt
.Set(30, Mar
, year
);
1050 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
1052 if ( year
== Inv_Year
)
1054 // take the current year if none given
1055 year
= GetCurrentYear();
1058 if ( country
== Country_Default
)
1060 country
= GetCountry();
1063 if ( !IsDSTApplicable(year
, country
) )
1065 return wxInvalidDateTime
;
1070 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
1072 // DST ends at 1 a.m. GMT on the last Sunday of October
1073 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1075 // weirder and weirder...
1076 wxFAIL_MSG( _T("no last Sunday in October?") );
1079 dt
+= wxTimeSpan::Hours(1);
1081 // disable DST tests because it could result in an infinite recursion!
1084 else switch ( country
)
1091 // don't know for sure - assume it was in effect all year
1095 dt
.Set(31, Dec
, year
);
1099 // the time was reset after the end of the WWII
1100 dt
.Set(30, Sep
, year
);
1104 // DST ends at 2 a.m. on the last Sunday of October
1105 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
1107 // weirder and weirder...
1108 wxFAIL_MSG( _T("no last Sunday in October?") );
1111 dt
+= wxTimeSpan::Hours(2);
1113 // TODO what about timezone??
1118 // assume October 26th as the end of the DST - totally bogus too
1119 dt
.Set(26, Oct
, year
);
1125 // ----------------------------------------------------------------------------
1126 // constructors and assignment operators
1127 // ----------------------------------------------------------------------------
1129 // return the current time with ms precision
1130 /* static */ wxDateTime
wxDateTime::UNow()
1132 return wxDateTime(wxGetLocalTimeMillis());
1135 // the values in the tm structure contain the local time
1136 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
1139 time_t timet
= mktime(&tm2
);
1141 if ( timet
== (time_t)-1 )
1143 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
1144 // less than timezone - try to make it work for this case
1145 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
1147 // add timezone to make sure that date is in range
1148 tm2
.tm_sec
-= GetTimeZone();
1150 timet
= mktime(&tm2
);
1151 if ( timet
!= (time_t)-1 )
1153 timet
+= GetTimeZone();
1159 wxFAIL_MSG( _T("mktime() failed") );
1161 *this = wxInvalidDateTime
;
1171 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
1172 wxDateTime_t minute
,
1173 wxDateTime_t second
,
1174 wxDateTime_t millisec
)
1176 // we allow seconds to be 61 to account for the leap seconds, even if we
1177 // don't use them really
1178 wxDATETIME_CHECK( hour
< 24 &&
1182 _T("Invalid time in wxDateTime::Set()") );
1184 // get the current date from system
1185 struct tm
*tm
= GetTmNow();
1187 wxDATETIME_CHECK( tm
, _T("localtime() failed") );
1191 tm
->tm_min
= minute
;
1192 tm
->tm_sec
= second
;
1196 // and finally adjust milliseconds
1197 return SetMillisecond(millisec
);
1200 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
1204 wxDateTime_t minute
,
1205 wxDateTime_t second
,
1206 wxDateTime_t millisec
)
1208 wxDATETIME_CHECK( hour
< 24 &&
1212 _T("Invalid time in wxDateTime::Set()") );
1214 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1216 wxDATETIME_CHECK( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
1217 _T("Invalid date in wxDateTime::Set()") );
1219 // the range of time_t type (inclusive)
1220 static const int yearMinInRange
= 1970;
1221 static const int yearMaxInRange
= 2037;
1223 // test only the year instead of testing for the exact end of the Unix
1224 // time_t range - it doesn't bring anything to do more precise checks
1225 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
1227 // use the standard library version if the date is in range - this is
1228 // probably more efficient than our code
1230 tm
.tm_year
= year
- 1900;
1236 tm
.tm_isdst
= -1; // mktime() will guess it
1240 // and finally adjust milliseconds
1241 return SetMillisecond(millisec
);
1245 // do time calculations ourselves: we want to calculate the number of
1246 // milliseconds between the given date and the epoch
1248 // get the JDN for the midnight of this day
1249 m_time
= GetTruncatedJDN(day
, month
, year
);
1250 m_time
-= EPOCH_JDN
;
1251 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1253 // JDN corresponds to GMT, we take localtime
1254 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1260 wxDateTime
& wxDateTime::Set(double jdn
)
1262 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1264 jdn
-= EPOCH_JDN
+ 0.5;
1266 jdn
*= MILLISECONDS_PER_DAY
;
1273 wxDateTime
& wxDateTime::ResetTime()
1277 if ( tm
.hour
|| tm
.min
|| tm
.sec
|| tm
.msec
)
1290 // ----------------------------------------------------------------------------
1291 // DOS Date and Time Format functions
1292 // ----------------------------------------------------------------------------
1293 // the dos date and time value is an unsigned 32 bit value in the format:
1294 // YYYYYYYMMMMDDDDDhhhhhmmmmmmsssss
1296 // Y = year offset from 1980 (0-127)
1298 // D = day of month (1-31)
1300 // m = minute (0-59)
1301 // s = bisecond (0-29) each bisecond indicates two seconds
1302 // ----------------------------------------------------------------------------
1304 wxDateTime
& wxDateTime::SetFromDOS(unsigned long ddt
)
1308 long year
= ddt
& 0xFE000000;
1313 long month
= ddt
& 0x1E00000;
1318 long day
= ddt
& 0x1F0000;
1322 long hour
= ddt
& 0xF800;
1326 long minute
= ddt
& 0x7E0;
1330 long second
= ddt
& 0x1F;
1331 tm
.tm_sec
= second
* 2;
1333 return Set(mktime(&tm
));
1336 unsigned long wxDateTime::GetAsDOS() const
1339 time_t ticks
= GetTicks();
1340 struct tm
*tm
= localtime(&ticks
);
1342 long year
= tm
->tm_year
;
1346 long month
= tm
->tm_mon
;
1350 long day
= tm
->tm_mday
;
1353 long hour
= tm
->tm_hour
;
1356 long minute
= tm
->tm_min
;
1359 long second
= tm
->tm_sec
;
1362 ddt
= year
| month
| day
| hour
| minute
| second
;
1366 // ----------------------------------------------------------------------------
1367 // time_t <-> broken down time conversions
1368 // ----------------------------------------------------------------------------
1370 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1372 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1374 time_t time
= GetTicks();
1375 if ( time
!= (time_t)-1 )
1377 // use C RTL functions
1379 if ( tz
.GetOffset() == -GetTimeZone() )
1381 // we are working with local time
1382 tm
= localtime(&time
);
1384 // should never happen
1385 wxCHECK_MSG( tm
, Tm(), _T("localtime() failed") );
1389 time
+= (time_t)tz
.GetOffset();
1390 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1391 int time2
= (int) time
;
1399 // should never happen
1400 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1404 tm
= (struct tm
*)NULL
;
1410 // adjust the milliseconds
1412 long timeOnly
= (m_time
% MILLISECONDS_PER_DAY
).ToLong();
1413 tm2
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1416 //else: use generic code below
1419 // remember the time and do the calculations with the date only - this
1420 // eliminates rounding errors of the floating point arithmetics
1422 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1424 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1426 // we want to always have positive time and timeMidnight to be really
1427 // the midnight before it
1430 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1433 timeMidnight
-= timeOnly
;
1435 // calculate the Gregorian date from JDN for the midnight of our date:
1436 // this will yield day, month (in 1..12 range) and year
1438 // actually, this is the JDN for the noon of the previous day
1439 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1441 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1443 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1445 // calculate the century
1446 long temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1447 long century
= temp
/ DAYS_PER_400_YEARS
;
1449 // then the year and day of year (1 <= dayOfYear <= 366)
1450 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1451 long year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1452 long dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1454 // and finally the month and day of the month
1455 temp
= dayOfYear
* 5 - 3;
1456 long month
= temp
/ DAYS_PER_5_MONTHS
;
1457 long day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1459 // month is counted from March - convert to normal
1470 // year is offset by 4800
1473 // check that the algorithm gave us something reasonable
1474 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1475 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1477 // construct Tm from these values
1479 tm
.year
= (int)year
;
1480 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1481 tm
.mday
= (wxDateTime_t
)day
;
1482 tm
.msec
= (wxDateTime_t
)(timeOnly
% 1000);
1483 timeOnly
-= tm
.msec
;
1484 timeOnly
/= 1000; // now we have time in seconds
1486 tm
.sec
= (wxDateTime_t
)(timeOnly
% 60);
1488 timeOnly
/= 60; // now we have time in minutes
1490 tm
.min
= (wxDateTime_t
)(timeOnly
% 60);
1493 tm
.hour
= (wxDateTime_t
)(timeOnly
/ 60);
1498 wxDateTime
& wxDateTime::SetYear(int year
)
1500 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1509 wxDateTime
& wxDateTime::SetMonth(Month month
)
1511 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1520 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1522 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1531 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1533 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1542 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1544 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1553 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1555 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1564 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1566 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1568 // we don't need to use GetTm() for this one
1569 m_time
-= m_time
% 1000l;
1570 m_time
+= millisecond
;
1575 // ----------------------------------------------------------------------------
1576 // wxDateTime arithmetics
1577 // ----------------------------------------------------------------------------
1579 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1583 tm
.year
+= diff
.GetYears();
1584 tm
.AddMonths(diff
.GetMonths());
1586 // check that the resulting date is valid
1587 if ( tm
.mday
> GetNumOfDaysInMonth(tm
.year
, tm
.mon
) )
1589 // We suppose that when adding one month to Jan 31 we want to get Feb
1590 // 28 (or 29), i.e. adding a month to the last day of the month should
1591 // give the last day of the next month which is quite logical.
1593 // Unfortunately, there is no logic way to understand what should
1594 // Jan 30 + 1 month be - Feb 28 too or Feb 27 (assuming non leap year)?
1595 // We make it Feb 28 (last day too), but it is highly questionable.
1596 tm
.mday
= GetNumOfDaysInMonth(tm
.year
, tm
.mon
);
1599 tm
.AddDays(diff
.GetTotalDays());
1603 wxASSERT_MSG( IsSameTime(tm
),
1604 _T("Add(wxDateSpan) shouldn't modify time") );
1609 // ----------------------------------------------------------------------------
1610 // Weekday and monthday stuff
1611 // ----------------------------------------------------------------------------
1613 bool wxDateTime::SetToTheWeek(wxDateTime_t numWeek
,
1617 wxASSERT_MSG( numWeek
> 0,
1618 _T("invalid week number: weeks are counted from 1") );
1620 int year
= GetYear();
1622 // Jan 4 always lies in the 1st week of the year
1624 SetToWeekDayInSameWeek(weekday
, flags
) += wxDateSpan::Weeks(numWeek
- 1);
1626 if ( GetYear() != year
)
1628 // oops... numWeek was too big
1635 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1638 // take the current month/year if none specified
1639 if ( year
== Inv_Year
)
1641 if ( month
== Inv_Month
)
1644 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1647 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
, WeekFlags flags
)
1649 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1651 int wdayThis
= GetWeekDay();
1652 if ( weekday
== wdayThis
)
1658 if ( flags
== Default_First
)
1660 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1663 // the logic below based on comparing weekday and wdayThis works if Sun (0)
1664 // is the first day in the week, but breaks down for Monday_First case so
1665 // we adjust the week days in this case
1666 if( flags
== Monday_First
)
1668 if ( wdayThis
== Sun
)
1671 //else: Sunday_First, nothing to do
1673 // go forward or back in time to the day we want
1674 if ( weekday
< wdayThis
)
1676 return Subtract(wxDateSpan::Days(wdayThis
- weekday
));
1678 else // weekday > wdayThis
1680 return Add(wxDateSpan::Days(weekday
- wdayThis
));
1684 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1686 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1689 WeekDay wdayThis
= GetWeekDay();
1690 if ( weekday
== wdayThis
)
1695 else if ( weekday
< wdayThis
)
1697 // need to advance a week
1698 diff
= 7 - (wdayThis
- weekday
);
1700 else // weekday > wdayThis
1702 diff
= weekday
- wdayThis
;
1705 return Add(wxDateSpan::Days(diff
));
1708 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1710 wxDATETIME_CHECK( weekday
!= Inv_WeekDay
, _T("invalid weekday") );
1713 WeekDay wdayThis
= GetWeekDay();
1714 if ( weekday
== wdayThis
)
1719 else if ( weekday
> wdayThis
)
1721 // need to go to previous week
1722 diff
= 7 - (weekday
- wdayThis
);
1724 else // weekday < wdayThis
1726 diff
= wdayThis
- weekday
;
1729 return Subtract(wxDateSpan::Days(diff
));
1732 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1737 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1739 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1740 // anyhow in such case - but may be should still give an assert for it?
1742 // take the current month/year if none specified
1743 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1747 // TODO this probably could be optimised somehow...
1751 // get the first day of the month
1752 dt
.Set(1, month
, year
);
1755 WeekDay wdayFirst
= dt
.GetWeekDay();
1757 // go to the first weekday of the month
1758 int diff
= weekday
- wdayFirst
;
1762 // add advance n-1 weeks more
1765 dt
+= wxDateSpan::Days(diff
);
1767 else // count from the end of the month
1769 // get the last day of the month
1770 dt
.SetToLastMonthDay(month
, year
);
1773 WeekDay wdayLast
= dt
.GetWeekDay();
1775 // go to the last weekday of the month
1776 int diff
= wdayLast
- weekday
;
1780 // and rewind n-1 weeks from there
1783 dt
-= wxDateSpan::Days(diff
);
1786 // check that it is still in the same month
1787 if ( dt
.GetMonth() == month
)
1795 // no such day in this month
1800 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1804 return gs_cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1807 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(wxDateTime::WeekFlags flags
,
1808 const TimeZone
& tz
) const
1810 if ( flags
== Default_First
)
1812 flags
= GetCountry() == USA
? Sunday_First
: Monday_First
;
1815 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1818 WeekDay wd
= GetWeekDay(tz
);
1819 if ( flags
== Sunday_First
)
1821 week
= (nDayInYear
- wd
+ 7) / 7;
1825 // have to shift the week days values
1826 week
= (nDayInYear
- (wd
- 1 + 7) % 7 + 7) / 7;
1829 // FIXME some more elegant way??
1830 WeekDay wdYearStart
= wxDateTime(1, Jan
, GetYear()).GetWeekDay();
1831 if ( wdYearStart
== Wed
|| wdYearStart
== Thu
)
1839 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfMonth(wxDateTime::WeekFlags flags
,
1840 const TimeZone
& tz
) const
1843 wxDateTime dtMonthStart
= wxDateTime(1, tm
.mon
, tm
.year
);
1844 int nWeek
= GetWeekOfYear(flags
) - dtMonthStart
.GetWeekOfYear(flags
) + 1;
1847 // this may happen for January when Jan, 1 is the last week of the
1849 nWeek
+= IsLeapYear(tm
.year
- 1) ? 53 : 52;
1852 return (wxDateTime::wxDateTime_t
)nWeek
;
1855 wxDateTime
& wxDateTime::SetToYearDay(wxDateTime::wxDateTime_t yday
)
1857 int year
= GetYear();
1858 wxDATETIME_CHECK( (0 < yday
) && (yday
<= GetNumberOfDays(year
)),
1859 _T("invalid year day") );
1861 bool isLeap
= IsLeapYear(year
);
1862 for ( Month mon
= Jan
; mon
< Inv_Month
; wxNextMonth(mon
) )
1864 // for Dec, we can't compare with gs_cumulatedDays[mon + 1], but we
1865 // don't need it neither - because of the CHECK above we know that
1866 // yday lies in December then
1867 if ( (mon
== Dec
) || (yday
< gs_cumulatedDays
[isLeap
][mon
+ 1]) )
1869 Set(yday
- gs_cumulatedDays
[isLeap
][mon
], mon
, year
);
1878 // ----------------------------------------------------------------------------
1879 // Julian day number conversion and related stuff
1880 // ----------------------------------------------------------------------------
1882 double wxDateTime::GetJulianDayNumber() const
1884 // JDN are always expressed for the GMT dates
1885 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1887 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1889 // add the part GetTruncatedJDN() neglected
1892 // and now add the time: 86400 sec = 1 JDN
1893 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1896 double wxDateTime::GetRataDie() const
1898 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1899 return GetJulianDayNumber() - 1721119.5 - 306;
1902 // ----------------------------------------------------------------------------
1903 // timezone and DST stuff
1904 // ----------------------------------------------------------------------------
1906 int wxDateTime::IsDST(wxDateTime::Country country
) const
1908 wxCHECK_MSG( country
== Country_Default
, -1,
1909 _T("country support not implemented") );
1911 // use the C RTL for the dates in the standard range
1912 time_t timet
= GetTicks();
1913 if ( timet
!= (time_t)-1 )
1915 tm
*tm
= localtime(&timet
);
1917 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1919 return tm
->tm_isdst
;
1923 int year
= GetYear();
1925 if ( !IsDSTApplicable(year
, country
) )
1927 // no DST time in this year in this country
1931 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1935 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
, bool noDST
)
1937 long secDiff
= GetTimeZone() + tz
.GetOffset();
1939 // we need to know whether DST is or not in effect for this date unless
1940 // the test disabled by the caller
1941 if ( !noDST
&& (IsDST() == 1) )
1943 // FIXME we assume that the DST is always shifted by 1 hour
1947 return Subtract(wxTimeSpan::Seconds(secDiff
));
1950 // ----------------------------------------------------------------------------
1951 // wxDateTime to/from text representations
1952 // ----------------------------------------------------------------------------
1954 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1956 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1958 // we have to use our own implementation if the date is out of range of
1959 // strftime() or if we use non standard specificators
1960 time_t time
= GetTicks();
1961 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
1965 if ( tz
.GetOffset() == -GetTimeZone() )
1967 // we are working with local time
1968 tm
= localtime(&time
);
1970 // should never happen
1971 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1975 time
+= (int)tz
.GetOffset();
1977 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
1978 int time2
= (int) time
;
1986 // should never happen
1987 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1991 tm
= (struct tm
*)NULL
;
1997 return CallStrftime(format
, tm
);
1999 //else: use generic code below
2002 // we only parse ANSI C format specifications here, no POSIX 2
2003 // complications, no GNU extensions but we do add support for a "%l" format
2004 // specifier allowing to get the number of milliseconds
2007 // used for calls to strftime() when we only deal with time
2008 struct tm tmTimeOnly
;
2009 tmTimeOnly
.tm_hour
= tm
.hour
;
2010 tmTimeOnly
.tm_min
= tm
.min
;
2011 tmTimeOnly
.tm_sec
= tm
.sec
;
2012 tmTimeOnly
.tm_wday
= 0;
2013 tmTimeOnly
.tm_yday
= 0;
2014 tmTimeOnly
.tm_mday
= 1; // any date will do
2015 tmTimeOnly
.tm_mon
= 0;
2016 tmTimeOnly
.tm_year
= 76;
2017 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
2019 wxString tmp
, res
, fmt
;
2020 for ( const wxChar
*p
= format
; *p
; p
++ )
2022 if ( *p
!= _T('%') )
2030 // set the default format
2033 case _T('Y'): // year has 4 digits
2037 case _T('j'): // day of year has 3 digits
2038 case _T('l'): // milliseconds have 3 digits
2042 case _T('w'): // week day as number has only one
2047 // it's either another valid format specifier in which case
2048 // the format is "%02d" (for all the rest) or we have the
2049 // field width preceding the format in which case it will
2050 // override the default format anyhow
2054 bool restart
= TRUE
;
2059 // start of the format specification
2062 case _T('a'): // a weekday name
2064 // second parameter should be TRUE for abbreviated names
2065 res
+= GetWeekDayName(tm
.GetWeekDay(),
2066 *p
== _T('a') ? Name_Abbr
: Name_Full
);
2069 case _T('b'): // a month name
2071 res
+= GetMonthName(tm
.mon
,
2072 *p
== _T('b') ? Name_Abbr
: Name_Full
);
2075 case _T('c'): // locale default date and time representation
2076 case _T('x'): // locale default date representation
2078 // the problem: there is no way to know what do these format
2079 // specifications correspond to for the current locale.
2081 // the solution: use a hack and still use strftime(): first
2082 // find the YEAR which is a year in the strftime() range (1970
2083 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
2084 // of the real year. Then make a copy of the format and
2085 // replace all occurences of YEAR in it with some unique
2086 // string not appearing anywhere else in it, then use
2087 // strftime() to format the date in year YEAR and then replace
2088 // YEAR back by the real year and the unique replacement
2089 // string back with YEAR. Notice that "all occurences of YEAR"
2090 // means all occurences of 4 digit as well as 2 digit form!
2092 // the bugs: we assume that neither of %c nor %x contains any
2093 // fields which may change between the YEAR and real year. For
2094 // example, the week number (%U, %W) and the day number (%j)
2095 // will change if one of these years is leap and the other one
2098 // find the YEAR: normally, for any year X, Jan 1 or the
2099 // year X + 28 is the same weekday as Jan 1 of X (because
2100 // the weekday advances by 1 for each normal X and by 2
2101 // for each leap X, hence by 5 every 4 years or by 35
2102 // which is 0 mod 7 every 28 years) but this rule breaks
2103 // down if there are years between X and Y which are
2104 // divisible by 4 but not leap (i.e. divisible by 100 but
2105 // not 400), hence the correction.
2107 int yearReal
= GetYear(tz
);
2108 int mod28
= yearReal
% 28;
2110 // be careful to not go too far - we risk to leave the
2115 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
2119 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
2122 int nCentury
= year
/ 100,
2123 nCenturyReal
= yearReal
/ 100;
2125 // need to adjust for the years divisble by 400 which are
2126 // not leap but are counted like leap ones if we just take
2127 // the number of centuries in between for nLostWeekDays
2128 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
2129 (nCentury
/ 4 - nCenturyReal
/ 4);
2131 // we have to gain back the "lost" weekdays: note that the
2132 // effect of this loop is to not do anything to
2133 // nLostWeekDays (which we won't use any more), but to
2134 // (indirectly) set the year correctly
2135 while ( (nLostWeekDays
% 7) != 0 )
2137 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
2140 // at any rate, we couldn't go further than 1988 + 9 + 28!
2141 wxASSERT_MSG( year
< 2030,
2142 _T("logic error in wxDateTime::Format") );
2144 wxString strYear
, strYear2
;
2145 strYear
.Printf(_T("%d"), year
);
2146 strYear2
.Printf(_T("%d"), year
% 100);
2148 // find two strings not occuring in format (this is surely
2149 // not optimal way of doing it... improvements welcome!)
2150 wxString fmt
= format
;
2151 wxString replacement
= (wxChar
)-1;
2152 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2154 replacement
<< (wxChar
)-1;
2157 wxString replacement2
= (wxChar
)-2;
2158 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
2160 replacement
<< (wxChar
)-2;
2163 // replace all occurences of year with it
2164 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
2166 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
2168 // use strftime() to format the same date but in supported
2171 // NB: we assume that strftime() doesn't check for the
2172 // date validity and will happily format the date
2173 // corresponding to Feb 29 of a non leap year (which
2174 // may happen if yearReal was leap and year is not)
2175 struct tm tmAdjusted
;
2177 tmAdjusted
.tm_hour
= tm
.hour
;
2178 tmAdjusted
.tm_min
= tm
.min
;
2179 tmAdjusted
.tm_sec
= tm
.sec
;
2180 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
2181 tmAdjusted
.tm_yday
= GetDayOfYear();
2182 tmAdjusted
.tm_mday
= tm
.mday
;
2183 tmAdjusted
.tm_mon
= tm
.mon
;
2184 tmAdjusted
.tm_year
= year
- 1900;
2185 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
2186 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
2190 // now replace the occurence of 1999 with the real year
2191 wxString strYearReal
, strYearReal2
;
2192 strYearReal
.Printf(_T("%04d"), yearReal
);
2193 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
2194 str
.Replace(strYear
, strYearReal
);
2195 str
.Replace(strYear2
, strYearReal2
);
2197 // and replace back all occurences of replacement string
2200 str
.Replace(replacement2
, strYear2
);
2201 str
.Replace(replacement
, strYear
);
2208 case _T('d'): // day of a month (01-31)
2209 res
+= wxString::Format(fmt
, tm
.mday
);
2212 case _T('H'): // hour in 24h format (00-23)
2213 res
+= wxString::Format(fmt
, tm
.hour
);
2216 case _T('I'): // hour in 12h format (01-12)
2218 // 24h -> 12h, 0h -> 12h too
2219 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
2220 : tm
.hour
? tm
.hour
: 12;
2221 res
+= wxString::Format(fmt
, hour12
);
2225 case _T('j'): // day of the year
2226 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
2229 case _T('l'): // milliseconds (NOT STANDARD)
2230 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
2233 case _T('m'): // month as a number (01-12)
2234 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
2237 case _T('M'): // minute as a decimal number (00-59)
2238 res
+= wxString::Format(fmt
, tm
.min
);
2241 case _T('p'): // AM or PM string
2242 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
2245 case _T('S'): // second as a decimal number (00-61)
2246 res
+= wxString::Format(fmt
, tm
.sec
);
2249 case _T('U'): // week number in the year (Sunday 1st week day)
2250 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
2253 case _T('W'): // week number in the year (Monday 1st week day)
2254 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
2257 case _T('w'): // weekday as a number (0-6), Sunday = 0
2258 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
2261 // case _T('x'): -- handled with "%c"
2263 case _T('X'): // locale default time representation
2264 // just use strftime() to format the time for us
2265 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
2268 case _T('y'): // year without century (00-99)
2269 res
+= wxString::Format(fmt
, tm
.year
% 100);
2272 case _T('Y'): // year with century
2273 res
+= wxString::Format(fmt
, tm
.year
);
2276 case _T('Z'): // timezone name
2277 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
2281 // is it the format width?
2283 while ( *p
== _T('-') || *p
== _T('+') ||
2284 *p
== _T(' ') || wxIsdigit(*p
) )
2289 if ( !fmt
.IsEmpty() )
2291 // we've only got the flags and width so far in fmt
2292 fmt
.Prepend(_T('%'));
2293 fmt
.Append(_T('d'));
2300 // no, it wasn't the width
2301 wxFAIL_MSG(_T("unknown format specificator"));
2303 // fall through and just copy it nevertheless
2305 case _T('%'): // a percent sign
2309 case 0: // the end of string
2310 wxFAIL_MSG(_T("missing format at the end of string"));
2312 // just put the '%' which was the last char in format
2322 // this function parses a string in (strict) RFC 822 format: see the section 5
2323 // of the RFC for the detailed description, but briefly it's something of the
2324 // form "Sat, 18 Dec 1999 00:48:30 +0100"
2326 // this function is "strict" by design - it must reject anything except true
2327 // RFC822 time specs.
2329 // TODO a great candidate for using reg exps
2330 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
2332 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2334 const wxChar
*p
= date
;
2335 const wxChar
*comma
= wxStrchr(p
, _T(','));
2338 // the part before comma is the weekday
2340 // skip it for now - we don't use but might check that it really
2341 // corresponds to the specfied date
2344 if ( *p
!= _T(' ') )
2346 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
2348 return (wxChar
*)NULL
;
2354 // the following 1 or 2 digits are the day number
2355 if ( !wxIsdigit(*p
) )
2357 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
2359 return (wxChar
*)NULL
;
2362 wxDateTime_t day
= *p
++ - _T('0');
2363 if ( wxIsdigit(*p
) )
2366 day
+= *p
++ - _T('0');
2369 if ( *p
++ != _T(' ') )
2371 return (wxChar
*)NULL
;
2374 // the following 3 letters specify the month
2375 wxString
monName(p
, 3);
2377 if ( monName
== _T("Jan") )
2379 else if ( monName
== _T("Feb") )
2381 else if ( monName
== _T("Mar") )
2383 else if ( monName
== _T("Apr") )
2385 else if ( monName
== _T("May") )
2387 else if ( monName
== _T("Jun") )
2389 else if ( monName
== _T("Jul") )
2391 else if ( monName
== _T("Aug") )
2393 else if ( monName
== _T("Sep") )
2395 else if ( monName
== _T("Oct") )
2397 else if ( monName
== _T("Nov") )
2399 else if ( monName
== _T("Dec") )
2403 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
2405 return (wxChar
*)NULL
;
2410 if ( *p
++ != _T(' ') )
2412 return (wxChar
*)NULL
;
2416 if ( !wxIsdigit(*p
) )
2419 return (wxChar
*)NULL
;
2422 int year
= *p
++ - _T('0');
2424 if ( !wxIsdigit(*p
) )
2426 // should have at least 2 digits in the year
2427 return (wxChar
*)NULL
;
2431 year
+= *p
++ - _T('0');
2433 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
2434 if ( wxIsdigit(*p
) )
2437 year
+= *p
++ - _T('0');
2439 if ( !wxIsdigit(*p
) )
2441 // no 3 digit years please
2442 return (wxChar
*)NULL
;
2446 year
+= *p
++ - _T('0');
2449 if ( *p
++ != _T(' ') )
2451 return (wxChar
*)NULL
;
2454 // time is in the format hh:mm:ss and seconds are optional
2455 if ( !wxIsdigit(*p
) )
2457 return (wxChar
*)NULL
;
2460 wxDateTime_t hour
= *p
++ - _T('0');
2462 if ( !wxIsdigit(*p
) )
2464 return (wxChar
*)NULL
;
2468 hour
+= *p
++ - _T('0');
2470 if ( *p
++ != _T(':') )
2472 return (wxChar
*)NULL
;
2475 if ( !wxIsdigit(*p
) )
2477 return (wxChar
*)NULL
;
2480 wxDateTime_t min
= *p
++ - _T('0');
2482 if ( !wxIsdigit(*p
) )
2484 return (wxChar
*)NULL
;
2488 min
+= *p
++ - _T('0');
2490 wxDateTime_t sec
= 0;
2491 if ( *p
++ == _T(':') )
2493 if ( !wxIsdigit(*p
) )
2495 return (wxChar
*)NULL
;
2498 sec
= *p
++ - _T('0');
2500 if ( !wxIsdigit(*p
) )
2502 return (wxChar
*)NULL
;
2506 sec
+= *p
++ - _T('0');
2509 if ( *p
++ != _T(' ') )
2511 return (wxChar
*)NULL
;
2514 // and now the interesting part: the timezone
2516 if ( *p
== _T('-') || *p
== _T('+') )
2518 // the explicit offset given: it has the form of hhmm
2519 bool plus
= *p
++ == _T('+');
2521 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2523 return (wxChar
*)NULL
;
2527 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
2531 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
2533 return (wxChar
*)NULL
;
2537 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
2548 // the symbolic timezone given: may be either military timezone or one
2549 // of standard abbreviations
2552 // military: Z = UTC, J unused, A = -1, ..., Y = +12
2553 static const int offsets
[26] =
2555 //A B C D E F G H I J K L M
2556 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
2557 //N O P R Q S T U V W Z Y Z
2558 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
2561 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
2563 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
2565 return (wxChar
*)NULL
;
2568 offset
= offsets
[*p
++ - _T('A')];
2574 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
2576 else if ( tz
== _T("AST") )
2577 offset
= AST
- GMT0
;
2578 else if ( tz
== _T("ADT") )
2579 offset
= ADT
- GMT0
;
2580 else if ( tz
== _T("EST") )
2581 offset
= EST
- GMT0
;
2582 else if ( tz
== _T("EDT") )
2583 offset
= EDT
- GMT0
;
2584 else if ( tz
== _T("CST") )
2585 offset
= CST
- GMT0
;
2586 else if ( tz
== _T("CDT") )
2587 offset
= CDT
- GMT0
;
2588 else if ( tz
== _T("MST") )
2589 offset
= MST
- GMT0
;
2590 else if ( tz
== _T("MDT") )
2591 offset
= MDT
- GMT0
;
2592 else if ( tz
== _T("PST") )
2593 offset
= PST
- GMT0
;
2594 else if ( tz
== _T("PDT") )
2595 offset
= PDT
- GMT0
;
2598 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
2600 return (wxChar
*)NULL
;
2610 // the spec was correct
2611 Set(day
, mon
, year
, hour
, min
, sec
);
2612 MakeTimezone((wxDateTime_t
)(60*offset
));
2617 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
,
2618 const wxChar
*format
,
2619 const wxDateTime
& dateDef
)
2621 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
2622 _T("NULL pointer in wxDateTime::ParseFormat()") );
2627 // what fields have we found?
2628 bool haveWDay
= FALSE
,
2637 bool hourIsIn12hFormat
= FALSE
, // or in 24h one?
2638 isPM
= FALSE
; // AM by default
2640 // and the value of the items we have (init them to get rid of warnings)
2641 wxDateTime_t sec
= 0,
2644 WeekDay wday
= Inv_WeekDay
;
2645 wxDateTime_t yday
= 0,
2647 wxDateTime::Month mon
= Inv_Month
;
2650 const wxChar
*input
= date
;
2651 for ( const wxChar
*fmt
= format
; *fmt
; fmt
++ )
2653 if ( *fmt
!= _T('%') )
2655 if ( wxIsspace(*fmt
) )
2657 // a white space in the format string matches 0 or more white
2658 // spaces in the input
2659 while ( wxIsspace(*input
) )
2666 // any other character (not whitespace, not '%') must be
2667 // matched by itself in the input
2668 if ( *input
++ != *fmt
)
2671 return (wxChar
*)NULL
;
2675 // done with this format char
2679 // start of a format specification
2681 // parse the optional width
2683 while ( isdigit(*++fmt
) )
2686 width
+= *fmt
- _T('0');
2689 // the default widths for the various fields
2694 case _T('Y'): // year has 4 digits
2698 case _T('j'): // day of year has 3 digits
2699 case _T('l'): // milliseconds have 3 digits
2703 case _T('w'): // week day as number has only one
2708 // default for all other fields
2713 // then the format itself
2716 case _T('a'): // a weekday name
2719 int flag
= *fmt
== _T('a') ? Name_Abbr
: Name_Full
;
2720 wday
= GetWeekDayFromName(GetAlphaToken(input
), flag
);
2721 if ( wday
== Inv_WeekDay
)
2724 return (wxChar
*)NULL
;
2730 case _T('b'): // a month name
2733 int flag
= *fmt
== _T('b') ? Name_Abbr
: Name_Full
;
2734 mon
= GetMonthFromName(GetAlphaToken(input
), flag
);
2735 if ( mon
== Inv_Month
)
2738 return (wxChar
*)NULL
;
2744 case _T('c'): // locale default date and time representation
2748 // this is the format which corresponds to ctime() output
2749 // and strptime("%c") should parse it, so try it first
2750 static const wxChar
*fmtCtime
= _T("%a %b %d %H:%M:%S %Y");
2752 const wxChar
*result
= dt
.ParseFormat(input
, fmtCtime
);
2755 result
= dt
.ParseFormat(input
, _T("%x %X"));
2760 result
= dt
.ParseFormat(input
, _T("%X %x"));
2765 // we've tried everything and still no match
2766 return (wxChar
*)NULL
;
2771 haveDay
= haveMon
= haveYear
=
2772 haveHour
= haveMin
= haveSec
= TRUE
;
2786 case _T('d'): // day of a month (01-31)
2787 if ( !GetNumericToken(width
, input
, &num
) ||
2788 (num
> 31) || (num
< 1) )
2791 return (wxChar
*)NULL
;
2794 // we can't check whether the day range is correct yet, will
2795 // do it later - assume ok for now
2797 mday
= (wxDateTime_t
)num
;
2800 case _T('H'): // hour in 24h format (00-23)
2801 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
2804 return (wxChar
*)NULL
;
2808 hour
= (wxDateTime_t
)num
;
2811 case _T('I'): // hour in 12h format (01-12)
2812 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2815 return (wxChar
*)NULL
;
2819 hourIsIn12hFormat
= TRUE
;
2820 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
2823 case _T('j'): // day of the year
2824 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
2827 return (wxChar
*)NULL
;
2831 yday
= (wxDateTime_t
)num
;
2834 case _T('m'): // month as a number (01-12)
2835 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
2838 return (wxChar
*)NULL
;
2842 mon
= (Month
)(num
- 1);
2845 case _T('M'): // minute as a decimal number (00-59)
2846 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
2849 return (wxChar
*)NULL
;
2853 min
= (wxDateTime_t
)num
;
2856 case _T('p'): // AM or PM string
2858 wxString am
, pm
, token
= GetAlphaToken(input
);
2860 GetAmPmStrings(&am
, &pm
);
2861 if ( token
.CmpNoCase(pm
) == 0 )
2865 else if ( token
.CmpNoCase(am
) != 0 )
2868 return (wxChar
*)NULL
;
2873 case _T('r'): // time as %I:%M:%S %p
2876 input
= dt
.ParseFormat(input
, _T("%I:%M:%S %p"));
2880 return (wxChar
*)NULL
;
2883 haveHour
= haveMin
= haveSec
= TRUE
;
2892 case _T('R'): // time as %H:%M
2895 input
= dt
.ParseFormat(input
, _T("%H:%M"));
2899 return (wxChar
*)NULL
;
2902 haveHour
= haveMin
= TRUE
;
2909 case _T('S'): // second as a decimal number (00-61)
2910 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
2913 return (wxChar
*)NULL
;
2917 sec
= (wxDateTime_t
)num
;
2920 case _T('T'): // time as %H:%M:%S
2923 input
= dt
.ParseFormat(input
, _T("%H:%M:%S"));
2927 return (wxChar
*)NULL
;
2930 haveHour
= haveMin
= haveSec
= TRUE
;
2939 case _T('w'): // weekday as a number (0-6), Sunday = 0
2940 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
2943 return (wxChar
*)NULL
;
2947 wday
= (WeekDay
)num
;
2950 case _T('x'): // locale default date representation
2951 #ifdef HAVE_STRPTIME
2952 // try using strptime() -- it may fail even if the input is
2953 // correct but the date is out of range, so we will fall back
2954 // to our generic code anyhow
2958 const wxChar
*result
= CallStrptime(input
, "%x", &tm
);
2963 haveDay
= haveMon
= haveYear
= TRUE
;
2965 year
= 1900 + tm
.tm_year
;
2966 mon
= (Month
)tm
.tm_mon
;
2972 #endif // HAVE_STRPTIME
2974 // TODO query the LOCALE_IDATE setting under Win32
2978 wxString fmtDate
, fmtDateAlt
;
2979 if ( IsWestEuropeanCountry(GetCountry()) ||
2980 GetCountry() == Russia
)
2982 fmtDate
= _T("%d/%m/%y");
2983 fmtDateAlt
= _T("%m/%d/%y");
2987 fmtDate
= _T("%m/%d/%y");
2988 fmtDateAlt
= _T("%d/%m/%y");
2991 const wxChar
*result
= dt
.ParseFormat(input
, fmtDate
);
2995 // ok, be nice and try another one
2996 result
= dt
.ParseFormat(input
, fmtDateAlt
);
3002 return (wxChar
*)NULL
;
3007 haveDay
= haveMon
= haveYear
= TRUE
;
3018 case _T('X'): // locale default time representation
3019 #ifdef HAVE_STRPTIME
3021 // use strptime() to do it for us (FIXME !Unicode friendly)
3023 input
= CallStrptime(input
, "%X", &tm
);
3026 return (wxChar
*)NULL
;
3029 haveHour
= haveMin
= haveSec
= TRUE
;
3035 #else // !HAVE_STRPTIME
3036 // TODO under Win32 we can query the LOCALE_ITIME system
3037 // setting which says whether the default time format is
3040 // try to parse what follows as "%H:%M:%S" and, if this
3041 // fails, as "%I:%M:%S %p" - this should catch the most
3045 const wxChar
*result
= dt
.ParseFormat(input
, _T("%T"));
3048 result
= dt
.ParseFormat(input
, _T("%r"));
3054 return (wxChar
*)NULL
;
3057 haveHour
= haveMin
= haveSec
= TRUE
;
3066 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
3069 case _T('y'): // year without century (00-99)
3070 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
3073 return (wxChar
*)NULL
;
3078 // TODO should have an option for roll over date instead of
3079 // hard coding it here
3080 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
3083 case _T('Y'): // year with century
3084 if ( !GetNumericToken(width
, input
, &num
) )
3087 return (wxChar
*)NULL
;
3091 year
= (wxDateTime_t
)num
;
3094 case _T('Z'): // timezone name
3095 wxFAIL_MSG(_T("TODO"));
3098 case _T('%'): // a percent sign
3099 if ( *input
++ != _T('%') )
3102 return (wxChar
*)NULL
;
3106 case 0: // the end of string
3107 wxFAIL_MSG(_T("unexpected format end"));
3111 default: // not a known format spec
3112 return (wxChar
*)NULL
;
3116 // format matched, try to construct a date from what we have now
3118 if ( dateDef
.IsValid() )
3120 // take this date as default
3121 tmDef
= dateDef
.GetTm();
3123 else if ( IsValid() )
3125 // if this date is valid, don't change it
3130 // no default and this date is invalid - fall back to Today()
3131 tmDef
= Today().GetTm();
3142 // TODO we don't check here that the values are consistent, if both year
3143 // day and month/day were found, we just ignore the year day and we
3144 // also always ignore the week day
3145 if ( haveMon
&& haveDay
)
3147 if ( mday
> GetNumOfDaysInMonth(tm
.year
, mon
) )
3149 wxLogDebug(_T("bad month day in wxDateTime::ParseFormat"));
3151 return (wxChar
*)NULL
;
3157 else if ( haveYDay
)
3159 if ( yday
> GetNumberOfDays(tm
.year
) )
3161 wxLogDebug(_T("bad year day in wxDateTime::ParseFormat"));
3163 return (wxChar
*)NULL
;
3166 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
3173 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
3175 // translate to 24hour format
3178 //else: either already in 24h format or no translation needed
3201 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
3203 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3205 // there is a public domain version of getdate.y, but it only works for
3207 wxFAIL_MSG(_T("TODO"));
3209 return (wxChar
*)NULL
;
3212 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
3214 // this is a simplified version of ParseDateTime() which understands only
3215 // "today" (for wxDate compatibility) and digits only otherwise (and not
3216 // all esoteric constructions ParseDateTime() knows about)
3218 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3220 const wxChar
*p
= date
;
3221 while ( wxIsspace(*p
) )
3224 // some special cases
3228 int dayDiffFromToday
;
3231 { wxTRANSLATE("today"), 0 },
3232 { wxTRANSLATE("yesterday"), -1 },
3233 { wxTRANSLATE("tomorrow"), 1 },
3236 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
3238 wxString date
= wxGetTranslation(literalDates
[n
].str
);
3239 size_t len
= date
.length();
3240 if ( wxStrlen(p
) >= len
&& (wxString(p
, len
).CmpNoCase(date
) == 0) )
3242 // nothing can follow this, so stop here
3245 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
3247 if ( dayDiffFromToday
)
3249 *this += wxDateSpan::Days(dayDiffFromToday
);
3256 // We try to guess what we have here: for each new (numeric) token, we
3257 // determine if it can be a month, day or a year. Of course, there is an
3258 // ambiguity as some numbers may be days as well as months, so we also
3259 // have the ability to back track.
3262 bool haveDay
= FALSE
, // the months day?
3263 haveWDay
= FALSE
, // the day of week?
3264 haveMon
= FALSE
, // the month?
3265 haveYear
= FALSE
; // the year?
3267 // and the value of the items we have (init them to get rid of warnings)
3268 WeekDay wday
= Inv_WeekDay
;
3269 wxDateTime_t day
= 0;
3270 wxDateTime::Month mon
= Inv_Month
;
3273 // tokenize the string
3275 static const wxChar
*dateDelimiters
= _T(".,/-\t\r\n ");
3276 wxStringTokenizer
tok(p
, dateDelimiters
);
3277 while ( tok
.HasMoreTokens() )
3279 wxString token
= tok
.GetNextToken();
3285 if ( token
.ToULong(&val
) )
3287 // guess what this number is
3293 if ( !haveMon
&& val
> 0 && val
<= 12 )
3295 // assume it is month
3298 else // not the month
3300 wxDateTime_t maxDays
= haveMon
3301 ? GetNumOfDaysInMonth(haveYear
? year
: Inv_Year
, mon
)
3305 if ( (val
== 0) || (val
> (unsigned long)maxDays
) ) // cast to shut up compiler warning in BCC
3322 year
= (wxDateTime_t
)val
;
3331 day
= (wxDateTime_t
)val
;
3337 mon
= (Month
)(val
- 1);
3340 else // not a number
3342 // be careful not to overwrite the current mon value
3343 Month mon2
= GetMonthFromName(token
, Name_Full
| Name_Abbr
);
3344 if ( mon2
!= Inv_Month
)
3349 // but we already have a month - maybe we guessed wrong?
3352 // no need to check in month range as always < 12, but
3353 // the days are counted from 1 unlike the months
3354 day
= (wxDateTime_t
)mon
+ 1;
3359 // could possible be the year (doesn't the year come
3360 // before the month in the japanese format?) (FIXME)
3369 else // not a valid month name
3371 wday
= GetWeekDayFromName(token
, Name_Full
| Name_Abbr
);
3372 if ( wday
!= Inv_WeekDay
)
3382 else // not a valid weekday name
3385 static const wxChar
*ordinals
[] =
3387 wxTRANSLATE("first"),
3388 wxTRANSLATE("second"),
3389 wxTRANSLATE("third"),
3390 wxTRANSLATE("fourth"),
3391 wxTRANSLATE("fifth"),
3392 wxTRANSLATE("sixth"),
3393 wxTRANSLATE("seventh"),
3394 wxTRANSLATE("eighth"),
3395 wxTRANSLATE("ninth"),
3396 wxTRANSLATE("tenth"),
3397 wxTRANSLATE("eleventh"),
3398 wxTRANSLATE("twelfth"),
3399 wxTRANSLATE("thirteenth"),
3400 wxTRANSLATE("fourteenth"),
3401 wxTRANSLATE("fifteenth"),
3402 wxTRANSLATE("sixteenth"),
3403 wxTRANSLATE("seventeenth"),
3404 wxTRANSLATE("eighteenth"),
3405 wxTRANSLATE("nineteenth"),
3406 wxTRANSLATE("twentieth"),
3407 // that's enough - otherwise we'd have problems with
3408 // composite (or not) ordinals
3412 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
3414 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
3420 if ( n
== WXSIZEOF(ordinals
) )
3422 // stop here - something unknown
3429 // don't try anything here (as in case of numeric day
3430 // above) - the symbolic day spec should always
3431 // precede the month/year
3437 day
= (wxDateTime_t
)(n
+ 1);
3442 nPosCur
= tok
.GetPosition();
3445 // either no more tokens or the scan was stopped by something we couldn't
3446 // parse - in any case, see if we can construct a date from what we have
3447 if ( !haveDay
&& !haveWDay
)
3449 wxLogDebug(_T("ParseDate: no day, no weekday hence no date."));
3451 return (wxChar
*)NULL
;
3454 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
3455 !(haveDay
&& haveMon
&& haveYear
) )
3457 // without adjectives (which we don't support here) the week day only
3458 // makes sense completely separately or with the full date
3459 // specification (what would "Wed 1999" mean?)
3460 return (wxChar
*)NULL
;
3463 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
3465 // may be we have month and day instead of day and year?
3466 if ( haveDay
&& !haveMon
)
3470 // exchange day and month
3471 mon
= (wxDateTime::Month
)(day
- 1);
3473 // we're in the current year then
3475 (unsigned)year
<= GetNumOfDaysInMonth(Inv_Year
, mon
) )
3482 //else: no, can't exchange, leave haveMon == FALSE
3488 // if we give the year, month and day must be given too
3489 wxLogDebug(_T("ParseDate: day and month should be specified if year is."));
3491 return (wxChar
*)NULL
;
3497 mon
= GetCurrentMonth();
3502 year
= GetCurrentYear();
3507 Set(day
, mon
, year
);
3511 // check that it is really the same
3512 if ( GetWeekDay() != wday
)
3514 // inconsistency detected
3515 wxLogDebug(_T("ParseDate: inconsistent day/weekday."));
3517 return (wxChar
*)NULL
;
3525 SetToWeekDayInSameWeek(wday
);
3528 // return the pointer to the first unparsed char
3530 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
3532 // if we couldn't parse the token after the delimiter, put back the
3533 // delimiter as well
3540 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
3542 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
3544 // first try some extra things
3551 { wxTRANSLATE("noon"), 12 },
3552 { wxTRANSLATE("midnight"), 00 },
3556 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
3558 wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
3559 size_t len
= timeString
.length();
3560 if ( timeString
.CmpNoCase(wxString(time
, len
)) == 0 )
3562 // casts required by DigitalMars
3563 Set(stdTimes
[n
].hour
, wxDateTime_t(0), wxDateTime_t(0));
3569 // try all time formats we may think about in the order from longest to
3572 // 12hour with AM/PM?
3573 const wxChar
*result
= ParseFormat(time
, _T("%I:%M:%S %p"));
3577 // normally, it's the same, but why not try it?
3578 result
= ParseFormat(time
, _T("%H:%M:%S"));
3583 // 12hour with AM/PM but without seconds?
3584 result
= ParseFormat(time
, _T("%I:%M %p"));
3590 result
= ParseFormat(time
, _T("%H:%M"));
3595 // just the hour and AM/PM?
3596 result
= ParseFormat(time
, _T("%I %p"));
3602 result
= ParseFormat(time
, _T("%H"));
3607 // parse the standard format: normally it is one of the formats above
3608 // but it may be set to something completely different by the user
3609 result
= ParseFormat(time
, _T("%X"));
3612 // TODO: parse timezones
3617 // ----------------------------------------------------------------------------
3618 // Workdays and holidays support
3619 // ----------------------------------------------------------------------------
3621 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
3623 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
3626 // ============================================================================
3628 // ============================================================================
3630 // this enum is only used in wxTimeSpan::Format() below but we can't declare
3631 // it locally to the method as it provokes an internal compiler error in egcs
3632 // 2.91.60 when building with -O2
3643 // not all strftime(3) format specifiers make sense here because, for example,
3644 // a time span doesn't have a year nor a timezone
3646 // Here are the ones which are supported (all of them are supported by strftime
3648 // %H hour in 24 hour format
3649 // %M minute (00 - 59)
3650 // %S second (00 - 59)
3653 // Also, for MFC CTimeSpan compatibility, we support
3654 // %D number of days
3656 // And, to be better than MFC :-), we also have
3657 // %E number of wEeks
3658 // %l milliseconds (000 - 999)
3659 wxString
wxTimeSpan::Format(const wxChar
*format
) const
3661 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
3664 str
.Alloc(wxStrlen(format
));
3666 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
3668 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
3669 // question is what should ts.Format("%S") do? The code here returns "3273"
3670 // in this case (i.e. the total number of seconds, not just seconds % 60)
3671 // because, for me, this call means "give me entire time interval in
3672 // seconds" and not "give me the seconds part of the time interval"
3674 // If we agree that it should behave like this, it is clear that the
3675 // interpretation of each format specifier depends on the presence of the
3676 // other format specs in the string: if there was "%H" before "%M", we
3677 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
3679 // we remember the most important unit found so far
3680 TimeSpanPart partBiggest
= Part_MSec
;
3682 for ( const wxChar
*pch
= format
; *pch
; pch
++ )
3686 if ( ch
== _T('%') )
3688 // the start of the format specification of the printf() below
3689 wxString fmtPrefix
= _T('%');
3694 ch
= *++pch
; // get the format spec char
3698 wxFAIL_MSG( _T("invalid format character") );
3704 // skip the part below switch
3709 if ( partBiggest
< Part_Day
)
3715 partBiggest
= Part_Day
;
3720 partBiggest
= Part_Week
;
3726 if ( partBiggest
< Part_Hour
)
3732 partBiggest
= Part_Hour
;
3735 fmtPrefix
+= _T("02");
3739 n
= GetMilliseconds().ToLong();
3740 if ( partBiggest
< Part_MSec
)
3744 //else: no need to reset partBiggest to Part_MSec, it is
3745 // the least significant one anyhow
3747 fmtPrefix
+= _T("03");
3752 if ( partBiggest
< Part_Min
)
3758 partBiggest
= Part_Min
;
3761 fmtPrefix
+= _T("02");
3765 n
= GetSeconds().ToLong();
3766 if ( partBiggest
< Part_Sec
)
3772 partBiggest
= Part_Sec
;
3775 fmtPrefix
+= _T("02");
3779 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
3783 // normal character, just copy
3791 // ============================================================================
3792 // wxDateTimeHolidayAuthority and related classes
3793 // ============================================================================
3795 #include "wx/arrimpl.cpp"
3797 WX_DEFINE_OBJARRAY(wxDateTimeArray
);
3799 static int wxCMPFUNC_CONV
3800 wxDateTimeCompareFunc(wxDateTime
**first
, wxDateTime
**second
)
3802 wxDateTime dt1
= **first
,
3805 return dt1
== dt2
? 0 : dt1
< dt2
? -1 : +1;
3808 // ----------------------------------------------------------------------------
3809 // wxDateTimeHolidayAuthority
3810 // ----------------------------------------------------------------------------
3812 wxHolidayAuthoritiesArray
wxDateTimeHolidayAuthority::ms_authorities
;
3815 bool wxDateTimeHolidayAuthority::IsHoliday(const wxDateTime
& dt
)
3817 size_t count
= ms_authorities
.size();
3818 for ( size_t n
= 0; n
< count
; n
++ )
3820 if ( ms_authorities
[n
]->DoIsHoliday(dt
) )
3831 wxDateTimeHolidayAuthority::GetHolidaysInRange(const wxDateTime
& dtStart
,
3832 const wxDateTime
& dtEnd
,
3833 wxDateTimeArray
& holidays
)
3835 wxDateTimeArray hol
;
3839 size_t count
= ms_authorities
.size();
3840 for ( size_t nAuth
= 0; nAuth
< count
; nAuth
++ )
3842 ms_authorities
[nAuth
]->DoGetHolidaysInRange(dtStart
, dtEnd
, hol
);
3844 WX_APPEND_ARRAY(holidays
, hol
);
3847 holidays
.Sort(wxDateTimeCompareFunc
);
3849 return holidays
.size();
3853 void wxDateTimeHolidayAuthority::ClearAllAuthorities()
3855 WX_CLEAR_ARRAY(ms_authorities
);
3859 void wxDateTimeHolidayAuthority::AddAuthority(wxDateTimeHolidayAuthority
*auth
)
3861 ms_authorities
.push_back(auth
);
3864 wxDateTimeHolidayAuthority::~wxDateTimeHolidayAuthority()
3866 // nothing to do here
3869 // ----------------------------------------------------------------------------
3870 // wxDateTimeWorkDays
3871 // ----------------------------------------------------------------------------
3873 bool wxDateTimeWorkDays::DoIsHoliday(const wxDateTime
& dt
) const
3875 wxDateTime::WeekDay wd
= dt
.GetWeekDay();
3877 return (wd
== wxDateTime::Sun
) || (wd
== wxDateTime::Sat
);
3880 size_t wxDateTimeWorkDays::DoGetHolidaysInRange(const wxDateTime
& dtStart
,
3881 const wxDateTime
& dtEnd
,
3882 wxDateTimeArray
& holidays
) const
3884 if ( dtStart
> dtEnd
)
3886 wxFAIL_MSG( _T("invalid date range in GetHolidaysInRange") );
3893 // instead of checking all days, start with the first Sat after dtStart and
3894 // end with the last Sun before dtEnd
3895 wxDateTime dtSatFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sat
),
3896 dtSatLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sat
),
3897 dtSunFirst
= dtStart
.GetNextWeekDay(wxDateTime::Sun
),
3898 dtSunLast
= dtEnd
.GetPrevWeekDay(wxDateTime::Sun
),
3901 for ( dt
= dtSatFirst
; dt
<= dtSatLast
; dt
+= wxDateSpan::Week() )
3906 for ( dt
= dtSunFirst
; dt
<= dtSunLast
; dt
+= wxDateSpan::Week() )
3911 return holidays
.GetCount();
3914 #endif // wxUSE_DATETIME