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