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"
74 #define wxDEFINE_TIME_CONSTANTS
76 #include "wx/datetime.h"
79 #define WX_TIMEZONE timezone
82 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
87 static const int MONTHS_IN_YEAR
= 12;
89 static const int SECONDS_IN_MINUTE
= 60;
91 static const long SECONDS_PER_DAY
= 86400l;
93 static const long MILLISECONDS_PER_DAY
= 86400000l;
95 // this is the integral part of JDN of the midnight of Jan 1, 1970
96 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
97 static const int EPOCH_JDN
= 2440587;
99 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
100 // reference date for us) is Nov 24, 4714BC
101 static const int JDN_0_YEAR
= -4713;
102 static const int JDN_0_MONTH
= wxDateTime::Nov
;
103 static const int JDN_0_DAY
= 24;
105 // the constants used for JDN calculations
106 static const int JDN_OFFSET
= 32046;
107 static const int DAYS_PER_5_MONTHS
= 153;
108 static const int DAYS_PER_4_YEARS
= 1461;
109 static const int DAYS_PER_400_YEARS
= 146097;
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 // a critical section is needed to protect GetTimeZone() static
116 // variable in MT case
118 wxCriticalSection gs_critsectTimezone
;
119 #endif // wxUSE_THREADS
121 // ----------------------------------------------------------------------------
123 // ----------------------------------------------------------------------------
125 // get the number of days in the given month of the given year
127 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
129 // the number of days in month in Julian/Gregorian calendar: the first line
130 // is for normal years, the second one is for the leap ones
131 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
133 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
134 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
137 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
140 // ensure that the timezone variable is set by calling localtime
141 static int GetTimeZone()
143 // set to TRUE when the timezone is set
144 static bool s_timezoneSet
= FALSE
;
146 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
148 if ( !s_timezoneSet
)
150 // just call localtime() instead of figuring out whether this system
151 // supports tzset(), _tzset() or something else
155 s_timezoneSet
= TRUE
;
158 return (int)WX_TIMEZONE
;
161 // return the integral part of the JDN for the midnight of the given date (to
162 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
163 // noon of the previous day)
164 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
165 wxDateTime::Month mon
,
168 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
170 // check the date validity
172 (year
> JDN_0_YEAR
) ||
173 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
174 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
175 _T("date out of range - can't convert to JDN")
178 // make the year positive to avoid problems with negative numbers division
181 // months are counted from March here
183 if ( mon
>= wxDateTime::Mar
)
193 // now we can simply add all the contributions together
194 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
195 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
196 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
201 // this function is a wrapper around strftime(3)
202 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
205 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
207 // is ti really possible that 1024 is too short?
208 wxFAIL_MSG(_T("strftime() failed"));
211 return wxString(buf
);
214 // if year and/or month have invalid values, replace them with the current ones
215 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
216 wxDateTime::Month
*month
)
218 struct tm
*tmNow
= NULL
;
220 if ( *year
== wxDateTime::Inv_Year
)
222 tmNow
= wxDateTime::GetTmNow();
224 *year
= 1900 + tmNow
->tm_year
;
227 if ( *month
== wxDateTime::Inv_Month
)
230 tmNow
= wxDateTime::GetTmNow();
232 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
236 // ============================================================================
237 // implementation of wxDateTime
238 // ============================================================================
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
245 wxDateTime
wxDateTime::ms_InvDateTime
;
247 // ----------------------------------------------------------------------------
249 // ----------------------------------------------------------------------------
253 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
254 mon
= wxDateTime::Inv_Month
;
256 hour
= min
= sec
= msec
= 0;
257 wday
= wxDateTime::Inv_WeekDay
;
260 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
268 mon
= (wxDateTime::Month
)tm
.tm_mon
;
269 year
= 1900 + tm
.tm_year
;
274 bool wxDateTime::Tm::IsValid() const
276 // we allow for the leap seconds, although we don't use them (yet)
277 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
278 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
279 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
282 void wxDateTime::Tm::ComputeWeekDay()
284 // compute the week day from day/month/year: we use the dumbest algorithm
285 // possible: just compute our JDN and then use the (simple to derive)
286 // formula: weekday = (JDN + 1.5) % 7
287 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
290 void wxDateTime::Tm::AddMonths(int monDiff
)
292 // normalize the months field
293 while ( monDiff
< -mon
)
297 monDiff
+= MONTHS_IN_YEAR
;
300 while ( monDiff
+ mon
> MONTHS_IN_YEAR
)
304 monDiff
-= MONTHS_IN_YEAR
;
307 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
309 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
312 void wxDateTime::Tm::AddDays(int dayDiff
)
314 // normalize the days field
320 mday
+= GetNumOfDaysInMonth(year
, mon
);
323 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
325 mday
-= GetNumOfDaysInMonth(year
, mon
);
330 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
334 // ----------------------------------------------------------------------------
336 // ----------------------------------------------------------------------------
338 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
342 case wxDateTime::Local
:
343 // get the offset from C RTL: it returns the difference GMT-local
344 // while we want to have the offset _from_ GMT, hence the '-'
345 m_offset
= -GetTimeZone();
348 case wxDateTime::GMT_12
:
349 case wxDateTime::GMT_11
:
350 case wxDateTime::GMT_10
:
351 case wxDateTime::GMT_9
:
352 case wxDateTime::GMT_8
:
353 case wxDateTime::GMT_7
:
354 case wxDateTime::GMT_6
:
355 case wxDateTime::GMT_5
:
356 case wxDateTime::GMT_4
:
357 case wxDateTime::GMT_3
:
358 case wxDateTime::GMT_2
:
359 case wxDateTime::GMT_1
:
360 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
363 case wxDateTime::GMT0
:
364 case wxDateTime::GMT1
:
365 case wxDateTime::GMT2
:
366 case wxDateTime::GMT3
:
367 case wxDateTime::GMT4
:
368 case wxDateTime::GMT5
:
369 case wxDateTime::GMT6
:
370 case wxDateTime::GMT7
:
371 case wxDateTime::GMT8
:
372 case wxDateTime::GMT9
:
373 case wxDateTime::GMT10
:
374 case wxDateTime::GMT11
:
375 case wxDateTime::GMT12
:
376 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
379 case wxDateTime::A_CST
:
380 // Central Standard Time in use in Australia = UTC + 9.5
381 m_offset
= 60*(9*60 + 30);
385 wxFAIL_MSG( _T("unknown time zone") );
389 // ----------------------------------------------------------------------------
391 // ----------------------------------------------------------------------------
394 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
396 if ( year
== Inv_Year
)
397 year
= GetCurrentYear();
399 if ( cal
== Gregorian
)
401 // in Gregorian calendar leap years are those divisible by 4 except
402 // those divisible by 100 unless they're also divisible by 400
403 // (in some countries, like Russia and Greece, additional corrections
404 // exist, but they won't manifest themselves until 2700)
405 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
407 else if ( cal
== Julian
)
409 // in Julian calendar the rule is simpler
410 return year
% 4 == 0;
414 wxFAIL_MSG(_T("unknown calendar"));
421 int wxDateTime::GetCentury(int year
)
423 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
427 int wxDateTime::ConvertYearToBC(int year
)
430 return year
> 0 ? year
: year
- 1;
434 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
439 return Now().GetYear();
442 wxFAIL_MSG(_T("TODO"));
446 wxFAIL_MSG(_T("unsupported calendar"));
454 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
459 return Now().GetMonth();
463 wxFAIL_MSG(_T("TODO"));
467 wxFAIL_MSG(_T("unsupported calendar"));
475 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
477 if ( year
== Inv_Year
)
479 // take the current year if none given
480 year
= GetCurrentYear();
487 return IsLeapYear(year
) ? 366 : 365;
491 wxFAIL_MSG(_T("unsupported calendar"));
499 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
501 wxDateTime::Calendar cal
)
503 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
505 if ( cal
== Gregorian
|| cal
== Julian
)
507 if ( year
== Inv_Year
)
509 // take the current year if none given
510 year
= GetCurrentYear();
513 return GetNumOfDaysInMonth(year
, month
);
517 wxFAIL_MSG(_T("unsupported calendar"));
524 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
, bool abbr
)
526 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
528 tm tm
= { 0, 0, 0, 1, month
, 76 }; // any year will do
530 return CallStrftime(abbr
? _T("%b") : _T("%B"), &tm
);
534 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
, bool abbr
)
536 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
538 // take some arbitrary Sunday
539 tm tm
= { 0, 0, 0, 28, Nov
, 99 };
541 // and offset it by the number of days needed to get the correct wday
544 // call mktime() to normalize it...
547 // ... and call strftime()
548 return CallStrftime(abbr
? _T("%a") : _T("%A"), &tm
);
551 // ----------------------------------------------------------------------------
552 // Country stuff: date calculations depend on the country (DST, work days,
553 // ...), so we need to know which rules to follow.
554 // ----------------------------------------------------------------------------
557 wxDateTime::Country
wxDateTime::GetCountry()
559 if ( ms_country
== Country_Unknown
)
561 // try to guess from the time zone name
562 time_t t
= time(NULL
);
563 struct tm
*tm
= localtime(&t
);
565 wxString tz
= CallStrftime(_T("%Z"), tm
);
566 if ( tz
== _T("WET") || tz
== _T("WEST") )
570 else if ( tz
== _T("CET") || tz
== _T("CEST") )
572 ms_country
= Country_EEC
;
574 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
578 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
579 tz
== _T("EST") || tz
== _T("EDT") ||
580 tz
== _T("CST") || tz
== _T("CDT") ||
581 tz
== _T("MST") || tz
== _T("MDT") ||
582 tz
== _T("PST") || tz
== _T("PDT") )
588 // well, choose a default one
597 void wxDateTime::SetCountry(wxDateTime::Country country
)
599 ms_country
= country
;
603 bool wxDateTime::IsWestEuropeanCountry(Country country
)
605 if ( country
== Country_Default
)
607 country
= GetCountry();
610 return (Country_WesternEurope_Start
<= country
) &&
611 (country
<= Country_WesternEurope_End
);
614 // ----------------------------------------------------------------------------
615 // DST calculations: we use 3 different rules for the West European countries,
616 // USA and for the rest of the world. This is undoubtedly false for many
617 // countries, but I lack the necessary info (and the time to gather it),
618 // please add the other rules here!
619 // ----------------------------------------------------------------------------
622 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
624 if ( year
== Inv_Year
)
626 // take the current year if none given
627 year
= GetCurrentYear();
630 if ( country
== Country_Default
)
632 country
= GetCountry();
639 // DST was first observed in the US and UK during WWI, reused
640 // during WWII and used again since 1966
641 return year
>= 1966 ||
642 (year
>= 1942 && year
<= 1945) ||
643 (year
== 1918 || year
== 1919);
646 // assume that it started after WWII
652 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
654 if ( year
== Inv_Year
)
656 // take the current year if none given
657 year
= GetCurrentYear();
660 if ( country
== Country_Default
)
662 country
= GetCountry();
665 if ( !IsDSTApplicable(year
, country
) )
667 return ms_InvDateTime
;
672 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
674 // DST begins at 1 a.m. GMT on the last Sunday of March
675 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
678 wxFAIL_MSG( _T("no last Sunday in March?") );
681 dt
+= wxTimeSpan::Hours(1);
685 else switch ( country
)
692 // don't know for sure - assume it was in effect all year
697 dt
.Set(1, Jan
, year
);
701 // DST was installed Feb 2, 1942 by the Congress
702 dt
.Set(2, Feb
, year
);
705 // Oil embargo changed the DST period in the US
707 dt
.Set(6, Jan
, 1974);
711 dt
.Set(23, Feb
, 1975);
715 // before 1986, DST begun on the last Sunday of April, but
716 // in 1986 Reagan changed it to begin at 2 a.m. of the
717 // first Sunday in April
720 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
723 wxFAIL_MSG( _T("no first Sunday in April?") );
728 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
731 wxFAIL_MSG( _T("no first Sunday in April?") );
735 dt
+= wxTimeSpan::Hours(2);
737 // TODO what about timezone??
743 // assume Mar 30 as the start of the DST for the rest of the world
744 // - totally bogus, of course
745 dt
.Set(30, Mar
, year
);
752 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
754 if ( year
== Inv_Year
)
756 // take the current year if none given
757 year
= GetCurrentYear();
760 if ( country
== Country_Default
)
762 country
= GetCountry();
765 if ( !IsDSTApplicable(year
, country
) )
767 return ms_InvDateTime
;
772 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
774 // DST ends at 1 a.m. GMT on the last Sunday of October
775 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
777 // weirder and weirder...
778 wxFAIL_MSG( _T("no last Sunday in October?") );
781 dt
+= wxTimeSpan::Hours(1);
785 else switch ( country
)
792 // don't know for sure - assume it was in effect all year
796 dt
.Set(31, Dec
, year
);
800 // the time was reset after the end of the WWII
801 dt
.Set(30, Sep
, year
);
805 // DST ends at 2 a.m. on the last Sunday of October
806 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
808 // weirder and weirder...
809 wxFAIL_MSG( _T("no last Sunday in October?") );
812 dt
+= wxTimeSpan::Hours(2);
814 // TODO what about timezone??
819 // assume October 26th as the end of the DST - totally bogus too
820 dt
.Set(26, Oct
, year
);
826 // ----------------------------------------------------------------------------
827 // constructors and assignment operators
828 // ----------------------------------------------------------------------------
830 // the values in the tm structure contain the local time
831 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
833 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
836 time_t timet
= mktime(&tm2
);
838 if ( timet
== (time_t)-1 )
840 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
841 // less than timezone - try to make it work for this case
842 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
844 // add timezone to make sure that date is in range
845 tm2
.tm_sec
-= GetTimeZone();
847 timet
= mktime(&tm2
);
848 if ( timet
!= (time_t)-1 )
850 timet
+= GetTimeZone();
856 wxFAIL_MSG( _T("mktime() failed") );
858 return ms_InvDateTime
;
866 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
869 wxDateTime_t millisec
)
871 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
873 // we allow seconds to be 61 to account for the leap seconds, even if we
874 // don't use them really
875 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
877 _T("Invalid time in wxDateTime::Set()") );
879 // get the current date from system
880 time_t timet
= GetTimeNow();
881 struct tm
*tm
= localtime(&timet
);
883 wxCHECK_MSG( tm
, ms_InvDateTime
, _T("localtime() failed") );
892 // and finally adjust milliseconds
893 return SetMillisecond(millisec
);
896 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
902 wxDateTime_t millisec
)
904 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
906 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
908 _T("Invalid time in wxDateTime::Set()") );
910 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
912 wxCHECK_MSG( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
914 _T("Invalid date in wxDateTime::Set()") );
916 // the range of time_t type (inclusive)
917 static const int yearMinInRange
= 1970;
918 static const int yearMaxInRange
= 2037;
920 // test only the year instead of testing for the exact end of the Unix
921 // time_t range - it doesn't bring anything to do more precise checks
922 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
924 // use the standard library version if the date is in range - this is
925 // probably more efficient than our code
927 tm
.tm_year
= year
- 1900;
933 tm
.tm_isdst
= -1; // mktime() will guess it
937 // and finally adjust milliseconds
938 return SetMillisecond(millisec
);
942 // do time calculations ourselves: we want to calculate the number of
943 // milliseconds between the given date and the epoch
945 // get the JDN for the midnight of this day
946 m_time
= GetTruncatedJDN(day
, month
, year
);
948 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
950 // JDN corresponds to GMT, we take localtime
951 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
957 wxDateTime
& wxDateTime::Set(double jdn
)
959 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
961 jdn
-= EPOCH_JDN
+ 0.5;
964 m_time
*= MILLISECONDS_PER_DAY
;
969 // ----------------------------------------------------------------------------
970 // time_t <-> broken down time conversions
971 // ----------------------------------------------------------------------------
973 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
975 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
977 time_t time
= GetTicks();
978 if ( time
!= (time_t)-1 )
980 // use C RTL functions
982 if ( tz
.GetOffset() == -GetTimeZone() )
984 // we are working with local time
985 tm
= localtime(&time
);
987 // should never happen
988 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
992 time
+= tz
.GetOffset();
997 // should never happen
998 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1002 tm
= (struct tm
*)NULL
;
1010 //else: use generic code below
1013 // remember the time and do the calculations with the date only - this
1014 // eliminates rounding errors of the floating point arithmetics
1016 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1018 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1020 // we want to always have positive time and timeMidnight to be really
1021 // the midnight before it
1024 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1027 timeMidnight
-= timeOnly
;
1029 // calculate the Gregorian date from JDN for the midnight of our date:
1030 // this will yield day, month (in 1..12 range) and year
1032 // actually, this is the JDN for the noon of the previous day
1033 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1035 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1037 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1039 // calculate the century
1040 int temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1041 int century
= temp
/ DAYS_PER_400_YEARS
;
1043 // then the year and day of year (1 <= dayOfYear <= 366)
1044 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1045 int year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1046 int dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1048 // and finally the month and day of the month
1049 temp
= dayOfYear
* 5 - 3;
1050 int month
= temp
/ DAYS_PER_5_MONTHS
;
1051 int day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1053 // month is counted from March - convert to normal
1064 // year is offset by 4800
1067 // check that the algorithm gave us something reasonable
1068 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1069 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1070 wxASSERT_MSG( (INT_MIN
<= year
) && (year
<= INT_MAX
),
1071 _T("year range overflow") );
1073 // construct Tm from these values
1075 tm
.year
= (int)year
;
1076 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1077 tm
.mday
= (wxDateTime_t
)day
;
1078 tm
.msec
= timeOnly
% 1000;
1079 timeOnly
-= tm
.msec
;
1080 timeOnly
/= 1000; // now we have time in seconds
1082 tm
.sec
= timeOnly
% 60;
1084 timeOnly
/= 60; // now we have time in minutes
1086 tm
.min
= timeOnly
% 60;
1089 tm
.hour
= timeOnly
/ 60;
1094 wxDateTime
& wxDateTime::SetYear(int year
)
1096 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1105 wxDateTime
& wxDateTime::SetMonth(Month month
)
1107 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1116 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1118 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1127 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1129 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1138 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1140 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1149 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1151 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1160 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1162 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1164 // we don't need to use GetTm() for this one
1165 m_time
-= m_time
% 1000l;
1166 m_time
+= millisecond
;
1171 // ----------------------------------------------------------------------------
1172 // wxDateTime arithmetics
1173 // ----------------------------------------------------------------------------
1175 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1179 tm
.year
+= diff
.GetYears();
1180 tm
.AddMonths(diff
.GetMonths());
1181 tm
.AddDays(diff
.GetTotalDays());
1188 // ----------------------------------------------------------------------------
1189 // Weekday and monthday stuff
1190 // ----------------------------------------------------------------------------
1192 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1195 // take the current month/year if none specified
1196 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1198 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1201 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1206 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1208 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1209 // anyhow in such case - but may be should still give an assert for it?
1211 // take the current month/year if none specified
1212 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1216 // TODO this probably could be optimised somehow...
1220 // get the first day of the month
1221 dt
.Set(1, month
, year
);
1224 WeekDay wdayFirst
= dt
.GetWeekDay();
1226 // go to the first weekday of the month
1227 int diff
= weekday
- wdayFirst
;
1231 // add advance n-1 weeks more
1234 dt
+= wxDateSpan::Days(diff
);
1236 else // count from the end of the month
1238 // get the last day of the month
1239 dt
.SetToLastMonthDay(month
, year
);
1242 WeekDay wdayLast
= dt
.GetWeekDay();
1244 // go to the last weekday of the month
1245 int diff
= wdayLast
- weekday
;
1249 // and rewind n-1 weeks from there
1252 dt
-= wxDateSpan::Days(diff
);
1255 // check that it is still in the same month
1256 if ( dt
.GetMonth() == month
)
1264 // no such day in this month
1269 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1271 // this array contains the cumulated number of days in all previous months
1272 // for normal and leap years
1273 static const wxDateTime_t cumulatedDays
[2][MONTHS_IN_YEAR
] =
1275 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
1276 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
1281 return cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1284 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(const TimeZone
& tz
) const
1286 // the first week of the year is the one which contains Jan, 4 (according
1287 // to ISO standard rule), so the year day N0 = 4 + 7*W always lies in the
1288 // week W+1. As any day N = 7*W + 4 + (N - 4)%7, it lies in the same week
1289 // as N0 or in the next one.
1291 // TODO this surely may be optimized - I got confused while writing it
1293 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1295 // the week day of the day lying in the first week
1296 WeekDay wdayStart
= wxDateTime(4, Jan
, GetYear()).GetWeekDay();
1298 wxDateTime_t week
= (nDayInYear
- 4) / 7 + 1;
1300 // notice that Sunday shoould be counted as 7, not 0 here!
1301 if ( ((nDayInYear
- 4) % 7) + (!wdayStart
? 7 : wdayStart
) > 7 )
1309 // ----------------------------------------------------------------------------
1310 // Julian day number conversion and related stuff
1311 // ----------------------------------------------------------------------------
1313 double wxDateTime::GetJulianDayNumber() const
1315 // JDN are always expressed for the GMT dates
1316 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1318 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1320 // add the part GetTruncatedJDN() neglected
1323 // and now add the time: 86400 sec = 1 JDN
1324 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1327 double wxDateTime::GetRataDie() const
1329 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1330 return GetJulianDayNumber() - 1721119.5 - 306;
1333 // ----------------------------------------------------------------------------
1334 // timezone and DST stuff
1335 // ----------------------------------------------------------------------------
1337 int wxDateTime::IsDST(wxDateTime::Country country
) const
1339 wxCHECK_MSG( country
== Country_Default
, -1,
1340 _T("country support not implemented") );
1342 // use the C RTL for the dates in the standard range
1343 time_t timet
= GetTicks();
1344 if ( timet
!= (time_t)-1 )
1346 tm
*tm
= localtime(&timet
);
1348 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1350 return tm
->tm_isdst
;
1354 int year
= GetYear();
1356 if ( !IsDSTApplicable(year
, country
) )
1358 // no DST time in this year in this country
1362 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1366 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
)
1368 int secDiff
= GetTimeZone() + tz
.GetOffset();
1370 // we need to know whether DST is or not in effect for this date
1373 // FIXME we assume that the DST is always shifted by 1 hour
1377 return Substract(wxTimeSpan::Seconds(secDiff
));
1380 // ----------------------------------------------------------------------------
1381 // wxDateTime to/from text representations
1382 // ----------------------------------------------------------------------------
1384 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1386 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1388 time_t time
= GetTicks();
1389 if ( time
!= (time_t)-1 )
1393 if ( tz
.GetOffset() == -GetTimeZone() )
1395 // we are working with local time
1396 tm
= localtime(&time
);
1398 // should never happen
1399 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1403 time
+= tz
.GetOffset();
1409 // should never happen
1410 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1414 tm
= (struct tm
*)NULL
;
1420 return CallStrftime(format
, tm
);
1422 //else: use generic code below
1425 // use a hack and still use strftime(): first find the YEAR which is a year
1426 // in the strftime() range (1970 - 2038) whose Jan 1 falls on the same week
1427 // day as the Jan 1 of the real year. Then make a copy of the format and
1428 // replace all occurences of YEAR in it with some unique string not
1429 // appearing anywhere else in it, then use strftime() to format the date in
1430 // year YEAR and then replace YEAR back by the real year and the unique
1431 // replacement string back with YEAR. Notice that "all occurences of YEAR"
1432 // means all occurences of 4 digit as well as 2 digit form!
1434 // NB: may be it would be simpler to "honestly" reimplement strftime()?
1436 // find the YEAR: normally, for any year X, Jan 1 or the year X + 28 is the
1437 // same weekday as Jan 1 of X (because the weekday advances by 1 for each
1438 // normal X and by 2 for each leap X, hence by 5 every 4 years or by 35
1439 // which is 0 mod 7 every 28 years) but this rule breaks down if there are
1440 // years between X and Y which are divisible by 4 but not leap (i.e.
1441 // divisible by 100 but not 400), hence the correction.
1443 int yearReal
= GetYear(tz
);
1444 int year
= 1970 + yearReal
% 28;
1446 int nCenturiesInBetween
= (year
/ 100) - (yearReal
/ 100);
1447 int nLostWeekDays
= nCenturiesInBetween
- (nCenturiesInBetween
/ 400);
1449 // we have to gain back the "lost" weekdays...
1450 while ( (nLostWeekDays
% 7) != 0 )
1452 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
1455 // at any rate, we can't go further than 1997 + 28!
1456 wxASSERT_MSG( year
< 2030, _T("logic error in wxDateTime::Format") );
1458 wxString strYear
, strYear2
;
1459 strYear
.Printf(_T("%d"), year
);
1460 strYear2
.Printf(_T("%d"), year
% 100);
1462 // find two strings not occuring in format (this is surely not optimal way
1463 // of doing it... improvements welcome!)
1464 wxString fmt
= format
;
1465 wxString replacement
= (wxChar
)-1;
1466 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1468 replacement
<< (wxChar
)-1;
1471 wxString replacement2
= (wxChar
)-2;
1472 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1474 replacement
<< (wxChar
)-2;
1477 // replace all occurences of year with it
1478 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
1480 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
1482 // use strftime() to format the same date but in supported year
1483 wxDateTime
dt(*this);
1485 wxString str
= dt
.Format(format
, tz
);
1487 // now replace the occurence of 1999 with the real year
1488 wxString strYearReal
, strYearReal2
;
1489 strYearReal
.Printf(_T("%04d"), yearReal
);
1490 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
1491 str
.Replace(strYear
, strYearReal
);
1492 str
.Replace(strYear2
, strYearReal2
);
1494 // and replace back all occurences of replacement string
1497 str
.Replace(replacement2
, strYear2
);
1498 str
.Replace(replacement
, strYear
);
1504 // ============================================================================
1506 // ============================================================================
1508 // not all strftime(3) format specifiers make sense here because, for example,
1509 // a time span doesn't have a year nor a timezone
1511 // Here are the ones which are supported (all of them are supported by strftime
1513 // %H hour in 24 hour format
1514 // %M minute (00 - 59)
1515 // %S second (00 - 59)
1518 // Also, for MFC CTimeSpan compatibility, we support
1519 // %D number of days
1521 // And, to be better than MFC :-), we also have
1522 // %E number of wEeks
1523 // %l milliseconds (000 - 999)
1524 wxString
wxTimeSpan::Format(const wxChar
*format
) const
1526 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
1529 str
.Alloc(strlen(format
));
1531 for ( const wxChar
*pch
= format
; pch
; pch
++ )
1543 wxFAIL_MSG( _T("invalid format character") );
1547 // will get to str << ch below
1551 tmp
.Printf(_T("%d"), GetDays());
1555 tmp
.Printf(_T("%d"), GetWeeks());
1559 tmp
.Printf(_T("%02d"), GetHours());
1563 tmp
.Printf(_T("%03d"), GetMilliseconds().GetValue());
1567 tmp
.Printf(_T("%02d"), GetMinutes());
1571 tmp
.Printf(_T("%02d"), GetSeconds().GetValue());
1579 // skip str += ch below