]> git.saurik.com Git - wxWidgets.git/blame - src/common/datetime.cpp
Added wxOutputStream::PutC()
[wxWidgets.git] / src / common / datetime.cpp
CommitLineData
1ef54dcf 1///////////////////////////////////////////////////////////////////////////////
0979c962
VZ
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$
1ef54dcf
VZ
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//
0979c962 16// Licence: wxWindows license
1ef54dcf
VZ
17///////////////////////////////////////////////////////////////////////////////
18
19/*
20 * Implementation notes:
21 *
22 * 1. the time is stored as a 64bit integer containing the signed number of
299fcbfe
VZ
23 * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
24 * expressed in GMT.
1ef54dcf
VZ
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 *
299fcbfe
VZ
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.
1ef54dcf 45 */
0979c962
VZ
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
fcc3d7cb
VZ
72#include "wx/thread.h"
73
b76b015e
VZ
74#define wxDEFINE_TIME_CONSTANTS
75
0979c962
VZ
76#include "wx/datetime.h"
77
b76b015e
VZ
78// ----------------------------------------------------------------------------
79// constants
80// ----------------------------------------------------------------------------
81
e6ec579c 82// some trivial ones
fcc3d7cb
VZ
83static const int MONTHS_IN_YEAR = 12;
84
85static const int SECONDS_IN_MINUTE = 60;
86
e6ec579c
VZ
87static const long SECONDS_PER_DAY = 86400l;
88
89static 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)
93static const int EPOCH_JDN = 2440587;
b76b015e 94
1ef54dcf
VZ
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
97static const int JDN_0_YEAR = -4713;
98static const int JDN_0_MONTH = wxDateTime::Nov;
99static const int JDN_0_DAY = 24;
100
101// the constants used for JDN calculations
102static const int JDN_OFFSET = 32046;
103static const int DAYS_PER_5_MONTHS = 153;
104static const int DAYS_PER_4_YEARS = 1461;
105static const int DAYS_PER_400_YEARS = 146097;
106
fcc3d7cb
VZ
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
b76b015e
VZ
117// ----------------------------------------------------------------------------
118// private functions
119// ----------------------------------------------------------------------------
120
fcc3d7cb
VZ
121// get the number of days in the given month of the given year
122static inline
123wxDateTime::wxDateTime_t GetNumOfDaysInMonth(int year, wxDateTime::Month month)
124{
e6ec579c
VZ
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];
fcc3d7cb
VZ
134}
135
136// ensure that the timezone variable is set by calling localtime
137static 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 {
1ef54dcf 146 // just call localtime() instead of figuring out whether this system
e6ec579c
VZ
147 // supports tzset(), _tzset() or something else
148 time_t t;
149 (void)localtime(&t);
fcc3d7cb
VZ
150
151 s_timezoneSet = TRUE;
152 }
153
154 return (int)timezone;
155}
156
e6ec579c 157// return the integral part of the JDN for the midnight of the given date (to
1ef54dcf
VZ
158// get the real JDN you need to add 0.5, this is, in fact, JDN of the
159// noon of the previous day)
e6ec579c
VZ
160static long GetTruncatedJDN(wxDateTime::wxDateTime_t day,
161 wxDateTime::Month mon,
162 int year)
163{
1ef54dcf
VZ
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 )
e6ec579c 180 {
1ef54dcf 181 month = mon - 2;
e6ec579c 182 }
1ef54dcf 183 else
e6ec579c 184 {
1ef54dcf
VZ
185 month = mon + 10;
186 year--;
187 }
e6ec579c 188
1ef54dcf
VZ
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;
e6ec579c
VZ
195}
196
2f02cb89 197// this function is a wrapper around strftime(3)
b76b015e
VZ
198static 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
2f02cb89
VZ
210// if year and/or month have invalid values, replace them with the current ones
211static 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
0979c962
VZ
232// ============================================================================
233// implementation of wxDateTime
234// ============================================================================
235
236// ----------------------------------------------------------------------------
237// static data
238// ----------------------------------------------------------------------------
239
b76b015e 240wxDateTime::Country wxDateTime::ms_country = wxDateTime::Country_Unknown;
0979c962
VZ
241wxDateTime wxDateTime::ms_InvDateTime;
242
b76b015e
VZ
243// ----------------------------------------------------------------------------
244// struct Tm
245// ----------------------------------------------------------------------------
246
247wxDateTime::Tm::Tm()
248{
249 year = (wxDateTime_t)wxDateTime::Inv_Year;
250 mon = wxDateTime::Inv_Month;
251 mday = 0;
e6ec579c 252 hour = min = sec = msec = 0;
b76b015e
VZ
253 wday = wxDateTime::Inv_WeekDay;
254}
255
299fcbfe
VZ
256wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
257 : m_tz(tz)
b76b015e 258{
e6ec579c 259 msec = 0;
b76b015e
VZ
260 sec = tm.tm_sec;
261 min = tm.tm_min;
262 hour = tm.tm_hour;
263 mday = tm.tm_mday;
fcc3d7cb 264 mon = (wxDateTime::Month)tm.tm_mon;
b76b015e
VZ
265 year = 1900 + tm.tm_year;
266 wday = tm.tm_wday;
267 yday = tm.tm_yday;
268}
269
270bool wxDateTime::Tm::IsValid() const
271{
272 // we allow for the leap seconds, although we don't use them (yet)
fcc3d7cb
VZ
273 return (year != wxDateTime::Inv_Year) && (mon != wxDateTime::Inv_Month) &&
274 (mday < GetNumOfDaysInMonth(year, mon)) &&
e6ec579c 275 (hour < 24) && (min < 60) && (sec < 62) && (msec < 1000);
b76b015e
VZ
276}
277
278void wxDateTime::Tm::ComputeWeekDay()
279{
280 wxFAIL_MSG(_T("TODO"));
281}
282
e6ec579c 283void wxDateTime::Tm::AddMonths(int monDiff)
fcc3d7cb
VZ
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
e6ec579c 300 wxASSERT_MSG( mon >= 0 && mon < MONTHS_IN_YEAR, _T("logic error") );
fcc3d7cb
VZ
301}
302
e6ec579c 303void wxDateTime::Tm::AddDays(int dayDiff)
fcc3d7cb
VZ
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
329wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
330{
331 switch ( tz )
332 {
333 case wxDateTime::Local:
299fcbfe
VZ
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();
fcc3d7cb
VZ
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:
299fcbfe 351 m_offset = -3600*(wxDateTime::GMT0 - tz);
fcc3d7cb
VZ
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:
299fcbfe 367 m_offset = 3600*(tz - wxDateTime::GMT0);
fcc3d7cb
VZ
368 break;
369
370 case wxDateTime::A_CST:
371 // Central Standard Time in use in Australia = UTC + 9.5
299fcbfe 372 m_offset = 60*(9*60 + 30);
fcc3d7cb
VZ
373 break;
374
375 default:
376 wxFAIL_MSG( _T("unknown time zone") );
377 }
378}
379
b76b015e
VZ
380// ----------------------------------------------------------------------------
381// static functions
382// ----------------------------------------------------------------------------
383
384/* static */
385bool wxDateTime::IsLeapYear(int year, wxDateTime::Calendar cal)
386{
2f02cb89
VZ
387 if ( year == Inv_Year )
388 year = GetCurrentYear();
389
b76b015e
VZ
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
fcc3d7cb
VZ
411/* static */
412int wxDateTime::GetCentury(int year)
413{
414 return year > 0 ? year / 100 : year / 100 - 1;
415}
416
b76b015e
VZ
417/* static */
418void wxDateTime::SetCountry(wxDateTime::Country country)
419{
420 ms_country = country;
421}
422
423/* static */
424int wxDateTime::ConvertYearToBC(int year)
425{
426 // year 0 is BC 1
427 return year > 0 ? year : year - 1;
428}
429
430/* static */
431int 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 */
451wxDateTime::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
2f02cb89
VZ
471/* static */
472wxDateTime::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
b76b015e
VZ
495/* static */
496wxDateTime::wxDateTime_t wxDateTime::GetNumberOfDays(wxDateTime::Month month,
497 int year,
498 wxDateTime::Calendar cal)
499{
fcc3d7cb 500 wxCHECK_MSG( month < MONTHS_IN_YEAR, 0, _T("invalid month") );
b76b015e
VZ
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
fcc3d7cb 510 return GetNumOfDaysInMonth(year, month);
b76b015e
VZ
511 }
512 else
513 {
514 wxFAIL_MSG(_T("unsupported calendar"));
515
516 return 0;
517 }
518}
519
520/* static */
521wxString 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 */
531wxString 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
1ef54dcf 538 // and offset it by the number of days needed to get the correct wday
b76b015e
VZ
539 tm.tm_mday += wday;
540
541 return CallStrftime(abbr ? _T("%a") : _T("%A"), &tm);
542}
543
0979c962
VZ
544// ----------------------------------------------------------------------------
545// constructors and assignment operators
546// ----------------------------------------------------------------------------
547
299fcbfe
VZ
548// the values in the tm structure contain the local time
549wxDateTime& wxDateTime::Set(const struct tm& tm)
0979c962 550{
b76b015e
VZ
551 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
552
299fcbfe 553 struct tm tm2(tm);
b76b015e 554 time_t timet = mktime(&tm2);
1ef54dcf 555
4afd7529 556 if ( timet == (time_t)-1 )
0979c962 557 {
4afd7529
VZ
558 // mktime() rather unintuitively fails for Jan 1, 1970 if the hour is
559 // less than timezone - try to make it work for this case
560 if ( tm2.tm_year == 70 && tm2.tm_mon == 0 && tm2.tm_mday == 1 )
561 {
562 // add timezone to make sure that date is in range
563 tm2.tm_sec -= GetTimeZone();
564
565 timet = mktime(&tm2);
566 if ( timet != (time_t)-1 )
567 {
568 timet += GetTimeZone();
569
570 return Set(timet);
571 }
572 }
573
574 wxFAIL_MSG( _T("mktime() failed") );
0979c962
VZ
575
576 return ms_InvDateTime;
577 }
578 else
579 {
580 return Set(timet);
581 }
582}
583
584wxDateTime& wxDateTime::Set(wxDateTime_t hour,
585 wxDateTime_t minute,
586 wxDateTime_t second,
587 wxDateTime_t millisec)
588{
b76b015e
VZ
589 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
590
0979c962
VZ
591 // we allow seconds to be 61 to account for the leap seconds, even if we
592 // don't use them really
593 wxCHECK_MSG( hour < 24 && second < 62 && minute < 60 && millisec < 1000,
594 ms_InvDateTime,
595 _T("Invalid time in wxDateTime::Set()") );
596
597 // get the current date from system
598 time_t timet = GetTimeNow();
299fcbfe
VZ
599 struct tm *tm = localtime(&timet);
600
601 wxCHECK_MSG( tm, ms_InvDateTime, _T("localtime() failed") );
0979c962
VZ
602
603 // adjust the time
604 tm->tm_hour = hour;
605 tm->tm_min = minute;
606 tm->tm_sec = second;
607
b76b015e 608 (void)Set(*tm);
0979c962
VZ
609
610 // and finally adjust milliseconds
611 return SetMillisecond(millisec);
612}
613
614wxDateTime& wxDateTime::Set(wxDateTime_t day,
615 Month month,
616 int year,
617 wxDateTime_t hour,
618 wxDateTime_t minute,
619 wxDateTime_t second,
620 wxDateTime_t millisec)
621{
b76b015e
VZ
622 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
623
0979c962
VZ
624 wxCHECK_MSG( hour < 24 && second < 62 && minute < 60 && millisec < 1000,
625 ms_InvDateTime,
626 _T("Invalid time in wxDateTime::Set()") );
627
2f02cb89 628 ReplaceDefaultYearMonthWithCurrent(&year, &month);
0979c962 629
1ef54dcf
VZ
630 wxCHECK_MSG( (0 < day) && (day <= GetNumberOfDays(month, year)),
631 ms_InvDateTime,
0979c962
VZ
632 _T("Invalid date in wxDateTime::Set()") );
633
634 // the range of time_t type (inclusive)
635 static const int yearMinInRange = 1970;
636 static const int yearMaxInRange = 2037;
637
638 // test only the year instead of testing for the exact end of the Unix
639 // time_t range - it doesn't bring anything to do more precise checks
2f02cb89 640 if ( year >= yearMinInRange && year <= yearMaxInRange )
0979c962
VZ
641 {
642 // use the standard library version if the date is in range - this is
b76b015e 643 // probably more efficient than our code
0979c962 644 struct tm tm;
b76b015e 645 tm.tm_year = year - 1900;
0979c962
VZ
646 tm.tm_mon = month;
647 tm.tm_mday = day;
648 tm.tm_hour = hour;
649 tm.tm_min = minute;
650 tm.tm_sec = second;
299fcbfe 651 tm.tm_isdst = -1; // mktime() will guess it
0979c962
VZ
652
653 (void)Set(tm);
654
655 // and finally adjust milliseconds
656 return SetMillisecond(millisec);
657 }
658 else
659 {
660 // do time calculations ourselves: we want to calculate the number of
fcc3d7cb 661 // milliseconds between the given date and the epoch
e6ec579c
VZ
662
663 // get the JDN for the midnight of this day
664 m_time = GetTruncatedJDN(day, month, year);
665 m_time -= EPOCH_JDN;
666 m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
667
299fcbfe
VZ
668 // JDN corresponds to GMT, we take localtime
669 Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
b76b015e
VZ
670 }
671
672 return *this;
673}
674
e6ec579c
VZ
675wxDateTime& wxDateTime::Set(double jdn)
676{
1ef54dcf
VZ
677 // so that m_time will be 0 for the midnight of Jan 1, 1970 which is jdn
678 // EPOCH_JDN + 0.5
679 jdn -= EPOCH_JDN + 0.5;
680
681 m_time = jdn;
682 m_time *= MILLISECONDS_PER_DAY;
e6ec579c
VZ
683
684 return *this;
685}
686
b76b015e
VZ
687// ----------------------------------------------------------------------------
688// time_t <-> broken down time conversions
689// ----------------------------------------------------------------------------
690
299fcbfe 691wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
b76b015e
VZ
692{
693 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
694
695 time_t time = GetTicks();
696 if ( time != (time_t)-1 )
697 {
698 // use C RTL functions
299fcbfe
VZ
699 tm *tm;
700 if ( tz.GetOffset() == -GetTimeZone() )
701 {
702 // we are working with local time
703 tm = localtime(&time);
704 }
705 else
706 {
151d66be 707 time += tz.GetOffset();
299fcbfe
VZ
708 tm = gmtime(&time);
709 }
b76b015e
VZ
710
711 // should never happen
1ef54dcf 712 wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
b76b015e 713
299fcbfe 714 return Tm(*tm, tz);
b76b015e
VZ
715 }
716 else
717 {
1ef54dcf
VZ
718 // remember the time and do the calculations with the date only - this
719 // eliminates rounding errors of the floating point arithmetics
e6ec579c 720
151d66be 721 wxLongLong timeMidnight = m_time + tz.GetOffset() * 1000;
299fcbfe
VZ
722
723 long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
1ef54dcf 724
299fcbfe
VZ
725 // we want to always have positive time and timeMidnight to be really
726 // the midnight before it
1ef54dcf
VZ
727 if ( timeOnly < 0 )
728 {
299fcbfe 729 timeOnly = MILLISECONDS_PER_DAY + timeOnly;
1ef54dcf
VZ
730 }
731
e6ec579c
VZ
732 timeMidnight -= timeOnly;
733
1ef54dcf
VZ
734 // calculate the Gregorian date from JDN for the midnight of our date:
735 // this will yield day, month (in 1..12 range) and year
736
737 // actually, this is the JDN for the noon of the previous day
738 long jdn = (timeMidnight / MILLISECONDS_PER_DAY).ToLong() + EPOCH_JDN;
739
740 // CREDIT: code below is by Scott E. Lee (but bugs are mine)
741
742 wxASSERT_MSG( jdn > -2, _T("JDN out of range") );
743
744 // calculate the century
745 int temp = (jdn + JDN_OFFSET) * 4 - 1;
746 int century = temp / DAYS_PER_400_YEARS;
747
748 // then the year and day of year (1 <= dayOfYear <= 366)
749 temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
750 int year = (century * 100) + (temp / DAYS_PER_4_YEARS);
751 int dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
752
753 // and finally the month and day of the month
754 temp = dayOfYear * 5 - 3;
755 int month = temp / DAYS_PER_5_MONTHS;
756 int day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
757
758 // month is counted from March - convert to normal
759 if ( month < 10 )
e6ec579c 760 {
1ef54dcf 761 month += 3;
e6ec579c 762 }
1ef54dcf
VZ
763 else
764 {
765 year += 1;
766 month -= 9;
767 }
768
769 // year is offset by 4800
770 year -= 4800;
771
772 // check that the algorithm gave us something reasonable
773 wxASSERT_MSG( (0 < month) && (month <= 12), _T("invalid month") );
774 wxASSERT_MSG( (1 <= day) && (day < 32), _T("invalid day") );
775 wxASSERT_MSG( (INT_MIN <= year) && (year <= INT_MAX),
776 _T("year range overflow") );
e6ec579c 777
1ef54dcf 778 // construct Tm from these values
e6ec579c 779 Tm tm;
1ef54dcf 780 tm.year = (int)year;
e6ec579c 781 tm.mon = (Month)(month - 1); // algorithm yields 1 for January, not 0
1ef54dcf 782 tm.mday = (wxDateTime_t)day;
e6ec579c
VZ
783 tm.msec = timeOnly % 1000;
784 timeOnly -= tm.msec;
785 timeOnly /= 1000; // now we have time in seconds
786
787 tm.sec = timeOnly % 60;
788 timeOnly -= tm.sec;
789 timeOnly /= 60; // now we have time in minutes
790
791 tm.min = timeOnly % 60;
792 timeOnly -= tm.min;
793
794 tm.hour = timeOnly / 60;
b76b015e 795
e6ec579c 796 return tm;
0979c962 797 }
b76b015e
VZ
798}
799
800wxDateTime& wxDateTime::SetYear(int year)
801{
802 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
803
804 Tm tm(GetTm());
805 tm.year = year;
806 Set(tm);
807
808 return *this;
809}
810
811wxDateTime& wxDateTime::SetMonth(Month month)
812{
813 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
814
815 Tm tm(GetTm());
816 tm.mon = month;
817 Set(tm);
818
819 return *this;
820}
821
822wxDateTime& wxDateTime::SetDay(wxDateTime_t mday)
823{
824 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
825
826 Tm tm(GetTm());
827 tm.mday = mday;
828 Set(tm);
829
830 return *this;
831}
832
833wxDateTime& wxDateTime::SetHour(wxDateTime_t hour)
834{
835 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
836
837 Tm tm(GetTm());
838 tm.hour = hour;
839 Set(tm);
840
841 return *this;
842}
843
844wxDateTime& wxDateTime::SetMinute(wxDateTime_t min)
845{
846 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
847
848 Tm tm(GetTm());
849 tm.min = min;
850 Set(tm);
851
852 return *this;
853}
854
855wxDateTime& wxDateTime::SetSecond(wxDateTime_t sec)
856{
857 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
858
859 Tm tm(GetTm());
860 tm.sec = sec;
861 Set(tm);
0979c962
VZ
862
863 return *this;
864}
b76b015e
VZ
865
866wxDateTime& wxDateTime::SetMillisecond(wxDateTime_t millisecond)
867{
868 wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
869
870 // we don't need to use GetTm() for this one
871 m_time -= m_time % 1000l;
872 m_time += millisecond;
873
874 return *this;
875}
876
877// ----------------------------------------------------------------------------
878// wxDateTime arithmetics
879// ----------------------------------------------------------------------------
880
881wxDateTime& wxDateTime::Add(const wxDateSpan& diff)
882{
883 Tm tm(GetTm());
884
885 tm.year += diff.GetYears();
fcc3d7cb
VZ
886 tm.AddMonths(diff.GetMonths());
887 tm.AddDays(diff.GetTotalDays());
b76b015e
VZ
888
889 Set(tm);
890
891 return *this;
892}
893
2f02cb89
VZ
894// ----------------------------------------------------------------------------
895// Weekday and monthday stuff
896// ----------------------------------------------------------------------------
897
898wxDateTime& wxDateTime::SetToLastMonthDay(Month month,
899 int year)
900{
901 // take the current month/year if none specified
902 ReplaceDefaultYearMonthWithCurrent(&year, &month);
903
fcc3d7cb 904 return Set(GetNumOfDaysInMonth(year, month), month, year);
2f02cb89
VZ
905}
906
907bool wxDateTime::SetToWeekDay(WeekDay weekday,
908 int n,
909 Month month,
910 int year)
911{
912 wxCHECK_MSG( weekday != Inv_WeekDay, FALSE, _T("invalid weekday") );
913
914 // we don't check explicitly that -5 <= n <= 5 because we will return FALSE
915 // anyhow in such case - but may be should still give an assert for it?
916
917 // take the current month/year if none specified
918 ReplaceDefaultYearMonthWithCurrent(&year, &month);
919
920 wxDateTime dt;
921
922 // TODO this probably could be optimised somehow...
923
924 if ( n > 0 )
925 {
926 // get the first day of the month
927 dt.Set(1, month, year);
928
929 // get its wday
930 WeekDay wdayFirst = dt.GetWeekDay();
931
932 // go to the first weekday of the month
933 int diff = weekday - wdayFirst;
934 if ( diff < 0 )
935 diff += 7;
936
937 // add advance n-1 weeks more
938 diff += 7*(n - 1);
939
940 dt -= wxDateSpan::Days(diff);
941 }
942 else
943 {
944 // get the last day of the month
945 dt.SetToLastMonthDay(month, year);
946
947 // get its wday
948 WeekDay wdayLast = dt.GetWeekDay();
949
950 // go to the last weekday of the month
951 int diff = wdayLast - weekday;
952 if ( diff < 0 )
953 diff += 7;
954
955 // and rewind n-1 weeks from there
956 diff += 7*(n - 1);
957
958 dt -= wxDateSpan::Days(diff);
959 }
960
961 // check that it is still in the same month
962 if ( dt.GetMonth() == month )
963 {
964 *this = dt;
965
966 return TRUE;
967 }
968 else
969 {
970 // no such day in this month
971 return FALSE;
972 }
973}
974
e6ec579c
VZ
975// ----------------------------------------------------------------------------
976// Julian day number conversion and related stuff
977// ----------------------------------------------------------------------------
978
979double wxDateTime::GetJulianDayNumber() const
980{
299fcbfe
VZ
981 // JDN are always expressed for the GMT dates
982 Tm tm(ToTimezone(GMT0).GetTm(GMT0));
e6ec579c
VZ
983
984 double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
985
986 // add the part GetTruncatedJDN() neglected
987 result += 0.5;
988
989 // and now add the time: 86400 sec = 1 JDN
990 return result + ((double)(60*(60*tm.hour + tm.min) + tm.sec)) / 86400;
991}
992
993double wxDateTime::GetRataDie() const
994{
995 // March 1 of the year 0 is Rata Die day -306 and JDN 1721119.5
996 return GetJulianDayNumber() - 1721119.5 - 306;
997}
998
fcc3d7cb 999// ----------------------------------------------------------------------------
299fcbfe 1000// timezone and DST stuff
fcc3d7cb
VZ
1001// ----------------------------------------------------------------------------
1002
299fcbfe 1003int wxDateTime::IsDST(wxDateTime::Country country) const
fcc3d7cb 1004{
299fcbfe
VZ
1005 wxCHECK_MSG( country == Country_Default, -1,
1006 _T("country support not implemented") );
1007
1008 // use the C RTL for the dates in the standard range
1009 time_t timet = GetTicks();
1010 if ( timet != (time_t)-1 )
1011 {
1012 tm *tm = localtime(&timet);
1013
1014 wxCHECK_MSG( tm, -1, _T("localtime() failed") );
1015
1016 return tm->tm_isdst;
1017 }
1018 else
1019 {
1020 // wxFAIL_MSG( _T("TODO") );
1021
1022 return -1;
1023 }
fcc3d7cb
VZ
1024}
1025
1026wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz)
1027{
299fcbfe 1028 int secDiff = GetTimeZone() + tz.GetOffset();
fcc3d7cb 1029
299fcbfe
VZ
1030 // we need to know whether DST is or not in effect for this date
1031 if ( IsDST() == 1 )
1032 {
1033 // FIXME we assume that the DST is always shifted by 1 hour
1034 secDiff -= 3600;
1035 }
1036
1037 return Substract(wxTimeSpan::Seconds(secDiff));
fcc3d7cb
VZ
1038}
1039
b76b015e
VZ
1040// ----------------------------------------------------------------------------
1041// wxDateTime to/from text representations
1042// ----------------------------------------------------------------------------
1043
299fcbfe 1044wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
b76b015e 1045{
e6ec579c
VZ
1046 wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
1047
b76b015e
VZ
1048 time_t time = GetTicks();
1049 if ( time != (time_t)-1 )
1050 {
1051 // use strftime()
299fcbfe
VZ
1052 tm *tm;
1053 if ( tz.GetOffset() == -GetTimeZone() )
1054 {
1055 // we are working with local time
1056 tm = localtime(&time);
1057 }
1058 else
1059 {
1060 time += tz.GetOffset();
1061
1062 tm = gmtime(&time);
1063 }
b76b015e
VZ
1064
1065 // should never happen
1ef54dcf 1066 wxCHECK_MSG( tm, _T(""), _T("gmtime() failed") );
b76b015e
VZ
1067
1068 return CallStrftime(format, tm);
1069 }
1070 else
1071 {
e6ec579c
VZ
1072 // use a hack and still use strftime(): make a copy of the format and
1073 // replace all occurences of YEAR in it with some unique string not
1074 // appearing anywhere else in it, then use strftime() to format the
1075 // date in year YEAR and then replace YEAR back by the real year and
1076 // the unique replacement string back with YEAR where YEAR is any year
1077 // in the range supported by strftime() (1970 - 2037) which is equal to
1078 // the real year modulo 28 (so the week days coincide for them)
1079
1080 // find the YEAR
299fcbfe 1081 int yearReal = GetYear(tz);
e6ec579c
VZ
1082 int year = 1970 + yearReal % 28;
1083
1084 wxString strYear;
1085 strYear.Printf(_T("%d"), year);
1086
1087 // find a string not occuring in format (this is surely not optimal way
1088 // of doing it... improvements welcome!)
1089 wxString fmt = format;
1090 wxString replacement = (wxChar)-1;
1091 while ( fmt.Find(replacement) != wxNOT_FOUND )
1092 {
1093 replacement << (wxChar)-1;
1094 }
1095
1096 // replace all occurences of year with it
1097 bool wasReplaced = fmt.Replace(strYear, replacement) > 0;
1098
1099 // use strftime() to format the same date but in supported year
1100 wxDateTime dt(*this);
1101 dt.SetYear(year);
299fcbfe 1102 wxString str = dt.Format(format, tz);
b76b015e 1103
e6ec579c
VZ
1104 // now replace the occurence of 1999 with the real year
1105 wxString strYearReal;
1106 strYearReal.Printf(_T("%d"), yearReal);
1107 str.Replace(strYear, strYearReal);
1108
1109 // and replace back all occurences of replacement string
1110 if ( wasReplaced )
1111 str.Replace(replacement, strYear);
1112
1113 return str;
b76b015e
VZ
1114 }
1115}
fcc3d7cb
VZ
1116
1117// ============================================================================
1118// wxTimeSpan
1119// ============================================================================
1120
e6ec579c
VZ
1121// not all strftime(3) format specifiers make sense here because, for example,
1122// a time span doesn't have a year nor a timezone
1123//
1124// Here are the ones which are supported (all of them are supported by strftime
1125// as well):
1126// %H hour in 24 hour format
1127// %M minute (00 - 59)
1128// %S second (00 - 59)
1129// %% percent sign
1130//
1131// Also, for MFC CTimeSpan compatibility, we support
1132// %D number of days
1133//
1134// And, to be better than MFC :-), we also have
1135// %E number of wEeks
1136// %l milliseconds (000 - 999)
fcc3d7cb
VZ
1137wxString wxTimeSpan::Format(const wxChar *format) const
1138{
e6ec579c 1139 wxCHECK_MSG( format, _T(""), _T("NULL format in wxTimeSpan::Format") );
fcc3d7cb
VZ
1140
1141 wxString str;
e6ec579c
VZ
1142 str.Alloc(strlen(format));
1143
1144 for ( const wxChar *pch = format; pch; pch++ )
1145 {
1146 wxChar ch = *pch;
1147
1148 if ( ch == '%' )
1149 {
1150 wxString tmp;
1151
1152 ch = *pch++;
1153 switch ( ch )
1154 {
1155 default:
1156 wxFAIL_MSG( _T("invalid format character") );
1157 // fall through
1158
1159 case '%':
1160 // will get to str << ch below
1161 break;
1162
1163 case 'D':
1164 tmp.Printf(_T("%d"), GetDays());
1165 break;
1166
1167 case 'E':
1168 tmp.Printf(_T("%d"), GetWeeks());
1169 break;
1170
1171 case 'H':
1172 tmp.Printf(_T("%02d"), GetHours());
1173 break;
1174
1175 case 'l':
1176 tmp.Printf(_T("%03d"), GetMilliseconds());
1177 break;
1178
1179 case 'M':
1180 tmp.Printf(_T("%02d"), GetMinutes());
1181 break;
1182
1183 case 'S':
1184 tmp.Printf(_T("%02d"), GetSeconds());
1185 break;
1186 }
1187
1188 if ( !!tmp )
1189 {
1190 str += tmp;
1191
1192 // skip str += ch below
1193 continue;
1194 }
1195 }
1196
1197 str += ch;
1198 }
fcc3d7cb
VZ
1199
1200 return str;
1201}