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 // Is this right? Just a guess. (JACS)
84 #define timezone _timezone
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
92 static const int MONTHS_IN_YEAR
= 12;
94 static const int SECONDS_IN_MINUTE
= 60;
96 static const long SECONDS_PER_DAY
= 86400l;
98 static const long MILLISECONDS_PER_DAY
= 86400000l;
100 // this is the integral part of JDN of the midnight of Jan 1, 1970
101 // (i.e. JDN(Jan 1, 1970) = 2440587.5)
102 static const int EPOCH_JDN
= 2440587;
104 // the date of JDN -0.5 (as we don't work with fractional parts, this is the
105 // reference date for us) is Nov 24, 4714BC
106 static const int JDN_0_YEAR
= -4713;
107 static const int JDN_0_MONTH
= wxDateTime::Nov
;
108 static const int JDN_0_DAY
= 24;
110 // the constants used for JDN calculations
111 static const int JDN_OFFSET
= 32046;
112 static const int DAYS_PER_5_MONTHS
= 153;
113 static const int DAYS_PER_4_YEARS
= 1461;
114 static const int DAYS_PER_400_YEARS
= 146097;
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 // a critical section is needed to protect GetTimeZone() static
121 // variable in MT case
123 wxCriticalSection gs_critsectTimezone
;
124 #endif // wxUSE_THREADS
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 // get the number of days in the given month of the given year
132 wxDateTime::wxDateTime_t
GetNumOfDaysInMonth(int year
, wxDateTime::Month month
)
134 // the number of days in month in Julian/Gregorian calendar: the first line
135 // is for normal years, the second one is for the leap ones
136 static wxDateTime::wxDateTime_t daysInMonth
[2][MONTHS_IN_YEAR
] =
138 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
139 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
142 return daysInMonth
[wxDateTime::IsLeapYear(year
)][month
];
145 // ensure that the timezone variable is set by calling localtime
146 static int GetTimeZone()
148 // set to TRUE when the timezone is set
149 static bool s_timezoneSet
= FALSE
;
151 wxCRIT_SECT_LOCKER(lock
, gs_critsectTimezone
);
153 if ( !s_timezoneSet
)
155 // just call localtime() instead of figuring out whether this system
156 // supports tzset(), _tzset() or something else
160 s_timezoneSet
= TRUE
;
163 return (int)WX_TIMEZONE
;
166 // return the integral part of the JDN for the midnight of the given date (to
167 // get the real JDN you need to add 0.5, this is, in fact, JDN of the
168 // noon of the previous day)
169 static long GetTruncatedJDN(wxDateTime::wxDateTime_t day
,
170 wxDateTime::Month mon
,
173 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
175 // check the date validity
177 (year
> JDN_0_YEAR
) ||
178 ((year
== JDN_0_YEAR
) && (mon
> JDN_0_MONTH
)) ||
179 ((year
== JDN_0_YEAR
) && (mon
== JDN_0_MONTH
) && (day
>= JDN_0_DAY
)),
180 _T("date out of range - can't convert to JDN")
183 // make the year positive to avoid problems with negative numbers division
186 // months are counted from March here
188 if ( mon
>= wxDateTime::Mar
)
198 // now we can simply add all the contributions together
199 return ((year
/ 100) * DAYS_PER_400_YEARS
) / 4
200 + ((year
% 100) * DAYS_PER_4_YEARS
) / 4
201 + (month
* DAYS_PER_5_MONTHS
+ 2) / 5
206 // this function is a wrapper around strftime(3)
207 static wxString
CallStrftime(const wxChar
*format
, const tm
* tm
)
210 if ( !wxStrftime(buf
, WXSIZEOF(buf
), format
, tm
) )
212 // is ti really possible that 1024 is too short?
213 wxFAIL_MSG(_T("strftime() failed"));
216 return wxString(buf
);
219 // if year and/or month have invalid values, replace them with the current ones
220 static void ReplaceDefaultYearMonthWithCurrent(int *year
,
221 wxDateTime::Month
*month
)
223 struct tm
*tmNow
= NULL
;
225 if ( *year
== wxDateTime::Inv_Year
)
227 tmNow
= wxDateTime::GetTmNow();
229 *year
= 1900 + tmNow
->tm_year
;
232 if ( *month
== wxDateTime::Inv_Month
)
235 tmNow
= wxDateTime::GetTmNow();
237 *month
= (wxDateTime::Month
)tmNow
->tm_mon
;
241 // ============================================================================
242 // implementation of wxDateTime
243 // ============================================================================
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
249 wxDateTime::Country
wxDateTime::ms_country
= wxDateTime::Country_Unknown
;
250 wxDateTime
wxDateTime::ms_InvDateTime
;
252 // ----------------------------------------------------------------------------
254 // ----------------------------------------------------------------------------
258 year
= (wxDateTime_t
)wxDateTime::Inv_Year
;
259 mon
= wxDateTime::Inv_Month
;
261 hour
= min
= sec
= msec
= 0;
262 wday
= wxDateTime::Inv_WeekDay
;
265 wxDateTime::Tm::Tm(const struct tm
& tm
, const TimeZone
& tz
)
273 mon
= (wxDateTime::Month
)tm
.tm_mon
;
274 year
= 1900 + tm
.tm_year
;
279 bool wxDateTime::Tm::IsValid() const
281 // we allow for the leap seconds, although we don't use them (yet)
282 return (year
!= wxDateTime::Inv_Year
) && (mon
!= wxDateTime::Inv_Month
) &&
283 (mday
<= GetNumOfDaysInMonth(year
, mon
)) &&
284 (hour
< 24) && (min
< 60) && (sec
< 62) && (msec
< 1000);
287 void wxDateTime::Tm::ComputeWeekDay()
289 // compute the week day from day/month/year: we use the dumbest algorithm
290 // possible: just compute our JDN and then use the (simple to derive)
291 // formula: weekday = (JDN + 1.5) % 7
292 wday
= (wxDateTime::WeekDay
)(GetTruncatedJDN(mday
, mon
, year
) + 2) % 7;
295 void wxDateTime::Tm::AddMonths(int monDiff
)
297 // normalize the months field
298 while ( monDiff
< -mon
)
302 monDiff
+= MONTHS_IN_YEAR
;
305 while ( monDiff
+ mon
> MONTHS_IN_YEAR
)
309 monDiff
-= MONTHS_IN_YEAR
;
312 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
314 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
317 void wxDateTime::Tm::AddDays(int dayDiff
)
319 // normalize the days field
325 mday
+= GetNumOfDaysInMonth(year
, mon
);
328 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
330 mday
-= GetNumOfDaysInMonth(year
, mon
);
335 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
339 // ----------------------------------------------------------------------------
341 // ----------------------------------------------------------------------------
343 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
347 case wxDateTime::Local
:
348 // get the offset from C RTL: it returns the difference GMT-local
349 // while we want to have the offset _from_ GMT, hence the '-'
350 m_offset
= -GetTimeZone();
353 case wxDateTime::GMT_12
:
354 case wxDateTime::GMT_11
:
355 case wxDateTime::GMT_10
:
356 case wxDateTime::GMT_9
:
357 case wxDateTime::GMT_8
:
358 case wxDateTime::GMT_7
:
359 case wxDateTime::GMT_6
:
360 case wxDateTime::GMT_5
:
361 case wxDateTime::GMT_4
:
362 case wxDateTime::GMT_3
:
363 case wxDateTime::GMT_2
:
364 case wxDateTime::GMT_1
:
365 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
368 case wxDateTime::GMT0
:
369 case wxDateTime::GMT1
:
370 case wxDateTime::GMT2
:
371 case wxDateTime::GMT3
:
372 case wxDateTime::GMT4
:
373 case wxDateTime::GMT5
:
374 case wxDateTime::GMT6
:
375 case wxDateTime::GMT7
:
376 case wxDateTime::GMT8
:
377 case wxDateTime::GMT9
:
378 case wxDateTime::GMT10
:
379 case wxDateTime::GMT11
:
380 case wxDateTime::GMT12
:
381 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
384 case wxDateTime::A_CST
:
385 // Central Standard Time in use in Australia = UTC + 9.5
386 m_offset
= 60*(9*60 + 30);
390 wxFAIL_MSG( _T("unknown time zone") );
394 // ----------------------------------------------------------------------------
396 // ----------------------------------------------------------------------------
399 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
401 if ( year
== Inv_Year
)
402 year
= GetCurrentYear();
404 if ( cal
== Gregorian
)
406 // in Gregorian calendar leap years are those divisible by 4 except
407 // those divisible by 100 unless they're also divisible by 400
408 // (in some countries, like Russia and Greece, additional corrections
409 // exist, but they won't manifest themselves until 2700)
410 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
412 else if ( cal
== Julian
)
414 // in Julian calendar the rule is simpler
415 return year
% 4 == 0;
419 wxFAIL_MSG(_T("unknown calendar"));
426 int wxDateTime::GetCentury(int year
)
428 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
432 int wxDateTime::ConvertYearToBC(int year
)
435 return year
> 0 ? year
: year
- 1;
439 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
444 return Now().GetYear();
447 wxFAIL_MSG(_T("TODO"));
451 wxFAIL_MSG(_T("unsupported calendar"));
459 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
464 return Now().GetMonth();
468 wxFAIL_MSG(_T("TODO"));
472 wxFAIL_MSG(_T("unsupported calendar"));
480 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
482 if ( year
== Inv_Year
)
484 // take the current year if none given
485 year
= GetCurrentYear();
492 return IsLeapYear(year
) ? 366 : 365;
496 wxFAIL_MSG(_T("unsupported calendar"));
504 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
506 wxDateTime::Calendar cal
)
508 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
510 if ( cal
== Gregorian
|| cal
== Julian
)
512 if ( year
== Inv_Year
)
514 // take the current year if none given
515 year
= GetCurrentYear();
518 return GetNumOfDaysInMonth(year
, month
);
522 wxFAIL_MSG(_T("unsupported calendar"));
529 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
, bool abbr
)
531 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
533 tm tm
= { 0, 0, 0, 1, month
, 76 }; // any year will do
535 return CallStrftime(abbr
? _T("%b") : _T("%B"), &tm
);
539 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
, bool abbr
)
541 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
543 // take some arbitrary Sunday
544 tm tm
= { 0, 0, 0, 28, Nov
, 99 };
546 // and offset it by the number of days needed to get the correct wday
549 // call mktime() to normalize it...
552 // ... and call strftime()
553 return CallStrftime(abbr
? _T("%a") : _T("%A"), &tm
);
556 // ----------------------------------------------------------------------------
557 // Country stuff: date calculations depend on the country (DST, work days,
558 // ...), so we need to know which rules to follow.
559 // ----------------------------------------------------------------------------
562 wxDateTime::Country
wxDateTime::GetCountry()
564 if ( ms_country
== Country_Unknown
)
566 // try to guess from the time zone name
567 time_t t
= time(NULL
);
568 struct tm
*tm
= localtime(&t
);
570 wxString tz
= CallStrftime(_T("%Z"), tm
);
571 if ( tz
== _T("WET") || tz
== _T("WEST") )
575 else if ( tz
== _T("CET") || tz
== _T("CEST") )
577 ms_country
= Country_EEC
;
579 else if ( tz
== _T("MSK") || tz
== _T("MSD") )
583 else if ( tz
== _T("AST") || tz
== _T("ADT") ||
584 tz
== _T("EST") || tz
== _T("EDT") ||
585 tz
== _T("CST") || tz
== _T("CDT") ||
586 tz
== _T("MST") || tz
== _T("MDT") ||
587 tz
== _T("PST") || tz
== _T("PDT") )
593 // well, choose a default one
602 void wxDateTime::SetCountry(wxDateTime::Country country
)
604 ms_country
= country
;
608 bool wxDateTime::IsWestEuropeanCountry(Country country
)
610 if ( country
== Country_Default
)
612 country
= GetCountry();
615 return (Country_WesternEurope_Start
<= country
) &&
616 (country
<= Country_WesternEurope_End
);
619 // ----------------------------------------------------------------------------
620 // DST calculations: we use 3 different rules for the West European countries,
621 // USA and for the rest of the world. This is undoubtedly false for many
622 // countries, but I lack the necessary info (and the time to gather it),
623 // please add the other rules here!
624 // ----------------------------------------------------------------------------
627 bool wxDateTime::IsDSTApplicable(int year
, Country country
)
629 if ( year
== Inv_Year
)
631 // take the current year if none given
632 year
= GetCurrentYear();
635 if ( country
== Country_Default
)
637 country
= GetCountry();
644 // DST was first observed in the US and UK during WWI, reused
645 // during WWII and used again since 1966
646 return year
>= 1966 ||
647 (year
>= 1942 && year
<= 1945) ||
648 (year
== 1918 || year
== 1919);
651 // assume that it started after WWII
657 wxDateTime
wxDateTime::GetBeginDST(int year
, Country country
)
659 if ( year
== Inv_Year
)
661 // take the current year if none given
662 year
= GetCurrentYear();
665 if ( country
== Country_Default
)
667 country
= GetCountry();
670 if ( !IsDSTApplicable(year
, country
) )
672 return ms_InvDateTime
;
677 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
679 // DST begins at 1 a.m. GMT on the last Sunday of March
680 if ( !dt
.SetToLastWeekDay(Sun
, Mar
, year
) )
683 wxFAIL_MSG( _T("no last Sunday in March?") );
686 dt
+= wxTimeSpan::Hours(1);
690 else switch ( country
)
697 // don't know for sure - assume it was in effect all year
702 dt
.Set(1, Jan
, year
);
706 // DST was installed Feb 2, 1942 by the Congress
707 dt
.Set(2, Feb
, year
);
710 // Oil embargo changed the DST period in the US
712 dt
.Set(6, Jan
, 1974);
716 dt
.Set(23, Feb
, 1975);
720 // before 1986, DST begun on the last Sunday of April, but
721 // in 1986 Reagan changed it to begin at 2 a.m. of the
722 // first Sunday in April
725 if ( !dt
.SetToLastWeekDay(Sun
, Apr
, year
) )
728 wxFAIL_MSG( _T("no first Sunday in April?") );
733 if ( !dt
.SetToWeekDay(Sun
, 1, Apr
, year
) )
736 wxFAIL_MSG( _T("no first Sunday in April?") );
740 dt
+= wxTimeSpan::Hours(2);
742 // TODO what about timezone??
748 // assume Mar 30 as the start of the DST for the rest of the world
749 // - totally bogus, of course
750 dt
.Set(30, Mar
, year
);
757 wxDateTime
wxDateTime::GetEndDST(int year
, Country country
)
759 if ( year
== Inv_Year
)
761 // take the current year if none given
762 year
= GetCurrentYear();
765 if ( country
== Country_Default
)
767 country
= GetCountry();
770 if ( !IsDSTApplicable(year
, country
) )
772 return ms_InvDateTime
;
777 if ( IsWestEuropeanCountry(country
) || (country
== Russia
) )
779 // DST ends at 1 a.m. GMT on the last Sunday of October
780 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
782 // weirder and weirder...
783 wxFAIL_MSG( _T("no last Sunday in October?") );
786 dt
+= wxTimeSpan::Hours(1);
790 else switch ( country
)
797 // don't know for sure - assume it was in effect all year
801 dt
.Set(31, Dec
, year
);
805 // the time was reset after the end of the WWII
806 dt
.Set(30, Sep
, year
);
810 // DST ends at 2 a.m. on the last Sunday of October
811 if ( !dt
.SetToLastWeekDay(Sun
, Oct
, year
) )
813 // weirder and weirder...
814 wxFAIL_MSG( _T("no last Sunday in October?") );
817 dt
+= wxTimeSpan::Hours(2);
819 // TODO what about timezone??
824 // assume October 26th as the end of the DST - totally bogus too
825 dt
.Set(26, Oct
, year
);
831 // ----------------------------------------------------------------------------
832 // constructors and assignment operators
833 // ----------------------------------------------------------------------------
835 // the values in the tm structure contain the local time
836 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
838 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
841 time_t timet
= mktime(&tm2
);
843 if ( timet
== (time_t)-1 )
845 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
846 // less than timezone - try to make it work for this case
847 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
849 // add timezone to make sure that date is in range
850 tm2
.tm_sec
-= GetTimeZone();
852 timet
= mktime(&tm2
);
853 if ( timet
!= (time_t)-1 )
855 timet
+= GetTimeZone();
861 wxFAIL_MSG( _T("mktime() failed") );
863 return ms_InvDateTime
;
871 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
874 wxDateTime_t millisec
)
876 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
878 // we allow seconds to be 61 to account for the leap seconds, even if we
879 // don't use them really
880 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
882 _T("Invalid time in wxDateTime::Set()") );
884 // get the current date from system
885 time_t timet
= GetTimeNow();
886 struct tm
*tm
= localtime(&timet
);
888 wxCHECK_MSG( tm
, ms_InvDateTime
, _T("localtime() failed") );
897 // and finally adjust milliseconds
898 return SetMillisecond(millisec
);
901 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
907 wxDateTime_t millisec
)
909 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
911 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
913 _T("Invalid time in wxDateTime::Set()") );
915 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
917 wxCHECK_MSG( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
919 _T("Invalid date in wxDateTime::Set()") );
921 // the range of time_t type (inclusive)
922 static const int yearMinInRange
= 1970;
923 static const int yearMaxInRange
= 2037;
925 // test only the year instead of testing for the exact end of the Unix
926 // time_t range - it doesn't bring anything to do more precise checks
927 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
929 // use the standard library version if the date is in range - this is
930 // probably more efficient than our code
932 tm
.tm_year
= year
- 1900;
938 tm
.tm_isdst
= -1; // mktime() will guess it
942 // and finally adjust milliseconds
943 return SetMillisecond(millisec
);
947 // do time calculations ourselves: we want to calculate the number of
948 // milliseconds between the given date and the epoch
950 // get the JDN for the midnight of this day
951 m_time
= GetTruncatedJDN(day
, month
, year
);
953 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
955 // JDN corresponds to GMT, we take localtime
956 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
962 wxDateTime
& wxDateTime::Set(double jdn
)
964 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
966 jdn
-= EPOCH_JDN
+ 0.5;
969 m_time
*= MILLISECONDS_PER_DAY
;
974 // ----------------------------------------------------------------------------
975 // time_t <-> broken down time conversions
976 // ----------------------------------------------------------------------------
978 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
980 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
982 time_t time
= GetTicks();
983 if ( time
!= (time_t)-1 )
985 // use C RTL functions
987 if ( tz
.GetOffset() == -GetTimeZone() )
989 // we are working with local time
990 tm
= localtime(&time
);
992 // should never happen
993 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
997 time
+= tz
.GetOffset();
1002 // should never happen
1003 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
1007 tm
= (struct tm
*)NULL
;
1015 //else: use generic code below
1018 // remember the time and do the calculations with the date only - this
1019 // eliminates rounding errors of the floating point arithmetics
1021 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
1023 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
1025 // we want to always have positive time and timeMidnight to be really
1026 // the midnight before it
1029 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
1032 timeMidnight
-= timeOnly
;
1034 // calculate the Gregorian date from JDN for the midnight of our date:
1035 // this will yield day, month (in 1..12 range) and year
1037 // actually, this is the JDN for the noon of the previous day
1038 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
1040 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
1042 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
1044 // calculate the century
1045 int temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
1046 int century
= temp
/ DAYS_PER_400_YEARS
;
1048 // then the year and day of year (1 <= dayOfYear <= 366)
1049 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
1050 int year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
1051 int dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
1053 // and finally the month and day of the month
1054 temp
= dayOfYear
* 5 - 3;
1055 int month
= temp
/ DAYS_PER_5_MONTHS
;
1056 int day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
1058 // month is counted from March - convert to normal
1069 // year is offset by 4800
1072 // check that the algorithm gave us something reasonable
1073 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
1074 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
1075 wxASSERT_MSG( (INT_MIN
<= year
) && (year
<= INT_MAX
),
1076 _T("year range overflow") );
1078 // construct Tm from these values
1080 tm
.year
= (int)year
;
1081 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
1082 tm
.mday
= (wxDateTime_t
)day
;
1083 tm
.msec
= timeOnly
% 1000;
1084 timeOnly
-= tm
.msec
;
1085 timeOnly
/= 1000; // now we have time in seconds
1087 tm
.sec
= timeOnly
% 60;
1089 timeOnly
/= 60; // now we have time in minutes
1091 tm
.min
= timeOnly
% 60;
1094 tm
.hour
= timeOnly
/ 60;
1099 wxDateTime
& wxDateTime::SetYear(int year
)
1101 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1110 wxDateTime
& wxDateTime::SetMonth(Month month
)
1112 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1121 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
1123 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1132 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
1134 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1143 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
1145 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1154 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
1156 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1165 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
1167 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
1169 // we don't need to use GetTm() for this one
1170 m_time
-= m_time
% 1000l;
1171 m_time
+= millisecond
;
1176 // ----------------------------------------------------------------------------
1177 // wxDateTime arithmetics
1178 // ----------------------------------------------------------------------------
1180 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
1184 tm
.year
+= diff
.GetYears();
1185 tm
.AddMonths(diff
.GetMonths());
1186 tm
.AddDays(diff
.GetTotalDays());
1193 // ----------------------------------------------------------------------------
1194 // Weekday and monthday stuff
1195 // ----------------------------------------------------------------------------
1197 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
1200 // take the current month/year if none specified
1201 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1203 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
1206 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
1211 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
1213 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
1214 // anyhow in such case - but may be should still give an assert for it?
1216 // take the current month/year if none specified
1217 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
1221 // TODO this probably could be optimised somehow...
1225 // get the first day of the month
1226 dt
.Set(1, month
, year
);
1229 WeekDay wdayFirst
= dt
.GetWeekDay();
1231 // go to the first weekday of the month
1232 int diff
= weekday
- wdayFirst
;
1236 // add advance n-1 weeks more
1239 dt
+= wxDateSpan::Days(diff
);
1241 else // count from the end of the month
1243 // get the last day of the month
1244 dt
.SetToLastMonthDay(month
, year
);
1247 WeekDay wdayLast
= dt
.GetWeekDay();
1249 // go to the last weekday of the month
1250 int diff
= wdayLast
- weekday
;
1254 // and rewind n-1 weeks from there
1257 dt
-= wxDateSpan::Days(diff
);
1260 // check that it is still in the same month
1261 if ( dt
.GetMonth() == month
)
1269 // no such day in this month
1274 wxDateTime::wxDateTime_t
wxDateTime::GetDayOfYear(const TimeZone
& tz
) const
1276 // this array contains the cumulated number of days in all previous months
1277 // for normal and leap years
1278 static const wxDateTime_t cumulatedDays
[2][MONTHS_IN_YEAR
] =
1280 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
1281 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
1286 return cumulatedDays
[IsLeapYear(tm
.year
)][tm
.mon
] + tm
.mday
;
1289 wxDateTime::wxDateTime_t
wxDateTime::GetWeekOfYear(const TimeZone
& tz
) const
1291 // the first week of the year is the one which contains Jan, 4 (according
1292 // to ISO standard rule), so the year day N0 = 4 + 7*W always lies in the
1293 // week W+1. As any day N = 7*W + 4 + (N - 4)%7, it lies in the same week
1294 // as N0 or in the next one.
1296 // TODO this surely may be optimized - I got confused while writing it
1298 wxDateTime_t nDayInYear
= GetDayOfYear(tz
);
1300 // the week day of the day lying in the first week
1301 WeekDay wdayStart
= wxDateTime(4, Jan
, GetYear()).GetWeekDay();
1303 wxDateTime_t week
= (nDayInYear
- 4) / 7 + 1;
1305 // notice that Sunday shoould be counted as 7, not 0 here!
1306 if ( ((nDayInYear
- 4) % 7) + (!wdayStart
? 7 : wdayStart
) > 7 )
1314 // ----------------------------------------------------------------------------
1315 // Julian day number conversion and related stuff
1316 // ----------------------------------------------------------------------------
1318 double wxDateTime::GetJulianDayNumber() const
1320 // JDN are always expressed for the GMT dates
1321 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1323 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1325 // add the part GetTruncatedJDN() neglected
1328 // and now add the time: 86400 sec = 1 JDN
1329 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1332 double wxDateTime::GetRataDie() const
1334 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1335 return GetJulianDayNumber() - 1721119.5 - 306;
1338 // ----------------------------------------------------------------------------
1339 // timezone and DST stuff
1340 // ----------------------------------------------------------------------------
1342 int wxDateTime::IsDST(wxDateTime::Country country
) const
1344 wxCHECK_MSG( country
== Country_Default
, -1,
1345 _T("country support not implemented") );
1347 // use the C RTL for the dates in the standard range
1348 time_t timet
= GetTicks();
1349 if ( timet
!= (time_t)-1 )
1351 tm
*tm
= localtime(&timet
);
1353 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1355 return tm
->tm_isdst
;
1359 int year
= GetYear();
1361 if ( !IsDSTApplicable(year
, country
) )
1363 // no DST time in this year in this country
1367 return IsBetween(GetBeginDST(year
, country
), GetEndDST(year
, country
));
1371 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
)
1373 int secDiff
= GetTimeZone() + tz
.GetOffset();
1375 // we need to know whether DST is or not in effect for this date
1378 // FIXME we assume that the DST is always shifted by 1 hour
1382 return Substract(wxTimeSpan::Seconds(secDiff
));
1385 // ----------------------------------------------------------------------------
1386 // wxDateTime to/from text representations
1387 // ----------------------------------------------------------------------------
1389 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1391 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1393 time_t time
= GetTicks();
1394 if ( time
!= (time_t)-1 )
1398 if ( tz
.GetOffset() == -GetTimeZone() )
1400 // we are working with local time
1401 tm
= localtime(&time
);
1403 // should never happen
1404 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1408 time
+= tz
.GetOffset();
1414 // should never happen
1415 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1419 tm
= (struct tm
*)NULL
;
1425 return CallStrftime(format
, tm
);
1427 //else: use generic code below
1430 // use a hack and still use strftime(): first find the YEAR which is a year
1431 // in the strftime() range (1970 - 2038) whose Jan 1 falls on the same week
1432 // day as the Jan 1 of the real year. Then make a copy of the format and
1433 // replace all occurences of YEAR in it with some unique string not
1434 // appearing anywhere else in it, then use strftime() to format the date in
1435 // year YEAR and then replace YEAR back by the real year and the unique
1436 // replacement string back with YEAR. Notice that "all occurences of YEAR"
1437 // means all occurences of 4 digit as well as 2 digit form!
1439 // NB: may be it would be simpler to "honestly" reimplement strftime()?
1441 // find the YEAR: normally, for any year X, Jan 1 or the year X + 28 is the
1442 // same weekday as Jan 1 of X (because the weekday advances by 1 for each
1443 // normal X and by 2 for each leap X, hence by 5 every 4 years or by 35
1444 // which is 0 mod 7 every 28 years) but this rule breaks down if there are
1445 // years between X and Y which are divisible by 4 but not leap (i.e.
1446 // divisible by 100 but not 400), hence the correction.
1448 int yearReal
= GetYear(tz
);
1449 int year
= 1970 + yearReal
% 28;
1451 int nCenturiesInBetween
= (year
/ 100) - (yearReal
/ 100);
1452 int nLostWeekDays
= nCenturiesInBetween
- (nCenturiesInBetween
/ 400);
1454 // we have to gain back the "lost" weekdays...
1455 while ( (nLostWeekDays
% 7) != 0 )
1457 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
1460 // at any rate, we can't go further than 1997 + 28!
1461 wxASSERT_MSG( year
< 2030, _T("logic error in wxDateTime::Format") );
1463 wxString strYear
, strYear2
;
1464 strYear
.Printf(_T("%d"), year
);
1465 strYear2
.Printf(_T("%d"), year
% 100);
1467 // find two strings not occuring in format (this is surely not optimal way
1468 // of doing it... improvements welcome!)
1469 wxString fmt
= format
;
1470 wxString replacement
= (wxChar
)-1;
1471 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1473 replacement
<< (wxChar
)-1;
1476 wxString replacement2
= (wxChar
)-2;
1477 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1479 replacement
<< (wxChar
)-2;
1482 // replace all occurences of year with it
1483 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
1485 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
1487 // use strftime() to format the same date but in supported year
1488 wxDateTime
dt(*this);
1490 wxString str
= dt
.Format(format
, tz
);
1492 // now replace the occurence of 1999 with the real year
1493 wxString strYearReal
, strYearReal2
;
1494 strYearReal
.Printf(_T("%04d"), yearReal
);
1495 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
1496 str
.Replace(strYear
, strYearReal
);
1497 str
.Replace(strYear2
, strYearReal2
);
1499 // and replace back all occurences of replacement string
1502 str
.Replace(replacement2
, strYear2
);
1503 str
.Replace(replacement
, strYear
);
1509 // ============================================================================
1511 // ============================================================================
1513 // not all strftime(3) format specifiers make sense here because, for example,
1514 // a time span doesn't have a year nor a timezone
1516 // Here are the ones which are supported (all of them are supported by strftime
1518 // %H hour in 24 hour format
1519 // %M minute (00 - 59)
1520 // %S second (00 - 59)
1523 // Also, for MFC CTimeSpan compatibility, we support
1524 // %D number of days
1526 // And, to be better than MFC :-), we also have
1527 // %E number of wEeks
1528 // %l milliseconds (000 - 999)
1529 wxString
wxTimeSpan::Format(const wxChar
*format
) const
1531 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
1534 str
.Alloc(strlen(format
));
1536 for ( const wxChar
*pch
= format
; pch
; pch
++ )
1548 wxFAIL_MSG( _T("invalid format character") );
1552 // will get to str << ch below
1556 tmp
.Printf(_T("%d"), GetDays());
1560 tmp
.Printf(_T("%d"), GetWeeks());
1564 tmp
.Printf(_T("%02d"), GetHours());
1568 tmp
.Printf(_T("%03d"), GetMilliseconds().GetValue());
1572 tmp
.Printf(_T("%02d"), GetMinutes());
1576 tmp
.Printf(_T("%02d"), GetSeconds().GetValue());
1584 // skip str += ch below