]> git.saurik.com Git - wxWidgets.git/blob - src/common/datetime.cpp
75ca1af34d9954554bbc7544efa1fa87934e6ded
[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 // 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;
288 }
289
290 void wxDateTime::Tm::AddMonths(int monDiff)
291 {
292 // normalize the months field
293 while ( monDiff < -mon )
294 {
295 year--;
296
297 monDiff += MONTHS_IN_YEAR;
298 }
299
300 while ( monDiff + mon > MONTHS_IN_YEAR )
301 {
302 year++;
303 }
304
305 mon = (wxDateTime::Month)(mon + monDiff);
306
307 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
308 }
309
310 void wxDateTime::Tm::AddDays(int dayDiff)
311 {
312 // normalize the days field
313 mday += dayDiff;
314 while ( mday < 1 )
315 {
316 AddMonths(-1);
317
318 mday += GetNumOfDaysInMonth(year, mon);
319 }
320
321 while ( mday > GetNumOfDaysInMonth(year, mon) )
322 {
323 mday -= GetNumOfDaysInMonth(year, mon);
324
325 AddMonths(1);
326 }
327
328 wxASSERT_MSG( mday > 0 && mday <= GetNumOfDaysInMonth(year, mon),
329 _T("logic error") );
330 }
331
332 // ----------------------------------------------------------------------------
333 // class TimeZone
334 // ----------------------------------------------------------------------------
335
336 wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
337 {
338 switch ( tz )
339 {
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();
344 break;
345
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);
359 break;
360
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);
375 break;
376
377 case wxDateTime::A_CST:
378 // Central Standard Time in use in Australia = UTC + 9.5
379 m_offset = 60*(9*60 + 30);
380 break;
381
382 default:
383 wxFAIL_MSG( _T("unknown time zone") );
384 }
385 }
386
387 // ----------------------------------------------------------------------------
388 // static functions
389 // ----------------------------------------------------------------------------
390
391 /* static */
392 bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
393 {
394 if ( year == Inv_Year )
395 year = GetCurrentYear();
396
397 if ( cal == Gregorian )
398 {
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));
404 }
405 else if ( cal == Julian )
406 {
407 // in Julian calendar the rule is simpler
408 return year % 4 == 0;
409 }
410 else
411 {
412 wxFAIL_MSG(_T("unknown calendar"));
413
414 return FALSE;
415 }
416 }
417
418 /* static */
419 int wxDateTime::GetCentury(int year)
420 {
421 return year > 0 ? year / 100 : year / 100 - 1;
422 }
423
424 /* static */
425 void wxDateTime::SetCountry(wxDateTime::Country country)
426 {
427 ms_country = country;
428 }
429
430 /* static */
431 int wxDateTime::ConvertYearToBC(int year)
432 {
433 // year 0 is BC 1
434 return year > 0 ? year : year - 1;
435 }
436
437 /* static */
438 int wxDateTime::GetCurrentYear(wxDateTime::Calendar cal)
439 {
440 switch ( cal )
441 {
442 case Gregorian:
443 return Now().GetYear();
444
445 case Julian:
446 wxFAIL_MSG(_T("TODO"));
447 break;
448
449 default:
450 wxFAIL_MSG(_T("unsupported calendar"));
451 break;
452 }
453
454 return Inv_Year;
455 }
456
457 /* static */
458 wxDateTime::Month wxDateTime::GetCurrentMonth(wxDateTime::Calendar cal)
459 {
460 switch ( cal )
461 {
462 case Gregorian:
463 return Now().GetMonth();
464 break;
465
466 case Julian:
467 wxFAIL_MSG(_T("TODO"));
468 break;
469
470 default:
471 wxFAIL_MSG(_T("unsupported calendar"));
472 break;
473 }
474
475 return Inv_Month;
476 }
477
478 /* static */
479 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(int year, Calendar cal)
480 {
481 if ( year == Inv_Year )
482 {
483 // take the current year if none given
484 year = GetCurrentYear();
485 }
486
487 switch ( cal )
488 {
489 case Gregorian:
490 case Julian:
491 return IsLeapYear(year) ? 366 : 365;
492 break;
493
494 default:
495 wxFAIL_MSG(_T("unsupported calendar"));
496 break;
497 }
498
499 return 0;
500 }
501
502 /* static */
503 wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
504 int year,
505 wxDateTime::Calendar cal)
506 {
507 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
508
509 if ( cal == Gregorian || cal == Julian )
510 {
511 if ( year == Inv_Year )
512 {
513 // take the current year if none given
514 year = GetCurrentYear();
515 }
516
517 return GetNumOfDaysInMonth(year, month);
518 }
519 else
520 {
521 wxFAIL_MSG(_T("unsupported calendar"));
522
523 return 0;
524 }
525 }
526
527 /* static */
528 wxString wxDateTime::GetMonthName(wxDateTime::Month month, bool abbr)
529 {
530 wxCHECK_MSG( month != Inv_Month, _T(""), _T("invalid month") );
531
532 tm tm = { 0, 0, 0, 1, month, 76 }; // any year will do
533
534 return CallStrftime(abbr ? _T("%b") : _T("%B"), &tm);
535 }
536
537 /* static */
538 wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday, bool abbr)
539 {
540 wxCHECK_MSG( wday != Inv_WeekDay, _T(""), _T("invalid weekday") );
541
542 // take some arbitrary Sunday
543 tm tm = { 0, 0, 0, 28, Nov, 99 };
544
545 // and offset it by the number of days needed to get the correct wday
546 tm.tm_mday += wday;
547
548 // call mktime() to normalize it...
549 (void)mktime(&tm);
550
551 // ... and call strftime()
552 return CallStrftime(abbr ? _T("%a") : _T("%A"), &tm);
553 }
554
555 // ----------------------------------------------------------------------------
556 // constructors and assignment operators
557 // ----------------------------------------------------------------------------
558
559 // the values in the tm structure contain the local time
560 wxDateTime& wxDateTime::Set(const struct tm& tm)
561 {
562 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
563
564 struct tm tm2(tm);
565 time_t timet = mktime(&tm2);
566
567 if ( timet == (time_t)-1 )
568 {
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 )
572 {
573 // add timezone to make sure that date is in range
574 tm2.tm_sec -= GetTimeZone();
575
576 timet = mktime(&tm2);
577 if ( timet != (time_t)-1 )
578 {
579 timet += GetTimeZone();
580
581 return Set(timet);
582 }
583 }
584
585 wxFAIL_MSG( _T("mktime() failed") );
586
587 return ms_InvDateTime;
588 }
589 else
590 {
591 return Set(timet);
592 }
593 }
594
595 wxDateTime& wxDateTime::Set(wxDateTime_t hour,
596 wxDateTime_t minute,
597 wxDateTime_t second,
598 wxDateTime_t millisec)
599 {
600 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
601
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,
605 ms_InvDateTime,
606 _T("Invalid time in wxDateTime::Set()") );
607
608 // get the current date from system
609 time_t timet = GetTimeNow();
610 struct tm *tm = localtime(&timet);
611
612 wxCHECK_MSG( tm, ms_InvDateTime, _T("localtime() failed") );
613
614 // adjust the time
615 tm->tm_hour = hour;
616 tm->tm_min = minute;
617 tm->tm_sec = second;
618
619 (void)Set(*tm);
620
621 // and finally adjust milliseconds
622 return SetMillisecond(millisec);
623 }
624
625 wxDateTime& wxDateTime::Set(wxDateTime_t day,
626 Month month,
627 int year,
628 wxDateTime_t hour,
629 wxDateTime_t minute,
630 wxDateTime_t second,
631 wxDateTime_t millisec)
632 {
633 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
634
635 wxCHECK_MSG( hour < 24 && second < 62 && minute < 60 && millisec < 1000,
636 ms_InvDateTime,
637 _T("Invalid time in wxDateTime::Set()") );
638
639 ReplaceDefaultYearMonthWithCurrent(&year, &month);
640
641 wxCHECK_MSG( (0 < day) && (day <= GetNumberOfDays(month, year)),
642 ms_InvDateTime,
643 _T("Invalid date in wxDateTime::Set()") );
644
645 // the range of time_t type (inclusive)
646 static const int yearMinInRange = 1970;
647 static const int yearMaxInRange = 2037;
648
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 )
652 {
653 // use the standard library version if the date is in range - this is
654 // probably more efficient than our code
655 struct tm tm;
656 tm.tm_year = year - 1900;
657 tm.tm_mon = month;
658 tm.tm_mday = day;
659 tm.tm_hour = hour;
660 tm.tm_min = minute;
661 tm.tm_sec = second;
662 tm.tm_isdst = -1; // mktime() will guess it
663
664 (void)Set(tm);
665
666 // and finally adjust milliseconds
667 return SetMillisecond(millisec);
668 }
669 else
670 {
671 // do time calculations ourselves: we want to calculate the number of
672 // milliseconds between the given date and the epoch
673
674 // get the JDN for the midnight of this day
675 m_time = GetTruncatedJDN(day, month, year);
676 m_time -= EPOCH_JDN;
677 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
678
679 // JDN corresponds to GMT, we take localtime
680 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
681 }
682
683 return *this;
684 }
685
686 wxDateTime& wxDateTime::Set(double jdn)
687 {
688 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
689 // EPOCH_JDN + 0.5
690 jdn -= EPOCH_JDN + 0.5;
691
692 m_time = jdn;
693 m_time *= MILLISECONDS_PER_DAY;
694
695 return *this;
696 }
697
698 // ----------------------------------------------------------------------------
699 // time_t <-> broken down time conversions
700 // ----------------------------------------------------------------------------
701
702 wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
703 {
704 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
705
706 time_t time = GetTicks();
707 if ( time != (time_t)-1 )
708 {
709 // use C RTL functions
710 tm *tm;
711 if ( tz.GetOffset() == -GetTimeZone() )
712 {
713 // we are working with local time
714 tm = localtime(&time);
715
716 // should never happen
717 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
718 }
719 else
720 {
721 time += tz.GetOffset();
722 if ( time >= 0 )
723 {
724 tm = gmtime(&time);
725
726 // should never happen
727 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
728 }
729 else
730 {
731 tm = (struct tm *)NULL;
732 }
733 }
734
735 if ( tm )
736 {
737 return Tm(*tm, tz);
738 }
739 //else: use generic code below
740 }
741
742 // remember the time and do the calculations with the date only - this
743 // eliminates rounding errors of the floating point arithmetics
744
745 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
746
747 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
748
749 // we want to always have positive time and timeMidnight to be really
750 // the midnight before it
751 if ( timeOnly < 0 )
752 {
753 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
754 }
755
756 timeMidnight -= timeOnly;
757
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
760
761 // actually, this is the JDN for the noon of the previous day
762 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
763
764 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
765
766 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
767
768 // calculate the century
769 int temp = (jdn + JDN_OFFSET) * 4 - 1;
770 int century = temp / DAYS_PER_400_YEARS;
771
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;
776
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;
781
782 // month is counted from March - convert to normal
783 if ( month < 10 )
784 {
785 month += 3;
786 }
787 else
788 {
789 year += 1;
790 month -= 9;
791 }
792
793 // year is offset by 4800
794 year -= 4800;
795
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") );
801
802 // construct Tm from these values
803 Tm tm;
804 tm.year = (int)year;
805 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
806 tm.mday = (wxDateTime_t)day;
807 tm.msec = timeOnly % 1000;
808 timeOnly -= tm.msec;
809 timeOnly /= 1000; // now we have time in seconds
810
811 tm.sec = timeOnly % 60;
812 timeOnly -= tm.sec;
813 timeOnly /= 60; // now we have time in minutes
814
815 tm.min = timeOnly % 60;
816 timeOnly -= tm.min;
817
818 tm.hour = timeOnly / 60;
819
820 return tm;
821 }
822
823 wxDateTime& wxDateTime::SetYear(int year)
824 {
825 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
826
827 Tm tm(GetTm());
828 tm.year = year;
829 Set(tm);
830
831 return *this;
832 }
833
834 wxDateTime& wxDateTime::SetMonth(Month month)
835 {
836 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
837
838 Tm tm(GetTm());
839 tm.mon = month;
840 Set(tm);
841
842 return *this;
843 }
844
845 wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
846 {
847 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
848
849 Tm tm(GetTm());
850 tm.mday = mday;
851 Set(tm);
852
853 return *this;
854 }
855
856 wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
857 {
858 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
859
860 Tm tm(GetTm());
861 tm.hour = hour;
862 Set(tm);
863
864 return *this;
865 }
866
867 wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
868 {
869 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
870
871 Tm tm(GetTm());
872 tm.min = min;
873 Set(tm);
874
875 return *this;
876 }
877
878 wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
879 {
880 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
881
882 Tm tm(GetTm());
883 tm.sec = sec;
884 Set(tm);
885
886 return *this;
887 }
888
889 wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
890 {
891 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
892
893 // we don't need to use GetTm() for this one
894 m_time -= m_time % 1000l;
895 m_time += millisecond;
896
897 return *this;
898 }
899
900 // ----------------------------------------------------------------------------
901 // wxDateTime arithmetics
902 // ----------------------------------------------------------------------------
903
904 wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
905 {
906 Tm tm(GetTm());
907
908 tm.year += diff.GetYears();
909 tm.AddMonths(diff.GetMonths());
910 tm.AddDays(diff.GetTotalDays());
911
912 Set(tm);
913
914 return *this;
915 }
916
917 // ----------------------------------------------------------------------------
918 // Weekday and monthday stuff
919 // ----------------------------------------------------------------------------
920
921 wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
922 int year)
923 {
924 // take the current month/year if none specified
925 ReplaceDefaultYearMonthWithCurrent(&year, &month);
926
927 return Set(GetNumOfDaysInMonth(year, month), month, year);
928 }
929
930 bool wxDateTime::SetToWeekDay(WeekDay weekday,
931 int n,
932 Month month,
933 int year)
934 {
935 wxCHECK_MSG( weekday != Inv_WeekDay, FALSE, _T("invalid weekday") );
936
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?
939
940 // take the current month/year if none specified
941 ReplaceDefaultYearMonthWithCurrent(&year, &month);
942
943 wxDateTime dt;
944
945 // TODO this probably could be optimised somehow...
946
947 if ( n > 0 )
948 {
949 // get the first day of the month
950 dt.Set(1, month, year);
951
952 // get its wday
953 WeekDay wdayFirst = dt.GetWeekDay();
954
955 // go to the first weekday of the month
956 int diff = weekday - wdayFirst;
957 if ( diff < 0 )
958 diff += 7;
959
960 // add advance n-1 weeks more
961 diff += 7*(n - 1);
962
963 dt -= wxDateSpan::Days(diff);
964 }
965 else
966 {
967 // get the last day of the month
968 dt.SetToLastMonthDay(month, year);
969
970 // get its wday
971 WeekDay wdayLast = dt.GetWeekDay();
972
973 // go to the last weekday of the month
974 int diff = wdayLast - weekday;
975 if ( diff < 0 )
976 diff += 7;
977
978 // and rewind n-1 weeks from there
979 diff += 7*(n - 1);
980
981 dt -= wxDateSpan::Days(diff);
982 }
983
984 // check that it is still in the same month
985 if ( dt.GetMonth() == month )
986 {
987 *this = dt;
988
989 return TRUE;
990 }
991 else
992 {
993 // no such day in this month
994 return FALSE;
995 }
996 }
997
998 // ----------------------------------------------------------------------------
999 // Julian day number conversion and related stuff
1000 // ----------------------------------------------------------------------------
1001
1002 double wxDateTime::GetJulianDayNumber() const
1003 {
1004 // JDN are always expressed for the GMT dates
1005 Tm tm(ToTimezone(GMT0).GetTm(GMT0));
1006
1007 double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
1008
1009 // add the part GetTruncatedJDN() neglected
1010 result += 0.5;
1011
1012 // and now add the time: 86400 sec = 1 JDN
1013 return result + ((double)(60*(60*tm.hour + tm.min) + tm.sec)) / 86400;
1014 }
1015
1016 double wxDateTime::GetRataDie() const
1017 {
1018 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
1019 return GetJulianDayNumber() - 1721119.5 - 306;
1020 }
1021
1022 // ----------------------------------------------------------------------------
1023 // timezone and DST stuff
1024 // ----------------------------------------------------------------------------
1025
1026 int wxDateTime::IsDST(wxDateTime::Country country) const
1027 {
1028 wxCHECK_MSG( country == Country_Default, -1,
1029 _T("country support not implemented") );
1030
1031 // use the C RTL for the dates in the standard range
1032 time_t timet = GetTicks();
1033 if ( timet != (time_t)-1 )
1034 {
1035 tm *tm = localtime(&timet);
1036
1037 wxCHECK_MSG( tm, -1, _T("localtime() failed") );
1038
1039 return tm->tm_isdst;
1040 }
1041 else
1042 {
1043 // wxFAIL_MSG( _T("TODO") );
1044
1045 return -1;
1046 }
1047 }
1048
1049 wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz)
1050 {
1051 int secDiff = GetTimeZone() + tz.GetOffset();
1052
1053 // we need to know whether DST is or not in effect for this date
1054 if ( IsDST() == 1 )
1055 {
1056 // FIXME we assume that the DST is always shifted by 1 hour
1057 secDiff -= 3600;
1058 }
1059
1060 return Substract(wxTimeSpan::Seconds(secDiff));
1061 }
1062
1063 // ----------------------------------------------------------------------------
1064 // wxDateTime to/from text representations
1065 // ----------------------------------------------------------------------------
1066
1067 wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
1068 {
1069 wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
1070
1071 time_t time = GetTicks();
1072 if ( time != (time_t)-1 )
1073 {
1074 // use strftime()
1075 tm *tm;
1076 if ( tz.GetOffset() == -GetTimeZone() )
1077 {
1078 // we are working with local time
1079 tm = localtime(&time);
1080
1081 // should never happen
1082 wxCHECK_MSG( tm, wxEmptyString, _T("localtime() failed") );
1083 }
1084 else
1085 {
1086 time += tz.GetOffset();
1087
1088 if ( time >= 0 )
1089 {
1090 tm = gmtime(&time);
1091
1092 // should never happen
1093 wxCHECK_MSG( tm, wxEmptyString, _T("gmtime() failed") );
1094 }
1095 else
1096 {
1097 tm = (struct tm *)NULL;
1098 }
1099 }
1100
1101 if ( tm )
1102 {
1103 return CallStrftime(format, tm);
1104 }
1105 //else: use generic code below
1106 }
1107
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!
1116
1117 // NB: may be it would be simpler to "honestly" reimplement strftime()?
1118
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.
1125
1126 int yearReal = GetYear(tz);
1127 int year = 1970 + yearReal % 28;
1128
1129 int nCenturiesInBetween = (year / 100) - (yearReal / 100);
1130 int nLostWeekDays = nCenturiesInBetween - (nCenturiesInBetween / 400);
1131
1132 // we have to gain back the "lost" weekdays...
1133 while ( (nLostWeekDays % 7) != 0 )
1134 {
1135 nLostWeekDays += year++ % 4 ? 1 : 2;
1136 }
1137
1138 // at any rate, we can't go further than 1997 + 28!
1139 wxASSERT_MSG( year < 2030, _T("logic error in wxDateTime::Format") );
1140
1141 wxString strYear, strYear2;
1142 strYear.Printf(_T("%d"), year);
1143 strYear2.Printf(_T("%d"), year % 100);
1144
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 )
1150 {
1151 replacement << (wxChar)-1;
1152 }
1153
1154 wxString replacement2 = (wxChar)-2;
1155 while ( fmt.Find(replacement) != wxNOT_FOUND )
1156 {
1157 replacement << (wxChar)-2;
1158 }
1159
1160 // replace all occurences of year with it
1161 bool wasReplaced = fmt.Replace(strYear, replacement) > 0;
1162 if ( !wasReplaced )
1163 wasReplaced = fmt.Replace(strYear2, replacement2) > 0;
1164
1165 // use strftime() to format the same date but in supported year
1166 wxDateTime dt(*this);
1167 dt.SetYear(year);
1168 wxString str = dt.Format(format, tz);
1169
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);
1176
1177 // and replace back all occurences of replacement string
1178 if ( wasReplaced )
1179 {
1180 str.Replace(replacement2, strYear2);
1181 str.Replace(replacement, strYear);
1182 }
1183
1184 return str;
1185 }
1186
1187 // ============================================================================
1188 // wxTimeSpan
1189 // ============================================================================
1190
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
1193 //
1194 // Here are the ones which are supported (all of them are supported by strftime
1195 // as well):
1196 // %H hour in 24 hour format
1197 // %M minute (00 - 59)
1198 // %S second (00 - 59)
1199 // %% percent sign
1200 //
1201 // Also, for MFC CTimeSpan compatibility, we support
1202 // %D number of days
1203 //
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
1208 {
1209 wxCHECK_MSG( format, _T(""), _T("NULL format in wxTimeSpan::Format") );
1210
1211 wxString str;
1212 str.Alloc(strlen(format));
1213
1214 for ( const wxChar *pch = format; pch; pch++ )
1215 {
1216 wxChar ch = *pch;
1217
1218 if ( ch == '%' )
1219 {
1220 wxString tmp;
1221
1222 ch = *pch++;
1223 switch ( ch )
1224 {
1225 default:
1226 wxFAIL_MSG( _T("invalid format character") );
1227 // fall through
1228
1229 case '%':
1230 // will get to str << ch below
1231 break;
1232
1233 case 'D':
1234 tmp.Printf(_T("%d"), GetDays());
1235 break;
1236
1237 case 'E':
1238 tmp.Printf(_T("%d"), GetWeeks());
1239 break;
1240
1241 case 'H':
1242 tmp.Printf(_T("%02d"), GetHours());
1243 break;
1244
1245 case 'l':
1246 tmp.Printf(_T("%03d"), GetMilliseconds());
1247 break;
1248
1249 case 'M':
1250 tmp.Printf(_T("%02d"), GetMinutes());
1251 break;
1252
1253 case 'S':
1254 tmp.Printf(_T("%02d"), GetSeconds());
1255 break;
1256 }
1257
1258 if ( !!tmp )
1259 {
1260 str += tmp;
1261
1262 // skip str += ch below
1263 continue;
1264 }
1265 }
1266
1267 str += ch;
1268 }
1269
1270 return str;
1271 }