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
)
305 mon
= (wxDateTime::Month
)(mon
+ monDiff
);
307 wxASSERT_MSG( mon
>= 0 && mon
< MONTHS_IN_YEAR
, _T("logic error") );
310 void wxDateTime::Tm::AddDays(int dayDiff
)
312 // normalize the days field
318 mday
+= GetNumOfDaysInMonth(year
, mon
);
321 while ( mday
> GetNumOfDaysInMonth(year
, mon
) )
323 mday
-= GetNumOfDaysInMonth(year
, mon
);
328 wxASSERT_MSG( mday
> 0 && mday
<= GetNumOfDaysInMonth(year
, mon
),
332 // ----------------------------------------------------------------------------
334 // ----------------------------------------------------------------------------
336 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz
)
340 case wxDateTime::Local
:
341 // get the offset from C RTL: it returns the difference GMT-local
342 // while we want to have the offset _from_ GMT, hence the '-'
343 m_offset
= -GetTimeZone();
346 case wxDateTime::GMT_12
:
347 case wxDateTime::GMT_11
:
348 case wxDateTime::GMT_10
:
349 case wxDateTime::GMT_9
:
350 case wxDateTime::GMT_8
:
351 case wxDateTime::GMT_7
:
352 case wxDateTime::GMT_6
:
353 case wxDateTime::GMT_5
:
354 case wxDateTime::GMT_4
:
355 case wxDateTime::GMT_3
:
356 case wxDateTime::GMT_2
:
357 case wxDateTime::GMT_1
:
358 m_offset
= -3600*(wxDateTime::GMT0
- tz
);
361 case wxDateTime::GMT0
:
362 case wxDateTime::GMT1
:
363 case wxDateTime::GMT2
:
364 case wxDateTime::GMT3
:
365 case wxDateTime::GMT4
:
366 case wxDateTime::GMT5
:
367 case wxDateTime::GMT6
:
368 case wxDateTime::GMT7
:
369 case wxDateTime::GMT8
:
370 case wxDateTime::GMT9
:
371 case wxDateTime::GMT10
:
372 case wxDateTime::GMT11
:
373 case wxDateTime::GMT12
:
374 m_offset
= 3600*(tz
- wxDateTime::GMT0
);
377 case wxDateTime::A_CST
:
378 // Central Standard Time in use in Australia = UTC + 9.5
379 m_offset
= 60*(9*60 + 30);
383 wxFAIL_MSG( _T("unknown time zone") );
387 // ----------------------------------------------------------------------------
389 // ----------------------------------------------------------------------------
392 bool wxDateTime::IsLeapYear(int year
, wxDateTime::Calendar cal
)
394 if ( year
== Inv_Year
)
395 year
= GetCurrentYear();
397 if ( cal
== Gregorian
)
399 // in Gregorian calendar leap years are those divisible by 4 except
400 // those divisible by 100 unless they're also divisible by 400
401 // (in some countries, like Russia and Greece, additional corrections
402 // exist, but they won't manifest themselves until 2700)
403 return (year
% 4 == 0) && ((year
% 100 != 0) || (year
% 400 == 0));
405 else if ( cal
== Julian
)
407 // in Julian calendar the rule is simpler
408 return year
% 4 == 0;
412 wxFAIL_MSG(_T("unknown calendar"));
419 int wxDateTime::GetCentury(int year
)
421 return year
> 0 ? year
/ 100 : year
/ 100 - 1;
425 void wxDateTime::SetCountry(wxDateTime::Country country
)
427 ms_country
= country
;
431 int wxDateTime::ConvertYearToBC(int year
)
434 return year
> 0 ? year
: year
- 1;
438 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal
)
443 return Now().GetYear();
446 wxFAIL_MSG(_T("TODO"));
450 wxFAIL_MSG(_T("unsupported calendar"));
458 wxDateTime::Month
wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal
)
463 return Now().GetMonth();
467 wxFAIL_MSG(_T("TODO"));
471 wxFAIL_MSG(_T("unsupported calendar"));
479 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(int year
, Calendar cal
)
481 if ( year
== Inv_Year
)
483 // take the current year if none given
484 year
= GetCurrentYear();
491 return IsLeapYear(year
) ? 366 : 365;
495 wxFAIL_MSG(_T("unsupported calendar"));
503 wxDateTime::wxDateTime_t
wxDateTime::GetNumberOfDays(wxDateTime::Month month
,
505 wxDateTime::Calendar cal
)
507 wxCHECK_MSG( month
< MONTHS_IN_YEAR
, 0, _T("invalid month") );
509 if ( cal
== Gregorian
|| cal
== Julian
)
511 if ( year
== Inv_Year
)
513 // take the current year if none given
514 year
= GetCurrentYear();
517 return GetNumOfDaysInMonth(year
, month
);
521 wxFAIL_MSG(_T("unsupported calendar"));
528 wxString
wxDateTime::GetMonthName(wxDateTime::Month month
, bool abbr
)
530 wxCHECK_MSG( month
!= Inv_Month
, _T(""), _T("invalid month") );
532 tm tm
= { 0, 0, 0, 1, month
, 76 }; // any year will do
534 return CallStrftime(abbr
? _T("%b") : _T("%B"), &tm
);
538 wxString
wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday
, bool abbr
)
540 wxCHECK_MSG( wday
!= Inv_WeekDay
, _T(""), _T("invalid weekday") );
542 // take some arbitrary Sunday
543 tm tm
= { 0, 0, 0, 28, Nov
, 99 };
545 // and offset it by the number of days needed to get the correct wday
548 // call mktime() to normalize it...
551 // ... and call strftime()
552 return CallStrftime(abbr
? _T("%a") : _T("%A"), &tm
);
555 // ----------------------------------------------------------------------------
556 // constructors and assignment operators
557 // ----------------------------------------------------------------------------
559 // the values in the tm structure contain the local time
560 wxDateTime
& wxDateTime::Set(const struct tm
& tm
)
562 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
565 time_t timet
= mktime(&tm2
);
567 if ( timet
== (time_t)-1 )
569 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
570 // less than timezone - try to make it work for this case
571 if ( tm2
.tm_year
== 70 && tm2
.tm_mon
== 0 && tm2
.tm_mday
== 1 )
573 // add timezone to make sure that date is in range
574 tm2
.tm_sec
-= GetTimeZone();
576 timet
= mktime(&tm2
);
577 if ( timet
!= (time_t)-1 )
579 timet
+= GetTimeZone();
585 wxFAIL_MSG( _T("mktime() failed") );
587 return ms_InvDateTime
;
595 wxDateTime
& wxDateTime::Set(wxDateTime_t hour
,
598 wxDateTime_t millisec
)
600 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
602 // we allow seconds to be 61 to account for the leap seconds, even if we
603 // don't use them really
604 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
606 _T("Invalid time in wxDateTime::Set()") );
608 // get the current date from system
609 time_t timet
= GetTimeNow();
610 struct tm
*tm
= localtime(&timet
);
612 wxCHECK_MSG( tm
, ms_InvDateTime
, _T("localtime() failed") );
621 // and finally adjust milliseconds
622 return SetMillisecond(millisec
);
625 wxDateTime
& wxDateTime::Set(wxDateTime_t day
,
631 wxDateTime_t millisec
)
633 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
635 wxCHECK_MSG( hour
< 24 && second
< 62 && minute
< 60 && millisec
< 1000,
637 _T("Invalid time in wxDateTime::Set()") );
639 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
641 wxCHECK_MSG( (0 < day
) && (day
<= GetNumberOfDays(month
, year
)),
643 _T("Invalid date in wxDateTime::Set()") );
645 // the range of time_t type (inclusive)
646 static const int yearMinInRange
= 1970;
647 static const int yearMaxInRange
= 2037;
649 // test only the year instead of testing for the exact end of the Unix
650 // time_t range - it doesn't bring anything to do more precise checks
651 if ( year
>= yearMinInRange
&& year
<= yearMaxInRange
)
653 // use the standard library version if the date is in range - this is
654 // probably more efficient than our code
656 tm
.tm_year
= year
- 1900;
662 tm
.tm_isdst
= -1; // mktime() will guess it
666 // and finally adjust milliseconds
667 return SetMillisecond(millisec
);
671 // do time calculations ourselves: we want to calculate the number of
672 // milliseconds between the given date and the epoch
674 // get the JDN for the midnight of this day
675 m_time
= GetTruncatedJDN(day
, month
, year
);
677 m_time
*= SECONDS_PER_DAY
* TIME_T_FACTOR
;
679 // JDN corresponds to GMT, we take localtime
680 Add(wxTimeSpan(hour
, minute
, second
+ GetTimeZone(), millisec
));
686 wxDateTime
& wxDateTime::Set(double jdn
)
688 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
690 jdn
-= EPOCH_JDN
+ 0.5;
693 m_time
*= MILLISECONDS_PER_DAY
;
698 // ----------------------------------------------------------------------------
699 // time_t <-> broken down time conversions
700 // ----------------------------------------------------------------------------
702 wxDateTime::Tm
wxDateTime::GetTm(const TimeZone
& tz
) const
704 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
706 time_t time
= GetTicks();
707 if ( time
!= (time_t)-1 )
709 // use C RTL functions
711 if ( tz
.GetOffset() == -GetTimeZone() )
713 // we are working with local time
714 tm
= localtime(&time
);
716 // should never happen
717 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
721 time
+= tz
.GetOffset();
726 // should never happen
727 wxCHECK_MSG( tm
, Tm(), _T("gmtime() failed") );
731 tm
= (struct tm
*)NULL
;
739 //else: use generic code below
742 // remember the time and do the calculations with the date only - this
743 // eliminates rounding errors of the floating point arithmetics
745 wxLongLong timeMidnight
= m_time
+ tz
.GetOffset() * 1000;
747 long timeOnly
= (timeMidnight
% MILLISECONDS_PER_DAY
).ToLong();
749 // we want to always have positive time and timeMidnight to be really
750 // the midnight before it
753 timeOnly
= MILLISECONDS_PER_DAY
+ timeOnly
;
756 timeMidnight
-= timeOnly
;
758 // calculate the Gregorian date from JDN for the midnight of our date:
759 // this will yield day, month (in 1..12 range) and year
761 // actually, this is the JDN for the noon of the previous day
762 long jdn
= (timeMidnight
/ MILLISECONDS_PER_DAY
).ToLong() + EPOCH_JDN
;
764 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
766 wxASSERT_MSG( jdn
> -2, _T("JDN out of range") );
768 // calculate the century
769 int temp
= (jdn
+ JDN_OFFSET
) * 4 - 1;
770 int century
= temp
/ DAYS_PER_400_YEARS
;
772 // then the year and day of year (1 <= dayOfYear <= 366)
773 temp
= ((temp
% DAYS_PER_400_YEARS
) / 4) * 4 + 3;
774 int year
= (century
* 100) + (temp
/ DAYS_PER_4_YEARS
);
775 int dayOfYear
= (temp
% DAYS_PER_4_YEARS
) / 4 + 1;
777 // and finally the month and day of the month
778 temp
= dayOfYear
* 5 - 3;
779 int month
= temp
/ DAYS_PER_5_MONTHS
;
780 int day
= (temp
% DAYS_PER_5_MONTHS
) / 5 + 1;
782 // month is counted from March - convert to normal
793 // year is offset by 4800
796 // check that the algorithm gave us something reasonable
797 wxASSERT_MSG( (0 < month
) && (month
<= 12), _T("invalid month") );
798 wxASSERT_MSG( (1 <= day
) && (day
< 32), _T("invalid day") );
799 wxASSERT_MSG( (INT_MIN
<= year
) && (year
<= INT_MAX
),
800 _T("year range overflow") );
802 // construct Tm from these values
805 tm
.mon
= (Month
)(month
- 1); // algorithm yields 1 for January, not 0
806 tm
.mday
= (wxDateTime_t
)day
;
807 tm
.msec
= timeOnly
% 1000;
809 timeOnly
/= 1000; // now we have time in seconds
811 tm
.sec
= timeOnly
% 60;
813 timeOnly
/= 60; // now we have time in minutes
815 tm
.min
= timeOnly
% 60;
818 tm
.hour
= timeOnly
/ 60;
823 wxDateTime
& wxDateTime::SetYear(int year
)
825 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
834 wxDateTime
& wxDateTime::SetMonth(Month month
)
836 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
845 wxDateTime
& wxDateTime::SetDay(wxDateTime_t mday
)
847 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
856 wxDateTime
& wxDateTime::SetHour(wxDateTime_t hour
)
858 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
867 wxDateTime
& wxDateTime::SetMinute(wxDateTime_t min
)
869 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
878 wxDateTime
& wxDateTime::SetSecond(wxDateTime_t sec
)
880 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
889 wxDateTime
& wxDateTime::SetMillisecond(wxDateTime_t millisecond
)
891 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
893 // we don't need to use GetTm() for this one
894 m_time
-= m_time
% 1000l;
895 m_time
+= millisecond
;
900 // ----------------------------------------------------------------------------
901 // wxDateTime arithmetics
902 // ----------------------------------------------------------------------------
904 wxDateTime
& wxDateTime::Add(const wxDateSpan
& diff
)
908 tm
.year
+= diff
.GetYears();
909 tm
.AddMonths(diff
.GetMonths());
910 tm
.AddDays(diff
.GetTotalDays());
917 // ----------------------------------------------------------------------------
918 // Weekday and monthday stuff
919 // ----------------------------------------------------------------------------
921 wxDateTime
& wxDateTime::SetToLastMonthDay(Month month
,
924 // take the current month/year if none specified
925 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
927 return Set(GetNumOfDaysInMonth(year
, month
), month
, year
);
930 bool wxDateTime::SetToWeekDay(WeekDay weekday
,
935 wxCHECK_MSG( weekday
!= Inv_WeekDay
, FALSE
, _T("invalid weekday") );
937 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
938 // anyhow in such case - but may be should still give an assert for it?
940 // take the current month/year if none specified
941 ReplaceDefaultYearMonthWithCurrent(&year
, &month
);
945 // TODO this probably could be optimised somehow...
949 // get the first day of the month
950 dt
.Set(1, month
, year
);
953 WeekDay wdayFirst
= dt
.GetWeekDay();
955 // go to the first weekday of the month
956 int diff
= weekday
- wdayFirst
;
960 // add advance n-1 weeks more
963 dt
-= wxDateSpan::Days(diff
);
967 // get the last day of the month
968 dt
.SetToLastMonthDay(month
, year
);
971 WeekDay wdayLast
= dt
.GetWeekDay();
973 // go to the last weekday of the month
974 int diff
= wdayLast
- weekday
;
978 // and rewind n-1 weeks from there
981 dt
-= wxDateSpan::Days(diff
);
984 // check that it is still in the same month
985 if ( dt
.GetMonth() == month
)
993 // no such day in this month
998 // ----------------------------------------------------------------------------
999 // Julian day number conversion and related stuff
1000 // ----------------------------------------------------------------------------
1002 double wxDateTime::GetJulianDayNumber() const
1004 // JDN are always expressed for the GMT dates
1005 Tm
tm(ToTimezone(GMT0
).GetTm(GMT0
));
1007 double result
= GetTruncatedJDN(tm
.mday
, tm
.mon
, tm
.year
);
1009 // add the part GetTruncatedJDN() neglected
1012 // and now add the time: 86400 sec = 1 JDN
1013 return result
+ ((double)(60*(60*tm
.hour
+ tm
.min
) + tm
.sec
)) / 86400;
1016 double wxDateTime::GetRataDie() const
1018 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1019 return GetJulianDayNumber() - 1721119.5 - 306;
1022 // ----------------------------------------------------------------------------
1023 // timezone and DST stuff
1024 // ----------------------------------------------------------------------------
1026 int wxDateTime::IsDST(wxDateTime::Country country
) const
1028 wxCHECK_MSG( country
== Country_Default
, -1,
1029 _T("country support not implemented") );
1031 // use the C RTL for the dates in the standard range
1032 time_t timet
= GetTicks();
1033 if ( timet
!= (time_t)-1 )
1035 tm
*tm
= localtime(&timet
);
1037 wxCHECK_MSG( tm
, -1, _T("localtime() failed") );
1039 return tm
->tm_isdst
;
1043 // wxFAIL_MSG( _T("TODO") );
1049 wxDateTime
& wxDateTime::MakeTimezone(const TimeZone
& tz
)
1051 int secDiff
= GetTimeZone() + tz
.GetOffset();
1053 // we need to know whether DST is or not in effect for this date
1056 // FIXME we assume that the DST is always shifted by 1 hour
1060 return Substract(wxTimeSpan::Seconds(secDiff
));
1063 // ----------------------------------------------------------------------------
1064 // wxDateTime to/from text representations
1065 // ----------------------------------------------------------------------------
1067 wxString
wxDateTime::Format(const wxChar
*format
, const TimeZone
& tz
) const
1069 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxDateTime::Format") );
1071 time_t time
= GetTicks();
1072 if ( time
!= (time_t)-1 )
1076 if ( tz
.GetOffset() == -GetTimeZone() )
1078 // we are working with local time
1079 tm
= localtime(&time
);
1081 // should never happen
1082 wxCHECK_MSG( tm
, wxEmptyString
, _T("localtime() failed") );
1086 time
+= tz
.GetOffset();
1092 // should never happen
1093 wxCHECK_MSG( tm
, wxEmptyString
, _T("gmtime() failed") );
1097 tm
= (struct tm
*)NULL
;
1103 return CallStrftime(format
, tm
);
1105 //else: use generic code below
1108 // use a hack and still use strftime(): first find the YEAR which is a year
1109 // in the strftime() range (1970 - 2038) whose Jan 1 falls on the same week
1110 // day as the Jan 1 of the real year. Then make a copy of the format and
1111 // replace all occurences of YEAR in it with some unique string not
1112 // appearing anywhere else in it, then use strftime() to format the date in
1113 // year YEAR and then replace YEAR back by the real year and the unique
1114 // replacement string back with YEAR. Notice that "all occurences of YEAR"
1115 // means all occurences of 4 digit as well as 2 digit form!
1117 // NB: may be it would be simpler to "honestly" reimplement strftime()?
1119 // find the YEAR: normally, for any year X, Jan 1 or the year X + 28 is the
1120 // same weekday as Jan 1 of X (because the weekday advances by 1 for each
1121 // normal X and by 2 for each leap X, hence by 5 every 4 years or by 35
1122 // which is 0 mod 7 every 28 years) but this rule breaks down if there are
1123 // years between X and Y which are divisible by 4 but not leap (i.e.
1124 // divisible by 100 but not 400), hence the correction.
1126 int yearReal
= GetYear(tz
);
1127 int year
= 1970 + yearReal
% 28;
1129 int nCenturiesInBetween
= (year
/ 100) - (yearReal
/ 100);
1130 int nLostWeekDays
= nCenturiesInBetween
- (nCenturiesInBetween
/ 400);
1132 // we have to gain back the "lost" weekdays...
1133 while ( (nLostWeekDays
% 7) != 0 )
1135 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
1138 // at any rate, we can't go further than 1997 + 28!
1139 wxASSERT_MSG( year
< 2030, _T("logic error in wxDateTime::Format") );
1141 wxString strYear
, strYear2
;
1142 strYear
.Printf(_T("%d"), year
);
1143 strYear2
.Printf(_T("%d"), year
% 100);
1145 // find two strings not occuring in format (this is surely not optimal way
1146 // of doing it... improvements welcome!)
1147 wxString fmt
= format
;
1148 wxString replacement
= (wxChar
)-1;
1149 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1151 replacement
<< (wxChar
)-1;
1154 wxString replacement2
= (wxChar
)-2;
1155 while ( fmt
.Find(replacement
) != wxNOT_FOUND
)
1157 replacement
<< (wxChar
)-2;
1160 // replace all occurences of year with it
1161 bool wasReplaced
= fmt
.Replace(strYear
, replacement
) > 0;
1163 wasReplaced
= fmt
.Replace(strYear2
, replacement2
) > 0;
1165 // use strftime() to format the same date but in supported year
1166 wxDateTime
dt(*this);
1168 wxString str
= dt
.Format(format
, tz
);
1170 // now replace the occurence of 1999 with the real year
1171 wxString strYearReal
, strYearReal2
;
1172 strYearReal
.Printf(_T("%04d"), yearReal
);
1173 strYearReal2
.Printf(_T("%02d"), yearReal
% 100);
1174 str
.Replace(strYear
, strYearReal
);
1175 str
.Replace(strYear2
, strYearReal2
);
1177 // and replace back all occurences of replacement string
1180 str
.Replace(replacement2
, strYear2
);
1181 str
.Replace(replacement
, strYear
);
1187 // ============================================================================
1189 // ============================================================================
1191 // not all strftime(3) format specifiers make sense here because, for example,
1192 // a time span doesn't have a year nor a timezone
1194 // Here are the ones which are supported (all of them are supported by strftime
1196 // %H hour in 24 hour format
1197 // %M minute (00 - 59)
1198 // %S second (00 - 59)
1201 // Also, for MFC CTimeSpan compatibility, we support
1202 // %D number of days
1204 // And, to be better than MFC :-), we also have
1205 // %E number of wEeks
1206 // %l milliseconds (000 - 999)
1207 wxString
wxTimeSpan::Format(const wxChar
*format
) const
1209 wxCHECK_MSG( format
, _T(""), _T("NULL format in wxTimeSpan::Format") );
1212 str
.Alloc(strlen(format
));
1214 for ( const wxChar
*pch
= format
; pch
; pch
++ )
1226 wxFAIL_MSG( _T("invalid format character") );
1230 // will get to str << ch below
1234 tmp
.Printf(_T("%d"), GetDays());
1238 tmp
.Printf(_T("%d"), GetWeeks());
1242 tmp
.Printf(_T("%02d"), GetHours());
1246 tmp
.Printf(_T("%03d"), GetMilliseconds());
1250 tmp
.Printf(_T("%02d"), GetMinutes());
1254 tmp
.Printf(_T("%02d"), GetSeconds());
1262 // skip str += ch below