]> git.saurik.com Git - wxWidgets.git/blob - src/common/datetime.cpp
JPEG handler does not read entire file into memory anymore (+, of course, that header...
[wxWidgets.git] / src / common / datetime.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: wx/datetime.h
3 // Purpose: implementation of time/date related classes
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 11.05.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
10 //
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.
15 //
16 // Licence: wxWindows license
17 ///////////////////////////////////////////////////////////////////////////////
18
19 /*
20 * Implementation notes:
21 *
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
24 * expressed in GMT.
25 *
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
28 *
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
31 *
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
35 * or less)
36 *
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
40 * ToTimezone()
41 *
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
44 * wxDateTime::Tm.
45 */
46
47 // ============================================================================
48 // declarations
49 // ============================================================================
50
51 // ----------------------------------------------------------------------------
52 // headers
53 // ----------------------------------------------------------------------------
54
55 #ifdef __GNUG__
56 #pragma implementation "datetime.h"
57 #endif
58
59 // For compilers that support precompilation, includes "wx.h".
60 #include "wx/wxprec.h"
61
62 #ifdef __BORLANDC__
63 #pragma hdrstop
64 #endif
65
66 #ifndef WX_PRECOMP
67 #include "wx/string.h"
68 #include "wx/intl.h"
69 #include "wx/log.h"
70 #endif // WX_PRECOMP
71
72 #include "wx/thread.h"
73
74 #define wxDEFINE_TIME_CONSTANTS
75
76 #include "wx/datetime.h"
77
78 #ifndef WX_TIMEZONE
79 #define WX_TIMEZONE timezone
80 #endif
81
82 // ----------------------------------------------------------------------------
83 // constants
84 // ----------------------------------------------------------------------------
85
86 // some trivial ones
87 static const int MONTHS_IN_YEAR = 12;
88
89 static const int SECONDS_IN_MINUTE = 60;
90
91 static const long SECONDS_PER_DAY = 86400l;
92
93 static const long MILLISECONDS_PER_DAY = 86400000l;
94
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;
98
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;
104
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;
110
111 // ----------------------------------------------------------------------------
112 // globals
113 // ----------------------------------------------------------------------------
114
115 // a critical section is needed to protect GetTimeZone() static
116 // variable in MT case
117 #ifdef wxUSE_THREADS
118 wxCriticalSection gs_critsectTimezone;
119 #endif // wxUSE_THREADS
120
121 // ----------------------------------------------------------------------------
122 // private functions
123 // ----------------------------------------------------------------------------
124
125 // get the number of days in the given month of the given year
126 static inline
127 wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
128 {
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] =
132 {
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 }
135 };
136
137 return daysInMonth[wxDateTime::IsLeapYear(year)][month];
138 }
139
140 // ensure that the timezone variable is set by calling localtime
141 static int GetTimeZone()
142 {
143 // set to TRUE when the timezone is set
144 static bool s_timezoneSet = FALSE;
145
146 wxCRIT_SECT_LOCKER(lock, gs_critsectTimezone);
147
148 if ( !s_timezoneSet )
149 {
150 // just call localtime() instead of figuring out whether this system
151 // supports tzset(), _tzset() or something else
152 time_t t;
153 (void)localtime(&t);
154
155 s_timezoneSet = TRUE;
156 }
157
158 return (int)WX_TIMEZONE;
159 }
160
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,
166 int year)
167 {
168 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
169
170 // check the date validity
171 wxASSERT_MSG(
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")
176 );
177
178 // make the year positive to avoid problems with negative numbers division
179 year += 4800;
180
181 // months are counted from March here
182 int month;
183 if ( mon >= wxDateTime::Mar )
184 {
185 month = mon - 2;
186 }
187 else
188 {
189 month = mon + 10;
190 year--;
191 }
192
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
197 + day
198 - JDN_OFFSET;
199 }
200
201 // this function is a wrapper around strftime(3)
202 static wxString CallStrftime(const wxChar *format, const tm* tm)
203 {
204 wxChar buf[1024];
205 if ( !wxStrftime(buf, WXSIZEOF(buf), format, tm) )
206 {
207 // is ti really possible that 1024 is too short?
208 wxFAIL_MSG(_T("strftime() failed"));
209 }
210
211 return wxString(buf);
212 }
213
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)
217 {
218 struct tm *tmNow = NULL;
219
220 if ( *year == wxDateTime::Inv_Year )
221 {
222 tmNow = wxDateTime::GetTmNow();
223
224 *year = 1900 + tmNow->tm_year;
225 }
226
227 if ( *month == wxDateTime::Inv_Month )
228 {
229 if ( !tmNow )
230 tmNow = wxDateTime::GetTmNow();
231
232 *month = (wxDateTime::Month)tmNow->tm_mon;
233 }
234 }
235
236 // ============================================================================
237 // implementation of wxDateTime
238 // ============================================================================
239
240 // ----------------------------------------------------------------------------
241 // static data
242 // ----------------------------------------------------------------------------
243
244 wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
245 wxDateTime wxDateTime::ms_InvDateTime;
246
247 // ----------------------------------------------------------------------------
248 // struct Tm
249 // ----------------------------------------------------------------------------
250
251 wxDateTime::Tm::Tm()
252 {
253 year = (wxDateTime_t)wxDateTime::Inv_Year;
254 mon = wxDateTime::Inv_Month;
255 mday = 0;
256 hour = min = sec = msec = 0;
257 wday = wxDateTime::Inv_WeekDay;
258 }
259
260 wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
261 : m_tz(tz)
262 {
263 msec = 0;
264 sec = tm.tm_sec;
265 min = tm.tm_min;
266 hour = tm.tm_hour;
267 mday = tm.tm_mday;
268 mon = (wxDateTime::Month)tm.tm_mon;
269 year = 1900 + tm.tm_year;
270 wday = tm.tm_wday;
271 yday = tm.tm_yday;
272 }
273
274 bool wxDateTime::Tm::IsValid() const
275 {
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);
280 }
281
282 void wxDateTime::Tm::ComputeWeekDay()
283 {
284 wxFAIL_MSG(_T("TODO"));
285 }
286
287 void wxDateTime::Tm::AddMonths(int monDiff)
288 {
289 // normalize the months field
290 while ( monDiff < -mon )
291 {
292 year--;
293
294 monDiff += MONTHS_IN_YEAR;
295 }
296
297 while ( monDiff + mon > MONTHS_IN_YEAR )
298 {
299 year++;
300 }
301
302 mon = (wxDateTime::Month)(mon + monDiff);
303
304 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
305 }
306
307 void wxDateTime::Tm::AddDays(int dayDiff)
308 {
309 // normalize the days field
310 mday += dayDiff;
311 while ( mday < 1 )
312 {
313 AddMonths(-1);
314
315 mday += GetNumOfDaysInMonth(year, mon);
316 }
317
318 while ( mday > GetNumOfDaysInMonth(year, mon) )
319 {
320 mday -= GetNumOfDaysInMonth(year, mon);
321
322 AddMonths(1);
323 }
324
325 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
326 _T("logic error") );
327 }
328
329 // ----------------------------------------------------------------------------
330 // class TimeZone
331 // ----------------------------------------------------------------------------
332
333 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
334 {
335 switch ( tz )
336 {
337 case wxDateTime::Local:
338 // get the offset from C RTL: it returns the difference GMT-local
339 // while we want to have the offset _from_ GMT, hence the '-'
340 m_offset = -GetTimeZone();
341 break;
342
343 case wxDateTime::GMT_12:
344 case wxDateTime::GMT_11:
345 case wxDateTime::GMT_10:
346 case wxDateTime::GMT_9:
347 case wxDateTime::GMT_8:
348 case wxDateTime::GMT_7:
349 case wxDateTime::GMT_6:
350 case wxDateTime::GMT_5:
351 case wxDateTime::GMT_4:
352 case wxDateTime::GMT_3:
353 case wxDateTime::GMT_2:
354 case wxDateTime::GMT_1:
355 m_offset = -3600*(wxDateTime::GMT0 - tz);
356 break;
357
358 case wxDateTime::GMT0:
359 case wxDateTime::GMT1:
360 case wxDateTime::GMT2:
361 case wxDateTime::GMT3:
362 case wxDateTime::GMT4:
363 case wxDateTime::GMT5:
364 case wxDateTime::GMT6:
365 case wxDateTime::GMT7:
366 case wxDateTime::GMT8:
367 case wxDateTime::GMT9:
368 case wxDateTime::GMT10:
369 case wxDateTime::GMT11:
370 case wxDateTime::GMT12:
371 m_offset = 3600*(tz - wxDateTime::GMT0);
372 break;
373
374 case wxDateTime::A_CST:
375 // Central Standard Time in use in Australia = UTC + 9.5
376 m_offset = 60*(9*60 + 30);
377 break;
378
379 default:
380 wxFAIL_MSG( _T("unknown time zone") );
381 }
382 }
383
384 // ----------------------------------------------------------------------------
385 // static functions
386 // ----------------------------------------------------------------------------
387
388 /* static */
389 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
390 {
391 if ( year == Inv_Year )
392 year = GetCurrentYear();
393
394 if ( cal == Gregorian )
395 {
396 // in Gregorian calendar leap years are those divisible by 4 except
397 // those divisible by 100 unless they're also divisible by 400
398 // (in some countries, like Russia and Greece, additional corrections
399 // exist, but they won't manifest themselves until 2700)
400 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
401 }
402 else if ( cal == Julian )
403 {
404 // in Julian calendar the rule is simpler
405 return year % 4 == 0;
406 }
407 else
408 {
409 wxFAIL_MSG(_T("unknown calendar"));
410
411 return FALSE;
412 }
413 }
414
415 /* static */
416 int wxDateTime::GetCentury(int year)
417 {
418 return year > 0 ? year / 100 : year / 100 - 1;
419 }
420
421 /* static */
422 void wxDateTime::SetCountry(wxDateTime::Country country)
423 {
424 ms_country = country;
425 }
426
427 /* static */
428 int wxDateTime::ConvertYearToBC(int year)
429 {
430 // year 0 is BC 1
431 return year > 0 ? year : year - 1;
432 }
433
434 /* static */
435 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
436 {
437 switch ( cal )
438 {
439 case Gregorian:
440 return Now().GetYear();
441
442 case Julian:
443 wxFAIL_MSG(_T("TODO"));
444 break;
445
446 default:
447 wxFAIL_MSG(_T("unsupported calendar"));
448 break;
449 }
450
451 return Inv_Year;
452 }
453
454 /* static */
455 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
456 {
457 switch ( cal )
458 {
459 case Gregorian:
460 return Now().GetMonth();
461 break;
462
463 case Julian:
464 wxFAIL_MSG(_T("TODO"));
465 break;
466
467 default:
468 wxFAIL_MSG(_T("unsupported calendar"));
469 break;
470 }
471
472 return Inv_Month;
473 }
474
475 /* static */
476 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
477 {
478 if ( year == Inv_Year )
479 {
480 // take the current year if none given
481 year = GetCurrentYear();
482 }
483
484 switch ( cal )
485 {
486 case Gregorian:
487 case Julian:
488 return IsLeapYear(year) ? 366 : 365;
489 break;
490
491 default:
492 wxFAIL_MSG(_T("unsupported calendar"));
493 break;
494 }
495
496 return 0;
497 }
498
499 /* static */
500 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
501 int year,
502 wxDateTime::Calendar cal)
503 {
504 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
505
506 if ( cal == Gregorian || cal == Julian )
507 {
508 if ( year == Inv_Year )
509 {
510 // take the current year if none given
511 year = GetCurrentYear();
512 }
513
514 return GetNumOfDaysInMonth(year, month);
515 }
516 else
517 {
518 wxFAIL_MSG(_T("unsupported calendar"));
519
520 return 0;
521 }
522 }
523
524 /* static */
525 wxString wxDateTime::GetMonthName(wxDateTime::Month month, bool abbr)
526 {
527 wxCHECK_MSG( month != Inv_Month, _T(""), _T("invalid month") );
528
529 tm tm = { 0, 0, 0, 1, month, 76 }; // any year will do
530
531 return CallStrftime(abbr ? _T("%b") : _T("%B"), &tm);
532 }
533
534 /* static */
535 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday, bool abbr)
536 {
537 wxCHECK_MSG( wday != Inv_WeekDay, _T(""), _T("invalid weekday") );
538
539 // take some arbitrary Sunday
540 tm tm = { 0, 0, 0, 28, Nov, 99 };
541
542 // and offset it by the number of days needed to get the correct wday
543 tm.tm_mday += wday;
544
545 return CallStrftime(abbr ? _T("%a") : _T("%A"), &tm);
546 }
547
548 // ----------------------------------------------------------------------------
549 // constructors and assignment operators
550 // ----------------------------------------------------------------------------
551
552 // the values in the tm structure contain the local time
553 wxDateTime& wxDateTime::Set(const struct tm& tm)
554 {
555 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
556
557 struct tm tm2(tm);
558 time_t timet = mktime(&tm2);
559
560 if ( timet == (time_t)-1 )
561 {
562 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
563 // less than timezone - try to make it work for this case
564 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
565 {
566 // add timezone to make sure that date is in range
567 tm2.tm_sec -= GetTimeZone();
568
569 timet = mktime(&tm2);
570 if ( timet != (time_t)-1 )
571 {
572 timet += GetTimeZone();
573
574 return Set(timet);
575 }
576 }
577
578 wxFAIL_MSG( _T("mktime() failed") );
579
580 return ms_InvDateTime;
581 }
582 else
583 {
584 return Set(timet);
585 }
586 }
587
588 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
589 wxDateTime_t minute,
590 wxDateTime_t second,
591 wxDateTime_t millisec)
592 {
593 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
594
595 // we allow seconds to be 61 to account for the leap seconds, even if we
596 // don't use them really
597 wxCHECK_MSG( hour < 24 && second < 62 && minute < 60 && millisec < 1000,
598 ms_InvDateTime,
599 _T("Invalid time in wxDateTime::Set()") );
600
601 // get the current date from system
602 time_t timet = GetTimeNow();
603 struct tm *tm = localtime(&timet);
604
605 wxCHECK_MSG( tm, ms_InvDateTime, _T("localtime() failed") );
606
607 // adjust the time
608 tm->tm_hour = hour;
609 tm->tm_min = minute;
610 tm->tm_sec = second;
611
612 (void)Set(*tm);
613
614 // and finally adjust milliseconds
615 return SetMillisecond(millisec);
616 }
617
618 wxDateTime& wxDateTime::Set(wxDateTime_t day,
619 Month month,
620 int year,
621 wxDateTime_t hour,
622 wxDateTime_t minute,
623 wxDateTime_t second,
624 wxDateTime_t millisec)
625 {
626 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
627
628 wxCHECK_MSG( hour < 24 && second < 62 && minute < 60 && millisec < 1000,
629 ms_InvDateTime,
630 _T("Invalid time in wxDateTime::Set()") );
631
632 ReplaceDefaultYearMonthWithCurrent(&year, &month);
633
634 wxCHECK_MSG( (0 < day) && (day <= GetNumberOfDays(month, year)),
635 ms_InvDateTime,
636 _T("Invalid date in wxDateTime::Set()") );
637
638 // the range of time_t type (inclusive)
639 static const int yearMinInRange = 1970;
640 static const int yearMaxInRange = 2037;
641
642 // test only the year instead of testing for the exact end of the Unix
643 // time_t range - it doesn't bring anything to do more precise checks
644 if ( year >= yearMinInRange && year <= yearMaxInRange )
645 {
646 // use the standard library version if the date is in range - this is
647 // probably more efficient than our code
648 struct tm tm;
649 tm.tm_year = year - 1900;
650 tm.tm_mon = month;
651 tm.tm_mday = day;
652 tm.tm_hour = hour;
653 tm.tm_min = minute;
654 tm.tm_sec = second;
655 tm.tm_isdst = -1; // mktime() will guess it
656
657 (void)Set(tm);
658
659 // and finally adjust milliseconds
660 return SetMillisecond(millisec);
661 }
662 else
663 {
664 // do time calculations ourselves: we want to calculate the number of
665 // milliseconds between the given date and the epoch
666
667 // get the JDN for the midnight of this day
668 m_time = GetTruncatedJDN(day, month, year);
669 m_time -= EPOCH_JDN;
670 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
671
672 // JDN corresponds to GMT, we take localtime
673 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
674 }
675
676 return *this;
677 }
678
679 wxDateTime& wxDateTime::Set(double jdn)
680 {
681 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
682 // EPOCH_JDN + 0.5
683 jdn -= EPOCH_JDN + 0.5;
684
685 m_time = jdn;
686 m_time *= MILLISECONDS_PER_DAY;
687
688 return *this;
689 }
690
691 // ----------------------------------------------------------------------------
692 // time_t <-> broken down time conversions
693 // ----------------------------------------------------------------------------
694
695 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
696 {
697 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
698
699 time_t time = GetTicks();
700 if ( time != (time_t)-1 )
701 {
702 // use C RTL functions
703 tm *tm;
704 if ( tz.GetOffset() == -GetTimeZone() )
705 {
706 // we are working with local time
707 tm = localtime(&time);
708 }
709 else
710 {
711 time += tz.GetOffset();
712 tm = gmtime(&time);
713 }
714
715 // should never happen
716 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
717
718 return Tm(*tm, tz);
719 }
720 else
721 {
722 // remember the time and do the calculations with the date only - this
723 // eliminates rounding errors of the floating point arithmetics
724
725 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
726
727 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
728
729 // we want to always have positive time and timeMidnight to be really
730 // the midnight before it
731 if ( timeOnly < 0 )
732 {
733 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
734 }
735
736 timeMidnight -= timeOnly;
737
738 // calculate the Gregorian date from JDN for the midnight of our date:
739 // this will yield day, month (in 1..12 range) and year
740
741 // actually, this is the JDN for the noon of the previous day
742 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
743
744 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
745
746 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
747
748 // calculate the century
749 int temp = (jdn + JDN_OFFSET) * 4 - 1;
750 int century = temp / DAYS_PER_400_YEARS;
751
752 // then the year and day of year (1 <= dayOfYear <= 366)
753 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
754 int year = (century * 100) + (temp / DAYS_PER_4_YEARS);
755 int dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
756
757 // and finally the month and day of the month
758 temp = dayOfYear * 5 - 3;
759 int month = temp / DAYS_PER_5_MONTHS;
760 int day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
761
762 // month is counted from March - convert to normal
763 if ( month < 10 )
764 {
765 month += 3;
766 }
767 else
768 {
769 year += 1;
770 month -= 9;
771 }
772
773 // year is offset by 4800
774 year -= 4800;
775
776 // check that the algorithm gave us something reasonable
777 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
778 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
779 wxASSERT_MSG( (INT_MIN <= year) && (year <= INT_MAX),
780 _T("year range overflow") );
781
782 // construct Tm from these values
783 Tm tm;
784 tm.year = (int)year;
785 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
786 tm.mday = (wxDateTime_t)day;
787 tm.msec = timeOnly % 1000;
788 timeOnly -= tm.msec;
789 timeOnly /= 1000; // now we have time in seconds
790
791 tm.sec = timeOnly % 60;
792 timeOnly -= tm.sec;
793 timeOnly /= 60; // now we have time in minutes
794
795 tm.min = timeOnly % 60;
796 timeOnly -= tm.min;
797
798 tm.hour = timeOnly / 60;
799
800 return tm;
801 }
802 }
803
804 wxDateTime& wxDateTime::SetYear(int year)
805 {
806 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
807
808 Tm tm(GetTm());
809 tm.year = year;
810 Set(tm);
811
812 return *this;
813 }
814
815 wxDateTime& wxDateTime::SetMonth(Month month)
816 {
817 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
818
819 Tm tm(GetTm());
820 tm.mon = month;
821 Set(tm);
822
823 return *this;
824 }
825
826 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
827 {
828 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
829
830 Tm tm(GetTm());
831 tm.mday = mday;
832 Set(tm);
833
834 return *this;
835 }
836
837 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
838 {
839 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
840
841 Tm tm(GetTm());
842 tm.hour = hour;
843 Set(tm);
844
845 return *this;
846 }
847
848 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
849 {
850 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
851
852 Tm tm(GetTm());
853 tm.min = min;
854 Set(tm);
855
856 return *this;
857 }
858
859 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
860 {
861 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
862
863 Tm tm(GetTm());
864 tm.sec = sec;
865 Set(tm);
866
867 return *this;
868 }
869
870 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
871 {
872 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
873
874 // we don't need to use GetTm() for this one
875 m_time -= m_time % 1000l;
876 m_time += millisecond;
877
878 return *this;
879 }
880
881 // ----------------------------------------------------------------------------
882 // wxDateTime arithmetics
883 // ----------------------------------------------------------------------------
884
885 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
886 {
887 Tm tm(GetTm());
888
889 tm.year += diff.GetYears();
890 tm.AddMonths(diff.GetMonths());
891 tm.AddDays(diff.GetTotalDays());
892
893 Set(tm);
894
895 return *this;
896 }
897
898 // ----------------------------------------------------------------------------
899 // Weekday and monthday stuff
900 // ----------------------------------------------------------------------------
901
902 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
903 int year)
904 {
905 // take the current month/year if none specified
906 ReplaceDefaultYearMonthWithCurrent(&year, &month);
907
908 return Set(GetNumOfDaysInMonth(year, month), month, year);
909 }
910
911 bool wxDateTime::SetToWeekDay(WeekDay weekday,
912 int n,
913 Month month,
914 int year)
915 {
916 wxCHECK_MSG( weekday != Inv_WeekDay, FALSE, _T("invalid weekday") );
917
918 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
919 // anyhow in such case - but may be should still give an assert for it?
920
921 // take the current month/year if none specified
922 ReplaceDefaultYearMonthWithCurrent(&year, &month);
923
924 wxDateTime dt;
925
926 // TODO this probably could be optimised somehow...
927
928 if ( n > 0 )
929 {
930 // get the first day of the month
931 dt.Set(1, month, year);
932
933 // get its wday
934 WeekDay wdayFirst = dt.GetWeekDay();
935
936 // go to the first weekday of the month
937 int diff = weekday - wdayFirst;
938 if ( diff < 0 )
939 diff += 7;
940
941 // add advance n-1 weeks more
942 diff += 7*(n - 1);
943
944 dt -= wxDateSpan::Days(diff);
945 }
946 else
947 {
948 // get the last day of the month
949 dt.SetToLastMonthDay(month, year);
950
951 // get its wday
952 WeekDay wdayLast = dt.GetWeekDay();
953
954 // go to the last weekday of the month
955 int diff = wdayLast - weekday;
956 if ( diff < 0 )
957 diff += 7;
958
959 // and rewind n-1 weeks from there
960 diff += 7*(n - 1);
961
962 dt -= wxDateSpan::Days(diff);
963 }
964
965 // check that it is still in the same month
966 if ( dt.GetMonth() == month )
967 {
968 *this = dt;
969
970 return TRUE;
971 }
972 else
973 {
974 // no such day in this month
975 return FALSE;
976 }
977 }
978
979 // ----------------------------------------------------------------------------
980 // Julian day number conversion and related stuff
981 // ----------------------------------------------------------------------------
982
983 double wxDateTime::GetJulianDayNumber() const
984 {
985 // JDN are always expressed for the GMT dates
986 Tm tm(ToTimezone(GMT0).GetTm(GMT0));
987
988 double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
989
990 // add the part GetTruncatedJDN() neglected
991 result += 0.5;
992
993 // and now add the time: 86400 sec = 1 JDN
994 return result + ((double)(60*(60*tm.hour + tm.min) + tm.sec)) / 86400;
995 }
996
997 double wxDateTime::GetRataDie() const
998 {
999 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1000 return GetJulianDayNumber() - 1721119.5 - 306;
1001 }
1002
1003 // ----------------------------------------------------------------------------
1004 // timezone and DST stuff
1005 // ----------------------------------------------------------------------------
1006
1007 int wxDateTime::IsDST(wxDateTime::Country country) const
1008 {
1009 wxCHECK_MSG( country == Country_Default, -1,
1010 _T("country support not implemented") );
1011
1012 // use the C RTL for the dates in the standard range
1013 time_t timet = GetTicks();
1014 if ( timet != (time_t)-1 )
1015 {
1016 tm *tm = localtime(&timet);
1017
1018 wxCHECK_MSG( tm, -1, _T("localtime() failed") );
1019
1020 return tm->tm_isdst;
1021 }
1022 else
1023 {
1024 // wxFAIL_MSG( _T("TODO") );
1025
1026 return -1;
1027 }
1028 }
1029
1030 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz)
1031 {
1032 int secDiff = GetTimeZone() + tz.GetOffset();
1033
1034 // we need to know whether DST is or not in effect for this date
1035 if ( IsDST() == 1 )
1036 {
1037 // FIXME we assume that the DST is always shifted by 1 hour
1038 secDiff -= 3600;
1039 }
1040
1041 return Substract(wxTimeSpan::Seconds(secDiff));
1042 }
1043
1044 // ----------------------------------------------------------------------------
1045 // wxDateTime to/from text representations
1046 // ----------------------------------------------------------------------------
1047
1048 wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
1049 {
1050 wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
1051
1052 time_t time = GetTicks();
1053 if ( time != (time_t)-1 )
1054 {
1055 // use strftime()
1056 tm *tm;
1057 if ( tz.GetOffset() == -GetTimeZone() )
1058 {
1059 // we are working with local time
1060 tm = localtime(&time);
1061 }
1062 else
1063 {
1064 time += tz.GetOffset();
1065
1066 tm = gmtime(&time);
1067 }
1068
1069 // should never happen
1070 wxCHECK_MSG( tm, _T(""), _T("gmtime() failed") );
1071
1072 return CallStrftime(format, tm);
1073 }
1074 else
1075 {
1076 // use a hack and still use strftime(): make a copy of the format and
1077 // replace all occurences of YEAR in it with some unique string not
1078 // appearing anywhere else in it, then use strftime() to format the
1079 // date in year YEAR and then replace YEAR back by the real year and
1080 // the unique replacement string back with YEAR where YEAR is any year
1081 // in the range supported by strftime() (1970 - 2037) which is equal to
1082 // the real year modulo 28 (so the week days coincide for them)
1083
1084 // find the YEAR
1085 int yearReal = GetYear(tz);
1086 int year = 1970 + yearReal % 28;
1087
1088 wxString strYear;
1089 strYear.Printf(_T("%d"), year);
1090
1091 // find a string not occuring in format (this is surely not optimal way
1092 // of doing it... improvements welcome!)
1093 wxString fmt = format;
1094 wxString replacement = (wxChar)-1;
1095 while ( fmt.Find(replacement) != wxNOT_FOUND )
1096 {
1097 replacement << (wxChar)-1;
1098 }
1099
1100 // replace all occurences of year with it
1101 bool wasReplaced = fmt.Replace(strYear, replacement) > 0;
1102
1103 // use strftime() to format the same date but in supported year
1104 wxDateTime dt(*this);
1105 dt.SetYear(year);
1106 wxString str = dt.Format(format, tz);
1107
1108 // now replace the occurence of 1999 with the real year
1109 wxString strYearReal;
1110 strYearReal.Printf(_T("%d"), yearReal);
1111 str.Replace(strYear, strYearReal);
1112
1113 // and replace back all occurences of replacement string
1114 if ( wasReplaced )
1115 str.Replace(replacement, strYear);
1116
1117 return str;
1118 }
1119 }
1120
1121 // ============================================================================
1122 // wxTimeSpan
1123 // ============================================================================
1124
1125 // not all strftime(3) format specifiers make sense here because, for example,
1126 // a time span doesn't have a year nor a timezone
1127 //
1128 // Here are the ones which are supported (all of them are supported by strftime
1129 // as well):
1130 // %H hour in 24 hour format
1131 // %M minute (00 - 59)
1132 // %S second (00 - 59)
1133 // %% percent sign
1134 //
1135 // Also, for MFC CTimeSpan compatibility, we support
1136 // %D number of days
1137 //
1138 // And, to be better than MFC :-), we also have
1139 // %E number of wEeks
1140 // %l milliseconds (000 - 999)
1141 wxString wxTimeSpan::Format(const wxChar *format) const
1142 {
1143 wxCHECK_MSG( format, _T(""), _T("NULL format in wxTimeSpan::Format") );
1144
1145 wxString str;
1146 str.Alloc(strlen(format));
1147
1148 for ( const wxChar *pch = format; pch; pch++ )
1149 {
1150 wxChar ch = *pch;
1151
1152 if ( ch == '%' )
1153 {
1154 wxString tmp;
1155
1156 ch = *pch++;
1157 switch ( ch )
1158 {
1159 default:
1160 wxFAIL_MSG( _T("invalid format character") );
1161 // fall through
1162
1163 case '%':
1164 // will get to str << ch below
1165 break;
1166
1167 case 'D':
1168 tmp.Printf(_T("%d"), GetDays());
1169 break;
1170
1171 case 'E':
1172 tmp.Printf(_T("%d"), GetWeeks());
1173 break;
1174
1175 case 'H':
1176 tmp.Printf(_T("%02d"), GetHours());
1177 break;
1178
1179 case 'l':
1180 tmp.Printf(_T("%03d"), GetMilliseconds());
1181 break;
1182
1183 case 'M':
1184 tmp.Printf(_T("%02d"), GetMinutes());
1185 break;
1186
1187 case 'S':
1188 tmp.Printf(_T("%02d"), GetSeconds());
1189 break;
1190 }
1191
1192 if ( !!tmp )
1193 {
1194 str += tmp;
1195
1196 // skip str += ch below
1197 continue;
1198 }
1199 }
1200
1201 str += ch;
1202 }
1203
1204 return str;
1205 }