1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows license
17 ///////////////////////////////////////////////////////////////////////////////
20 * Implementation notes:
22 * 1. the time is stored as a 64bit integer containing the signed number of
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
26 * 2. the range is thus something about 580 million years, but due to current
27 * algorithms limitations, only dates from Nov 24, 4714BC are handled
29 * 3. standard ANSI C functions are used to do time calculations whenever
30 * possible, i.e. when the date is in the range Jan 1, 1970 to 2038
32 * 4. otherwise, the calculations are done by converting the date to/from JDN
33 * first (the range limitation mentioned above comes from here: the
34 * algorithm used by Scott E. Lee's code only works for positive JDNs, more
37 * 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
38 * this moment in local time and may be converted to the object
39 * corresponding to the same date/time in another time zone by using
42 * 6. the conversions to the current (or any other) timezone are done when the
43 * internal time representation is converted to the broken-down one in
47 // ============================================================================
49 // ============================================================================
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
56 #pragma implementation "datetime.h"
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
67 #include "wx/string.h"
72 #include "wx/thread.h"
73 #include "wx/tokenzr.h"
75 #define wxDEFINE_TIME_CONSTANTS
77 #include "wx/datetime.h"
80 #define WX_TIMEZONE timezone
83 // Is this right? Just a guess. (JACS)
85 #define timezone _timezone
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
93 static const int MONTHS_IN_YEAR
= 12;
95 static const int SECONDS_IN_MINUTE
= 60;
97 static const long SECONDS_PER_DAY
= 86400l;
99 static const long MILLISECONDS_PER_DAY
= 86400000l;
101 // this is the integral part of JDN of the midnight of Jan 1, 1970
102 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
103 static const long EPOCH_JDN
= 2440587l;
105 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
106 // reference date for us) is Nov 24, 4714BC
107 static const int JDN_0_YEAR
= -4713;
108 static const int JDN_0_MONTH
= wxDateTime::Nov
;
109 static const int JDN_0_DAY
= 24;
111 // the constants used for JDN calculations
112 static const long JDN_OFFSET
= 32046l;
113 static const long DAYS_PER_5_MONTHS
= 153l;
114 static const long DAYS_PER_4_YEARS
= 1461l;
115 static const long DAYS_PER_400_YEARS
= 146097l;
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // a critical section is needed to protect GetTimeZone() static
122 // variable in MT case
124 wxCriticalSection gs_critsectTimezone
;
125 #endif // wxUSE_THREADS
127 // the symbolic names for date spans
128 wxDateSpan wxYear
= wxDateSpan(1, 0, 0, 0);
129 wxDateSpan wxMonth
= wxDateSpan(0, 1, 0, 0);
130 wxDateSpan wxWeek
= wxDateSpan(0, 0, 1, 0);
131 wxDateSpan wxDay
= wxDateSpan(0, 0, 0, 1);
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 // get the number of days in the given month of the given year
139 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
141 // the number of days in month in Julian/Gregorian calendar: the first line
142 // is for normal years, the second one is for the leap ones
143 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
145 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
146 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
149 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
152 // ensure that the timezone variable is set by calling localtime
153 static int GetTimeZone()
155 // set to TRUE when the timezone is set
156 static bool s_timezoneSet
= FALSE
;
158 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
160 if ( !s_timezoneSet
)
162 // just call localtime() instead of figuring out whether this system
163 // supports tzset(), _tzset() or something else
167 s_timezoneSet
= TRUE
;
170 return (int)WX_TIMEZONE
;
173 // return the integral part of the JDN for the midnight of the given date (to
174 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
175 // noon of the previous day)
176 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
177 wxDateTime::Month mon
,
180 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
182 // check the date validity
184 (year
> JDN_0_YEAR
) ||
185 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
186 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
187 _T("date out of range - can't convert to JDN")
190 // make the year positive to avoid problems with negative numbers division
193 // months are counted from March here
195 if ( mon
>= wxDateTime::Mar
)
205 // now we can simply add all the contributions together
206 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
207 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
208 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
213 // this function is a wrapper around strftime(3)
214 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
217 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
219 // is ti really possible that 1024 is too short?
220 wxFAIL_MSG(_T("strftime() failed"));
223 return wxString(buf
);
226 // if year and/or month have invalid values, replace them with the current ones
227 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
228 wxDateTime::Month
*month
)
230 struct tm
*tmNow
= NULL
;
232 if ( *year
== wxDateTime::Inv_Year
)
234 tmNow
= wxDateTime::GetTmNow();
236 *year
= 1900 + tmNow
->tm_year
;
239 if ( *month
== wxDateTime::Inv_Month
)
242 tmNow
= wxDateTime::GetTmNow();
244 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
251 // return the month if the string is a month name or Inv_Month otherwise
252 static wxDateTime::Month
GetMonthFromName(const wxString
& name
)
254 wxDateTime::Month mon
;
255 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
257 // case-insensitive comparison with both abbreviated and not versions
258 if ( name
.CmpNoCase(wxDateTime::GetMonthName(mon
, TRUE
)) ||
259 name
.CmpNoCase(wxDateTime::GetMonthName(mon
, FALSE
)) )
268 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
269 static wxDateTime::WeekDay
GetWeekDayFromName(const wxString
& name
)
271 wxDateTime::WeekDay wd
;
272 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
274 // case-insensitive comparison with both abbreviated and not versions
275 if ( name
.IsSameAs(wxDateTime::GetWeekDayName(wd
, TRUE
), FALSE
) ||
276 name
.IsSameAs(wxDateTime::GetWeekDayName(wd
, FALSE
), FALSE
) )
285 // ============================================================================
286 // implementation of wxDateTime
287 // ============================================================================
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
294 wxDateTime
wxDateTime::ms_InvDateTime
;
296 // ----------------------------------------------------------------------------
298 // ----------------------------------------------------------------------------
302 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
303 mon
= wxDateTime::Inv_Month
;
305 hour
= min
= sec
= msec
= 0;
306 wday
= wxDateTime::Inv_WeekDay
;
309 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
317 mon
= (wxDateTime::Month
)tm
.tm_mon
;
318 year
= 1900 + tm
.tm_year
;
323 bool wxDateTime::Tm::IsValid() const
325 // we allow for the leap seconds, although we don't use them (yet)
326 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
327 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
328 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
331 void wxDateTime::Tm::ComputeWeekDay()
333 // compute the week day from day/month/year: we use the dumbest algorithm
334 // possible: just compute our JDN and then use the (simple to derive)
335 // formula: weekday = (JDN + 1.5) % 7
336 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
339 void wxDateTime::Tm::AddMonths(int monDiff
)
341 // normalize the months field
342 while ( monDiff
< -mon
)
346 monDiff
+= MONTHS_IN_YEAR
;
349 while ( monDiff
+ mon
> MONTHS_IN_YEAR
)
353 monDiff
-= MONTHS_IN_YEAR
;
356 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
358 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
361 void wxDateTime::Tm::AddDays(int dayDiff
)
363 // normalize the days field
369 mday
+= GetNumOfDaysInMonth(year
, mon
);
372 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
374 mday
-= GetNumOfDaysInMonth(year
, mon
);
379 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
383 // ----------------------------------------------------------------------------
385 // ----------------------------------------------------------------------------
387 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
391 case wxDateTime::Local
:
392 // get the offset from C RTL: it returns the difference GMT-local
393 // while we want to have the offset _from_ GMT, hence the '-'
394 m_offset
= -GetTimeZone();
397 case wxDateTime::GMT_12
:
398 case wxDateTime::GMT_11
:
399 case wxDateTime::GMT_10
:
400 case wxDateTime::GMT_9
:
401 case wxDateTime::GMT_8
:
402 case wxDateTime::GMT_7
:
403 case wxDateTime::GMT_6
:
404 case wxDateTime::GMT_5
:
405 case wxDateTime::GMT_4
:
406 case wxDateTime::GMT_3
:
407 case wxDateTime::GMT_2
:
408 case wxDateTime::GMT_1
:
409 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
412 case wxDateTime::GMT0
:
413 case wxDateTime::GMT1
:
414 case wxDateTime::GMT2
:
415 case wxDateTime::GMT3
:
416 case wxDateTime::GMT4
:
417 case wxDateTime::GMT5
:
418 case wxDateTime::GMT6
:
419 case wxDateTime::GMT7
:
420 case wxDateTime::GMT8
:
421 case wxDateTime::GMT9
:
422 case wxDateTime::GMT10
:
423 case wxDateTime::GMT11
:
424 case wxDateTime::GMT12
:
425 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
428 case wxDateTime::A_CST
:
429 // Central Standard Time in use in Australia = UTC + 9.5
430 m_offset
= 60l*(9*60 + 30);
434 wxFAIL_MSG( _T("unknown time zone") );
438 // ----------------------------------------------------------------------------
440 // ----------------------------------------------------------------------------
443 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
445 if ( year
== Inv_Year
)
446 year
= GetCurrentYear();
448 if ( cal
== Gregorian
)
450 // in Gregorian calendar leap years are those divisible by 4 except
451 // those divisible by 100 unless they're also divisible by 400
452 // (in some countries, like Russia and Greece, additional corrections
453 // exist, but they won't manifest themselves until 2700)
454 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
456 else if ( cal
== Julian
)
458 // in Julian calendar the rule is simpler
459 return year
% 4 == 0;
463 wxFAIL_MSG(_T("unknown calendar"));
470 int wxDateTime::GetCentury(int year
)
472 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
476 int wxDateTime::ConvertYearToBC(int year
)
479 return year
> 0 ? year
: year
- 1;
483 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
488 return Now().GetYear();
491 wxFAIL_MSG(_T("TODO"));
495 wxFAIL_MSG(_T("unsupported calendar"));
503 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
508 return Now().GetMonth();
512 wxFAIL_MSG(_T("TODO"));
516 wxFAIL_MSG(_T("unsupported calendar"));
524 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
526 if ( year
== Inv_Year
)
528 // take the current year if none given
529 year
= GetCurrentYear();
536 return IsLeapYear(year
) ? 366 : 365;
540 wxFAIL_MSG(_T("unsupported calendar"));
548 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
550 wxDateTime::Calendar cal
)
552 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
554 if ( cal
== Gregorian
|| cal
== Julian
)
556 if ( year
== Inv_Year
)
558 // take the current year if none given
559 year
= GetCurrentYear();
562 return GetNumOfDaysInMonth(year
, month
);
566 wxFAIL_MSG(_T("unsupported calendar"));
573 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
, bool abbr
)
575 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
583 tm
.tm_year
= 76; // any year will do
585 return CallStrftime(abbr
? _T("%b") : _T("%B"), &tm
);
589 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
, bool abbr
)
591 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
593 // take some arbitrary Sunday
594 tm tm
= { 0, 0, 0, 28, Nov
, 99 };
596 // and offset it by the number of days needed to get the correct wday
599 // call mktime() to normalize it...
602 // ... and call strftime()
603 return CallStrftime(abbr
? _T("%a") : _T("%A"), &tm
);
606 // ----------------------------------------------------------------------------
607 // Country stuff: date calculations depend on the country (DST, work days,
608 // ...), so we need to know which rules to follow.
609 // ----------------------------------------------------------------------------
612 wxDateTime::Country
wxDateTime::GetCountry()
614 if ( ms_country
== Country_Unknown
)
616 // try to guess from the time zone name
617 time_t t
= time(NULL
);
618 struct tm
*tm
= localtime(&t
);
620 wxString tz
= CallStrftime(_T("%Z"), tm
);
621 if ( tz
== _T("WET") || tz
== _T("WEST") )
625 else if ( tz
== _T("CET") || tz
== _T("CEST") )
627 ms_country
= Country_EEC
;
629 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
633 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
634 tz
== _T("EST") || tz
== _T("EDT") ||
635 tz
== _T("CST") || tz
== _T("CDT") ||
636 tz
== _T("MST") || tz
== _T("MDT") ||
637 tz
== _T("PST") || tz
== _T("PDT") )
643 // well, choose a default one
652 void wxDateTime::SetCountry(wxDateTime::Country country
)
654 ms_country
= country
;
658 bool wxDateTime::IsWestEuropeanCountry(Country country
)
660 if ( country
== Country_Default
)
662 country
= GetCountry();
665 return (Country_WesternEurope_Start
<= country
) &&
666 (country
<= Country_WesternEurope_End
);
669 // ----------------------------------------------------------------------------
670 // DST calculations: we use 3 different rules for the West European countries,
671 // USA and for the rest of the world. This is undoubtedly false for many
672 // countries, but I lack the necessary info (and the time to gather it),
673 // please add the other rules here!
674 // ----------------------------------------------------------------------------
677 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
679 if ( year
== Inv_Year
)
681 // take the current year if none given
682 year
= GetCurrentYear();
685 if ( country
== Country_Default
)
687 country
= GetCountry();
694 // DST was first observed in the US and UK during WWI, reused
695 // during WWII and used again since 1966
696 return year
>= 1966 ||
697 (year
>= 1942 && year
<= 1945) ||
698 (year
== 1918 || year
== 1919);
701 // assume that it started after WWII
707 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
709 if ( year
== Inv_Year
)
711 // take the current year if none given
712 year
= GetCurrentYear();
715 if ( country
== Country_Default
)
717 country
= GetCountry();
720 if ( !IsDSTApplicable(year
, country
) )
722 return ms_InvDateTime
;
727 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
729 // DST begins at 1 a.m. GMT on the last Sunday of March
730 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
733 wxFAIL_MSG( _T("no last Sunday in March?") );
736 dt
+= wxTimeSpan::Hours(1);
740 else switch ( country
)
747 // don't know for sure - assume it was in effect all year
752 dt
.Set(1, Jan
, year
);
756 // DST was installed Feb 2, 1942 by the Congress
757 dt
.Set(2, Feb
, year
);
760 // Oil embargo changed the DST period in the US
762 dt
.Set(6, Jan
, 1974);
766 dt
.Set(23, Feb
, 1975);
770 // before 1986, DST begun on the last Sunday of April, but
771 // in 1986 Reagan changed it to begin at 2 a.m. of the
772 // first Sunday in April
775 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
778 wxFAIL_MSG( _T("no first Sunday in April?") );
783 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
786 wxFAIL_MSG( _T("no first Sunday in April?") );
790 dt
+= wxTimeSpan::Hours(2);
792 // TODO what about timezone??
798 // assume Mar 30 as the start of the DST for the rest of the world
799 // - totally bogus, of course
800 dt
.Set(30, Mar
, year
);
807 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
809 if ( year
== Inv_Year
)
811 // take the current year if none given
812 year
= GetCurrentYear();
815 if ( country
== Country_Default
)
817 country
= GetCountry();
820 if ( !IsDSTApplicable(year
, country
) )
822 return ms_InvDateTime
;
827 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
829 // DST ends at 1 a.m. GMT on the last Sunday of October
830 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
832 // weirder and weirder...
833 wxFAIL_MSG( _T("no last Sunday in October?") );
836 dt
+= wxTimeSpan::Hours(1);
840 else switch ( country
)
847 // don't know for sure - assume it was in effect all year
851 dt
.Set(31, Dec
, year
);
855 // the time was reset after the end of the WWII
856 dt
.Set(30, Sep
, year
);
860 // DST ends at 2 a.m. on the last Sunday of October
861 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
863 // weirder and weirder...
864 wxFAIL_MSG( _T("no last Sunday in October?") );
867 dt
+= wxTimeSpan::Hours(2);
869 // TODO what about timezone??
874 // assume October 26th as the end of the DST - totally bogus too
875 dt
.Set(26, Oct
, year
);
881 // ----------------------------------------------------------------------------
882 // constructors and assignment operators
883 // ----------------------------------------------------------------------------
885 // the values in the tm structure contain the local time
886 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
888 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
891 time_t timet
= mktime(&tm2
);
893 if ( timet
== (time_t)-1 )
895 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
896 // less than timezone - try to make it work for this case
897 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
899 // add timezone to make sure that date is in range
900 tm2
.tm_sec
-= GetTimeZone();
902 timet
= mktime(&tm2
);
903 if ( timet
!= (time_t)-1 )
905 timet
+= GetTimeZone();
911 wxFAIL_MSG( _T("mktime() failed") );
913 return ms_InvDateTime
;
921 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
924 wxDateTime_t millisec
)
926 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
928 // we allow seconds to be 61 to account for the leap seconds, even if we
929 // don't use them really
930 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
932 _T("Invalid time in wxDateTime::Set()") );
934 // get the current date from system
935 time_t timet
= GetTimeNow();
936 struct tm
*tm
= localtime(&timet
);
938 wxCHECK_MSG( tm
, ms_InvDateTime
, _T("localtime() failed") );
947 // and finally adjust milliseconds
948 return SetMillisecond(millisec
);
951 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
957 wxDateTime_t millisec
)
959 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
961 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
963 _T("Invalid time in wxDateTime::Set()") );
965 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
967 wxCHECK_MSG( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
969 _T("Invalid date in wxDateTime::Set()") );
971 // the range of time_t type (inclusive)
972 static const int yearMinInRange
= 1970;
973 static const int yearMaxInRange
= 2037;
975 // test only the year instead of testing for the exact end of the Unix
976 // time_t range - it doesn't bring anything to do more precise checks
977 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
979 // use the standard library version if the date is in range - this is
980 // probably more efficient than our code
982 tm
.tm_year
= year
- 1900;
988 tm
.tm_isdst
= -1; // mktime() will guess it
992 // and finally adjust milliseconds
993 return SetMillisecond(millisec
);
997 // do time calculations ourselves: we want to calculate the number of
998 // milliseconds between the given date and the epoch
1000 // get the JDN for the midnight of this day
1001 m_time
= GetTruncatedJDN(day
, month
, year
);
1002 m_time
-= EPOCH_JDN
;
1003 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
1005 // JDN corresponds to GMT, we take localtime
1006 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
1012 wxDateTime
& wxDateTime::Set(double jdn
)
1014 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
1016 jdn
-= EPOCH_JDN
+ 0.5;
1018 jdn
*= MILLISECONDS_PER_DAY
;
1025 // ----------------------------------------------------------------------------
1026 // time_t <-> broken down time conversions
1027 // ----------------------------------------------------------------------------
1029 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
1031 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1033 time_t time
= GetTicks();
1034 if ( time
!= (time_t)-1 )
1036 // use C RTL functions
1038 if ( tz
.GetOffset() == -GetTimeZone() )
1040 // we are working with local time
1041 tm
= localtime(&time
);
1043 // should never happen
1044 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1048 time
+= tz
.GetOffset();
1053 // should never happen
1054 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1058 tm
= (struct tm
*)NULL
;
1066 //else: use generic code below
1069 // remember the time and do the calculations with the date only - this
1070 // eliminates rounding errors of the floating point arithmetics
1072 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1074 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1076 // we want to always have positive time and timeMidnight to be really
1077 // the midnight before it
1080 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1083 timeMidnight
-= timeOnly
;
1085 // calculate the Gregorian date from JDN for the midnight of our date:
1086 // this will yield day, month (in 1..12 range) and year
1088 // actually, this is the JDN for the noon of the previous day
1089 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1091 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1093 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1095 // calculate the century
1096 int temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1097 int century
= temp
/ DAYS_PER_400_YEARS
;
1099 // then the year and day of year (1 <= dayOfYear <= 366)
1100 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1101 int year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1102 int dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1104 // and finally the month and day of the month
1105 temp
= dayOfYear
* 5 - 3;
1106 int month
= temp
/ DAYS_PER_5_MONTHS
;
1107 int day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1109 // month is counted from March - convert to normal
1120 // year is offset by 4800
1123 // check that the algorithm gave us something reasonable
1124 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1125 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1126 wxASSERT_MSG( (INT_MIN
<= year
) && (year
<= INT_MAX
),
1127 _T("year range overflow") );
1129 // construct Tm from these values
1131 tm
.year
= (int)year
;
1132 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1133 tm
.mday
= (wxDateTime_t
)day
;
1134 tm
.msec
= timeOnly
% 1000;
1135 timeOnly
-= tm
.msec
;
1136 timeOnly
/= 1000; // now we have time in seconds
1138 tm
.sec
= timeOnly
% 60;
1140 timeOnly
/= 60; // now we have time in minutes
1142 tm
.min
= timeOnly
% 60;
1145 tm
.hour
= timeOnly
/ 60;
1150 wxDateTime
& wxDateTime::SetYear(int year
)
1152 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1161 wxDateTime
& wxDateTime::SetMonth(Month month
)
1163 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1172 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1174 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1183 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1185 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1194 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1196 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1205 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1207 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1216 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1218 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1220 // we don't need to use GetTm() for this one
1221 m_time
-= m_time
% 1000l;
1222 m_time
+= millisecond
;
1227 // ----------------------------------------------------------------------------
1228 // wxDateTime arithmetics
1229 // ----------------------------------------------------------------------------
1231 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1235 tm
.year
+= diff
.GetYears();
1236 tm
.AddMonths(diff
.GetMonths());
1237 tm
.AddDays(diff
.GetTotalDays());
1244 // ----------------------------------------------------------------------------
1245 // Weekday and monthday stuff
1246 // ----------------------------------------------------------------------------
1248 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1251 // take the current month/year if none specified
1252 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1254 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1257 wxDateTime
& wxDateTime::SetToWeekDayInSameWeek(WeekDay weekday
)
1259 wxCHECK_MSG( weekday
!= Inv_WeekDay
, ms_InvDateTime
, _T("invalid weekday") );
1261 WeekDay wdayThis
= GetWeekDay();
1262 if ( weekday
== wdayThis
)
1267 else if ( weekday
< wdayThis
)
1269 return Substract(wxTimeSpan::Days(wdayThis
- weekday
));
1271 else // weekday > wdayThis
1273 return Add(wxTimeSpan::Days(weekday
- wdayThis
));
1277 wxDateTime
& wxDateTime::SetToNextWeekDay(WeekDay weekday
)
1279 wxCHECK_MSG( weekday
!= Inv_WeekDay
, ms_InvDateTime
, _T("invalid weekday") );
1282 WeekDay wdayThis
= GetWeekDay();
1283 if ( weekday
== wdayThis
)
1288 else if ( weekday
< wdayThis
)
1290 // need to advance a week
1291 diff
= 7 - (wdayThis
- weekday
);
1293 else // weekday > wdayThis
1295 diff
= weekday
- wdayThis
;
1298 return Add(wxTimeSpan::Days(diff
));
1301 wxDateTime
& wxDateTime::SetToPrevWeekDay(WeekDay weekday
)
1303 wxCHECK_MSG( weekday
!= Inv_WeekDay
, ms_InvDateTime
, _T("invalid weekday") );
1306 WeekDay wdayThis
= GetWeekDay();
1307 if ( weekday
== wdayThis
)
1312 else if ( weekday
> wdayThis
)
1314 // need to go to previous week
1315 diff
= 7 - (weekday
- wdayThis
);
1317 else // weekday < wdayThis
1319 diff
= wdayThis
- weekday
;
1322 return Substract(wxTimeSpan::Days(diff
));
1325 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1330 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1332 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1333 // anyhow in such case - but may be should still give an assert for it?
1335 // take the current month/year if none specified
1336 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1340 // TODO this probably could be optimised somehow...
1344 // get the first day of the month
1345 dt
.Set(1, month
, year
);
1348 WeekDay wdayFirst
= dt
.GetWeekDay();
1350 // go to the first weekday of the month
1351 int diff
= weekday
- wdayFirst
;
1355 // add advance n-1 weeks more
1358 dt
+= wxDateSpan::Days(diff
);
1360 else // count from the end of the month
1362 // get the last day of the month
1363 dt
.SetToLastMonthDay(month
, year
);
1366 WeekDay wdayLast
= dt
.GetWeekDay();
1368 // go to the last weekday of the month
1369 int diff
= wdayLast
- weekday
;
1373 // and rewind n-1 weeks from there
1376 dt
-= wxDateSpan::Days(diff
);
1379 // check that it is still in the same month
1380 if ( dt
.GetMonth() == month
)
1388 // no such day in this month
1393 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1395 // this array contains the cumulated number of days in all previous months
1396 // for normal and leap years
1397 static const wxDateTime_t cumulatedDays
[2][MONTHS_IN_YEAR
] =
1399 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
1400 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
1405 return cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1408 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(const TimeZone
& tz
) const
1410 // the first week of the year is the one which contains Jan, 4 (according
1411 // to ISO standard rule), so the year day N0 = 4 + 7*W always lies in the
1412 // week W+1. As any day N = 7*W + 4 + (N - 4)%7, it lies in the same week
1413 // as N0 or in the next one.
1415 // TODO this surely may be optimized - I got confused while writing it
1417 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1419 // the week day of the day lying in the first week
1420 WeekDay wdayStart
= wxDateTime(4, Jan
, GetYear()).GetWeekDay();
1422 wxDateTime_t week
= (nDayInYear
- 4) / 7 + 1;
1424 // notice that Sunday shoould be counted as 7, not 0 here!
1425 if ( ((nDayInYear
- 4) % 7) + (!wdayStart
? 7 : wdayStart
) > 7 )
1433 // ----------------------------------------------------------------------------
1434 // Julian day number conversion and related stuff
1435 // ----------------------------------------------------------------------------
1437 double wxDateTime::GetJulianDayNumber() const
1439 // JDN are always expressed for the GMT dates
1440 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1442 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1444 // add the part GetTruncatedJDN() neglected
1447 // and now add the time: 86400 sec = 1 JDN
1448 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1451 double wxDateTime::GetRataDie() const
1453 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1454 return GetJulianDayNumber() - 1721119.5 - 306;
1457 // ----------------------------------------------------------------------------
1458 // timezone and DST stuff
1459 // ----------------------------------------------------------------------------
1461 int wxDateTime::IsDST(wxDateTime::Country country
) const
1463 wxCHECK_MSG( country
== Country_Default
, -1,
1464 _T("country support not implemented") );
1466 // use the C RTL for the dates in the standard range
1467 time_t timet
= GetTicks();
1468 if ( timet
!= (time_t)-1 )
1470 tm
*tm
= localtime(&timet
);
1472 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1474 return tm
->tm_isdst
;
1478 int year
= GetYear();
1480 if ( !IsDSTApplicable(year
, country
) )
1482 // no DST time in this year in this country
1486 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1490 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
)
1492 int secDiff
= GetTimeZone() + tz
.GetOffset();
1494 // we need to know whether DST is or not in effect for this date
1497 // FIXME we assume that the DST is always shifted by 1 hour
1501 return Substract(wxTimeSpan::Seconds(secDiff
));
1504 // ----------------------------------------------------------------------------
1505 // wxDateTime to/from text representations
1506 // ----------------------------------------------------------------------------
1508 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1510 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1512 time_t time
= GetTicks();
1513 if ( time
!= (time_t)-1 )
1517 if ( tz
.GetOffset() == -GetTimeZone() )
1519 // we are working with local time
1520 tm
= localtime(&time
);
1522 // should never happen
1523 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1527 time
+= tz
.GetOffset();
1533 // should never happen
1534 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1538 tm
= (struct tm
*)NULL
;
1544 return CallStrftime(format
, tm
);
1546 //else: use generic code below
1549 // use a hack and still use strftime(): first find the YEAR which is a year
1550 // in the strftime() range (1970 - 2038) whose Jan 1 falls on the same week
1551 // day as the Jan 1 of the real year. Then make a copy of the format and
1552 // replace all occurences of YEAR in it with some unique string not
1553 // appearing anywhere else in it, then use strftime() to format the date in
1554 // year YEAR and then replace YEAR back by the real year and the unique
1555 // replacement string back with YEAR. Notice that "all occurences of YEAR"
1556 // means all occurences of 4 digit as well as 2 digit form!
1558 // NB: may be it would be simpler to "honestly" reimplement strftime()?
1560 // find the YEAR: normally, for any year X, Jan 1 or the year X + 28 is the
1561 // same weekday as Jan 1 of X (because the weekday advances by 1 for each
1562 // normal X and by 2 for each leap X, hence by 5 every 4 years or by 35
1563 // which is 0 mod 7 every 28 years) but this rule breaks down if there are
1564 // years between X and Y which are divisible by 4 but not leap (i.e.
1565 // divisible by 100 but not 400), hence the correction.
1567 int yearReal
= GetYear(tz
);
1568 int year
= 1970 + yearReal
% 28;
1570 int nCenturiesInBetween
= (year
/ 100) - (yearReal
/ 100);
1571 int nLostWeekDays
= nCenturiesInBetween
- (nCenturiesInBetween
/ 400);
1573 // we have to gain back the "lost" weekdays...
1574 while ( (nLostWeekDays
% 7) != 0 )
1576 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
1579 // at any rate, we can't go further than 1997 + 28!
1580 wxASSERT_MSG( year
< 2030, _T("logic error in wxDateTime::Format") );
1582 wxString strYear
, strYear2
;
1583 strYear
.Printf(_T("%d"), year
);
1584 strYear2
.Printf(_T("%d"), year
% 100);
1586 // find two strings not occuring in format (this is surely not optimal way
1587 // of doing it... improvements welcome!)
1588 wxString fmt
= format
;
1589 wxString replacement
= (wxChar
)-1;
1590 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1592 replacement
<< (wxChar
)-1;
1595 wxString replacement2
= (wxChar
)-2;
1596 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1598 replacement
<< (wxChar
)-2;
1601 // replace all occurences of year with it
1602 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
1604 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
1606 // use strftime() to format the same date but in supported year
1607 wxDateTime
dt(*this);
1609 wxString str
= dt
.Format(format
, tz
);
1611 // now replace the occurence of 1999 with the real year
1612 wxString strYearReal
, strYearReal2
;
1613 strYearReal
.Printf(_T("%04d"), yearReal
);
1614 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
1615 str
.Replace(strYear
, strYearReal
);
1616 str
.Replace(strYear2
, strYearReal2
);
1618 // and replace back all occurences of replacement string
1621 str
.Replace(replacement2
, strYear2
);
1622 str
.Replace(replacement
, strYear
);
1628 // this function parses a string in (strict) RFC 822 format: see the section 5
1629 // of the RFC for the detailed description, but briefly it's something of the
1630 // form "Sat, 18 Dec 1999 00:48:30 +0100"
1632 // this function is "strict" by design - it must reject anything except true
1633 // RFC822 time specs.
1635 // TODO a great candidate for using reg exps
1636 const wxChar
*wxDateTime::ParseRfc822Date(const wxChar
* date
)
1638 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
1640 const wxChar
*p
= date
;
1641 const wxChar
*comma
= wxStrchr(p
, _T(','));
1644 // the part before comma is the weekday
1646 // skip it for now - we don't use but might check that it really
1647 // corresponds to the specfied date
1650 if ( *p
!= _T(' ') )
1652 wxLogDebug(_T("no space after weekday in RFC822 time spec"));
1654 return (wxChar
*)NULL
;
1660 // the following 1 or 2 digits are the day number
1661 if ( !wxIsdigit(*p
) )
1663 wxLogDebug(_T("day number expected in RFC822 time spec, none found"));
1665 return (wxChar
*)NULL
;
1668 wxDateTime_t day
= *p
++ - _T('0');
1669 if ( wxIsdigit(*p
) )
1672 day
+= *p
++ - _T('0');
1675 if ( *p
++ != _T(' ') )
1677 return (wxChar
*)NULL
;
1680 // the following 3 letters specify the month
1681 wxString
monName(p
, 3);
1683 if ( monName
== _T("Jan") )
1685 else if ( monName
== _T("Feb") )
1687 else if ( monName
== _T("Mar") )
1689 else if ( monName
== _T("Apr") )
1691 else if ( monName
== _T("May") )
1693 else if ( monName
== _T("Jun") )
1695 else if ( monName
== _T("Jul") )
1697 else if ( monName
== _T("Aug") )
1699 else if ( monName
== _T("Sep") )
1701 else if ( monName
== _T("Oct") )
1703 else if ( monName
== _T("Nov") )
1705 else if ( monName
== _T("Dec") )
1709 wxLogDebug(_T("Invalid RFC 822 month name '%s'"), monName
.c_str());
1711 return (wxChar
*)NULL
;
1716 if ( *p
++ != _T(' ') )
1718 return (wxChar
*)NULL
;
1722 if ( !wxIsdigit(*p
) )
1725 return (wxChar
*)NULL
;
1728 int year
= *p
++ - _T('0');
1730 if ( !wxIsdigit(*p
) )
1732 // should have at least 2 digits in the year
1733 return (wxChar
*)NULL
;
1737 year
+= *p
++ - _T('0');
1739 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
1740 if ( wxIsdigit(*p
) )
1743 year
+= *p
++ - _T('0');
1745 if ( !wxIsdigit(*p
) )
1747 // no 3 digit years please
1748 return (wxChar
*)NULL
;
1752 year
+= *p
++ - _T('0');
1755 if ( *p
++ != _T(' ') )
1757 return (wxChar
*)NULL
;
1760 // time is in the format hh:mm:ss and seconds are optional
1761 if ( !wxIsdigit(*p
) )
1763 return (wxChar
*)NULL
;
1766 wxDateTime_t hour
= *p
++ - _T('0');
1768 if ( !wxIsdigit(*p
) )
1770 return (wxChar
*)NULL
;
1774 hour
+= *p
++ - _T('0');
1776 if ( *p
++ != _T(':') )
1778 return (wxChar
*)NULL
;
1781 if ( !wxIsdigit(*p
) )
1783 return (wxChar
*)NULL
;
1786 wxDateTime_t min
= *p
++ - _T('0');
1788 if ( !wxIsdigit(*p
) )
1790 return (wxChar
*)NULL
;
1794 min
+= *p
++ - _T('0');
1796 wxDateTime_t sec
= 0;
1797 if ( *p
++ == _T(':') )
1799 if ( !wxIsdigit(*p
) )
1801 return (wxChar
*)NULL
;
1804 sec
= *p
++ - _T('0');
1806 if ( !wxIsdigit(*p
) )
1808 return (wxChar
*)NULL
;
1812 sec
+= *p
++ - _T('0');
1815 if ( *p
++ != _T(' ') )
1817 return (wxChar
*)NULL
;
1820 // and now the interesting part: the timezone
1822 if ( *p
== _T('-') || *p
== _T('+') )
1824 // the explicit offset given: it has the form of hhmm
1825 bool plus
= *p
++ == _T('+');
1827 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
1829 return (wxChar
*)NULL
;
1833 offset
= 60*(10*(*p
- _T('0')) + (*(p
+ 1) - _T('0')));
1837 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
1839 return (wxChar
*)NULL
;
1843 offset
+= 10*(*p
- _T('0')) + (*(p
+ 1) - _T('0'));
1854 // the symbolic timezone given: may be either military timezone or one
1855 // of standard abbreviations
1858 // military: Z = UTC, J unused, A = -1, ..., Y = +12
1859 static const int offsets
[26] =
1861 //A B C D E F G H I J K L M
1862 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
1863 //N O P R Q S T U V W Z Y Z
1864 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
1867 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
1869 wxLogDebug(_T("Invalid militaty timezone '%c'"), *p
);
1871 return (wxChar
*)NULL
;
1874 offset
= offsets
[*p
++ - _T('A')];
1880 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
1882 else if ( tz
== _T("AST") )
1883 offset
= AST
- GMT0
;
1884 else if ( tz
== _T("ADT") )
1885 offset
= ADT
- GMT0
;
1886 else if ( tz
== _T("EST") )
1887 offset
= EST
- GMT0
;
1888 else if ( tz
== _T("EDT") )
1889 offset
= EDT
- GMT0
;
1890 else if ( tz
== _T("CST") )
1891 offset
= CST
- GMT0
;
1892 else if ( tz
== _T("CDT") )
1893 offset
= CDT
- GMT0
;
1894 else if ( tz
== _T("MST") )
1895 offset
= MST
- GMT0
;
1896 else if ( tz
== _T("MDT") )
1897 offset
= MDT
- GMT0
;
1898 else if ( tz
== _T("PST") )
1899 offset
= PST
- GMT0
;
1900 else if ( tz
== _T("PDT") )
1901 offset
= PDT
- GMT0
;
1904 wxLogDebug(_T("Unknown RFC 822 timezone '%s'"), p
);
1906 return (wxChar
*)NULL
;
1916 // the spec was correct
1917 Set(day
, mon
, year
, hour
, min
, sec
);
1918 MakeTimezone(60*offset
);
1923 const wxChar
*wxDateTime::ParseFormat(const wxChar
*date
, const wxChar
*format
)
1925 wxCHECK_MSG( date
&& format
, (wxChar
*)NULL
,
1926 _T("NULL pointer in wxDateTime::Parse") );
1928 // there is a public domain version of getdate.y, but it only works for
1930 wxFAIL_MSG(_T("TODO"));
1932 return (wxChar
*)NULL
;
1935 const wxChar
*wxDateTime::ParseDateTime(const wxChar
*date
)
1937 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
1939 // find a public domain version of strptime() somewhere?
1940 wxFAIL_MSG(_T("TODO"));
1942 return (wxChar
*)NULL
;
1945 const wxChar
*wxDateTime::ParseDate(const wxChar
*date
)
1947 // this is a simplified version of ParseDateTime() which understands only
1948 // "today" (for wxDate compatibility) and digits only otherwise (and not
1949 // all esoteric constructions ParseDateTime() knows about)
1951 wxCHECK_MSG( date
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
1953 const wxChar
*p
= date
;
1954 while ( wxIsspace(*p
) )
1957 wxString today
= _T("today");
1958 size_t len
= today
.length();
1959 if ( wxString(p
, len
).CmpNoCase(today
) == 0 )
1961 // nothing can follow this, so stop here
1970 bool haveDay
= FALSE
, // the months day?
1971 haveWDay
= FALSE
, // the day of week?
1972 haveMon
= FALSE
, // the month?
1973 haveYear
= FALSE
; // the year?
1975 // and the value of the items we have (init them to get rid of warnings)
1976 WeekDay wday
= Inv_WeekDay
;
1977 wxDateTime_t day
= 0;
1978 wxDateTime::Month mon
= Inv_Month
;
1981 // tokenize the string
1982 wxStringTokenizer
tok(p
, _T(",/-\t "));
1983 while ( tok
.HasMoreTokens() )
1985 wxString token
= tok
.GetNextToken();
1989 if ( token
.ToULong(&val
) )
1991 // guess what this number is
1995 // only years are counted from 0
1996 isYear
= (val
== 0) || (val
> 31);
1999 // may be the month or month day or the year, assume the
2000 // month day by default and fallback to month if the range
2001 // allow it or to the year if our assumption doesn't work
2004 // we already have the day, so may only be a month or year
2014 else // it may be day
2021 if ( val
> GetNumOfDaysInMonth(haveYear
? year
2025 // oops, it can't be a day finally
2041 // remember that we have this and stop the scan if it's the second
2042 // time we find this, except for the day logic (see there)
2052 // no roll over - 99 means 99, not 1999 for us
2064 mon
= (wxDateTime::Month
)val
;
2068 wxASSERT_MSG( isDay
, _T("logic error") );
2072 // may be were mistaken when we found it for the first
2073 // time? may be it was a month or year instead?
2075 // this ability to "backtrack" allows us to correctly parse
2076 // both things like 01/13 and 13/01 - but, of course, we
2077 // still can't resolve the ambiguity in 01/02 (it will be
2078 // Feb 1 for us, not Jan 2 as americans might expect!)
2079 if ( (day
<= 12) && !haveMon
)
2081 // exchange day and month
2082 mon
= (wxDateTime::Month
)day
;
2086 else if ( !haveYear
)
2088 // exchange day and year
2100 else // not a number
2102 mon
= GetMonthFromName(token
);
2103 if ( mon
!= Inv_Month
)
2115 wday
= GetWeekDayFromName(token
);
2116 if ( wday
!= Inv_WeekDay
)
2129 static const wxChar
*ordinals
[] =
2131 wxTRANSLATE("first"),
2132 wxTRANSLATE("second"),
2133 wxTRANSLATE("third"),
2134 wxTRANSLATE("fourth"),
2135 wxTRANSLATE("fifth"),
2136 wxTRANSLATE("sixth"),
2137 wxTRANSLATE("seventh"),
2138 wxTRANSLATE("eighth"),
2139 wxTRANSLATE("ninth"),
2140 wxTRANSLATE("tenth"),
2141 wxTRANSLATE("eleventh"),
2142 wxTRANSLATE("twelfth"),
2143 wxTRANSLATE("thirteenth"),
2144 wxTRANSLATE("fourteenth"),
2145 wxTRANSLATE("fifteenth"),
2146 wxTRANSLATE("sixteenth"),
2147 wxTRANSLATE("seventeenth"),
2148 wxTRANSLATE("eighteenth"),
2149 wxTRANSLATE("nineteenth"),
2150 wxTRANSLATE("twentieth"),
2151 // that's enough - otherwise we'd have problems with
2152 // composite (or not) ordinals otherwise
2156 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
2158 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
2164 if ( n
== WXSIZEOF(ordinals
) )
2166 // stop here - something unknown
2173 // don't try anything here (as in case of numeric day
2174 // above) - the symbolic day spec should always
2175 // precede the month/year
2187 // either no more tokens or the scan was stopped by something we couldn't
2188 // parse - in any case, see if we can construct a date from what we have
2189 if ( !haveDay
&& !haveWDay
)
2191 wxLogDebug(_T("no day, no weekday hence no date."));
2193 return (wxChar
*)NULL
;
2196 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
2197 !(haveMon
&& haveMon
&& haveYear
) )
2199 // without adjectives (which we don't support here) the week day only
2200 // makes sense completely separately or with the full date
2201 // specification (what would "Wed 1999" mean?)
2202 return (wxChar
*)NULL
;
2207 mon
= GetCurrentMonth();
2212 year
= GetCurrentYear();
2217 Set(day
, mon
, year
);
2221 // check that it is really the same
2222 if ( GetWeekDay() != wday
)
2224 // inconsistency detected
2225 return (wxChar
*)NULL
;
2233 SetToWeekDayInSameWeek(wday
);
2236 // return the pointer to the next char
2237 return p
+ wxStrlen(p
) - wxStrlen(tok
.GetString());
2240 const wxChar
*wxDateTime::ParseTime(const wxChar
*time
)
2242 wxCHECK_MSG( time
, (wxChar
*)NULL
, _T("NULL pointer in wxDateTime::Parse") );
2244 // this function should be able to parse different time formats as well as
2245 // timezones (take the code out from ParseRfc822Date()) and AM/PM.
2246 wxFAIL_MSG(_T("TODO"));
2248 return (wxChar
*)NULL
;
2251 // ============================================================================
2253 // ============================================================================
2255 // not all strftime(3) format specifiers make sense here because, for example,
2256 // a time span doesn't have a year nor a timezone
2258 // Here are the ones which are supported (all of them are supported by strftime
2260 // %H hour in 24 hour format
2261 // %M minute (00 - 59)
2262 // %S second (00 - 59)
2265 // Also, for MFC CTimeSpan compatibility, we support
2266 // %D number of days
2268 // And, to be better than MFC :-), we also have
2269 // %E number of wEeks
2270 // %l milliseconds (000 - 999)
2271 wxString
wxTimeSpan::Format(const wxChar
*format
) const
2273 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
2276 str
.Alloc(strlen(format
));
2278 for ( const wxChar
*pch
= format
; pch
; pch
++ )
2290 wxFAIL_MSG( _T("invalid format character") );
2294 // will get to str << ch below
2298 tmp
.Printf(_T("%d"), GetDays());
2302 tmp
.Printf(_T("%d"), GetWeeks());
2306 tmp
.Printf(_T("%02d"), GetHours());
2310 tmp
.Printf(_T("%03ld"), GetMilliseconds().ToLong());
2314 tmp
.Printf(_T("%02d"), GetMinutes());
2318 tmp
.Printf(_T("%02ld"), GetSeconds().ToLong());
2326 // skip str += ch below