1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/datetimefmt.cpp
3 // Purpose: wxDateTime formatting & parsing code
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // parts of code taken from sndcal library by Scott E. Lee:
11 // Copyright 1993-1995, Scott E. Lee, all rights reserved.
12 // Permission granted to use, copy, modify, distribute and sell
13 // so long as the above copyright and this permission statement
14 // are retained in all copies.
16 // Licence: wxWindows licence
17 ///////////////////////////////////////////////////////////////////////////////
19 // ============================================================================
21 // ============================================================================
23 // ----------------------------------------------------------------------------
25 // ----------------------------------------------------------------------------
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
34 #if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
38 #include "wx/msw/wrapwin.h"
40 #include "wx/string.h"
43 #include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
44 #include "wx/module.h"
48 #include "wx/thread.h"
49 #include "wx/tokenzr.h"
60 #include "wx/datetime.h"
62 // ============================================================================
63 // implementation of wxDateTime
64 // ============================================================================
66 // ----------------------------------------------------------------------------
67 // helpers shared between datetime.cpp and datetimefmt.cpp
68 // ----------------------------------------------------------------------------
70 extern void InitTm(struct tm
& tm
);
72 extern int GetTimeZone();
74 extern wxString
CallStrftime(const wxString
& format
, const tm
* tm
);
76 // ----------------------------------------------------------------------------
77 // constants (see also datetime.cpp)
78 // ----------------------------------------------------------------------------
80 static const int DAYS_PER_WEEK
= 7;
82 static const int HOURS_PER_DAY
= 24;
84 static const int SEC_PER_MIN
= 60;
86 static const int MIN_PER_HOUR
= 60;
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
97 #if wxUSE_UNIX && !defined(HAVE_STRPTIME_DECL)
98 // configure detected that we had strptime() but not its declaration,
99 // provide it ourselves
100 extern "C" char *strptime(const char *, const char *, struct tm
*);
103 // strptime() wrapper: call strptime() for the string starting at the given
104 // iterator and fill output tm struct with the results and modify input to
105 // point to the end of the string consumed by strptime() if successful,
106 // otherwise return false and don't modify anything
108 CallStrptime(const wxString
& str
,
109 wxString::const_iterator
& p
,
113 // convert from iterator to char pointer: this is simple as wxCStrData
114 // already supports this
115 const char * const start
= str
.c_str() + (p
- str
.begin());
117 const char * const end
= strptime(start
, fmt
, tm
);
121 // convert back from char pointer to iterator: unfortunately we have no way
122 // to do it efficiently currently so create a temporary string just to
123 // compute the number of characters between start and end
124 p
+= wxString(start
, end
- start
).length();
129 #endif // HAVE_STRPTIME
133 DateLang_English
= 1,
137 // return the month if the string is a month name or Inv_Month otherwise
139 // flags can contain wxDateTime::Name_Abbr/Name_Full or both of them and lang
140 // can be either DateLang_Local (default) to interpret string as a localized
141 // month name or DateLang_English to parse it as a standard English name or
142 // their combination to interpret it in any way
144 GetMonthFromName(const wxString
& name
, int flags
, int lang
)
146 wxDateTime::Month mon
;
147 for ( mon
= wxDateTime::Jan
; mon
< wxDateTime::Inv_Month
; wxNextMonth(mon
) )
149 // case-insensitive comparison either one of or with both abbreviated
151 if ( flags
& wxDateTime::Name_Full
)
153 if ( lang
& DateLang_English
)
155 if ( name
.CmpNoCase(wxDateTime::GetEnglishMonthName(mon
,
156 wxDateTime::Name_Full
)) == 0 )
160 if ( lang
& DateLang_Local
)
162 if ( name
.CmpNoCase(wxDateTime::GetMonthName(mon
,
163 wxDateTime::Name_Full
)) == 0 )
168 if ( flags
& wxDateTime::Name_Abbr
)
170 if ( lang
& DateLang_English
)
172 if ( name
.CmpNoCase(wxDateTime::GetEnglishMonthName(mon
,
173 wxDateTime::Name_Abbr
)) == 0 )
177 if ( lang
& DateLang_Local
)
179 if ( name
.CmpNoCase(wxDateTime::GetMonthName(mon
,
180 wxDateTime::Name_Abbr
)) == 0 )
189 // return the weekday if the string is a weekday name or Inv_WeekDay otherwise
191 // flags and lang parameters have the same meaning as for GetMonthFromName()
194 GetWeekDayFromName(const wxString
& name
, int flags
, int lang
)
196 wxDateTime::WeekDay wd
;
197 for ( wd
= wxDateTime::Sun
; wd
< wxDateTime::Inv_WeekDay
; wxNextWDay(wd
) )
199 if ( flags
& wxDateTime::Name_Full
)
201 if ( lang
& DateLang_English
)
203 if ( name
.CmpNoCase(wxDateTime::GetEnglishWeekDayName(wd
,
204 wxDateTime::Name_Full
)) == 0 )
208 if ( lang
& DateLang_Local
)
210 if ( name
.CmpNoCase(wxDateTime::GetWeekDayName(wd
,
211 wxDateTime::Name_Full
)) == 0 )
216 if ( flags
& wxDateTime::Name_Abbr
)
218 if ( lang
& DateLang_English
)
220 if ( name
.CmpNoCase(wxDateTime::GetEnglishWeekDayName(wd
,
221 wxDateTime::Name_Abbr
)) == 0 )
225 if ( lang
& DateLang_Local
)
227 if ( name
.CmpNoCase(wxDateTime::GetWeekDayName(wd
,
228 wxDateTime::Name_Abbr
)) == 0 )
237 // scans all digits (but no more than len) and returns the resulting number
238 bool GetNumericToken(size_t len
,
239 wxString::const_iterator
& p
,
240 unsigned long *number
)
244 while ( wxIsdigit(*p
) )
248 if ( len
&& ++n
> len
)
252 return !s
.empty() && s
.ToULong(number
);
255 // scans all alphabetic characters and returns the resulting string
256 wxString
GetAlphaToken(wxString::const_iterator
& p
)
259 while ( wxIsalpha(*p
) )
267 // parses string starting at given iterator using the specified format and,
268 // optionally, a fall back format (and optionally another one... but it stops
271 // if unsuccessful, returns invalid wxDateTime without changing p; otherwise
272 // advance p to the end of the match and returns wxDateTime containing the
273 // results of the parsing
275 ParseFormatAt(wxString::const_iterator
& p
,
276 const wxString::const_iterator
& end
,
278 // FIXME-VC6: using wxString() instead of wxEmptyString in the
279 // line below results in error C2062: type 'class
280 // wxString (__cdecl *)(void)' unexpected
281 const wxString
& fmtAlt
= wxEmptyString
,
282 const wxString
& fmtAlt2
= wxString())
284 const wxString
str(p
, end
);
285 wxString::const_iterator endParse
;
287 if ( dt
.ParseFormat(str
, fmt
, &endParse
) ||
288 (!fmtAlt
.empty() && dt
.ParseFormat(str
, fmtAlt
, &endParse
)) ||
289 (!fmtAlt2
.empty() && dt
.ParseFormat(str
, fmtAlt2
, &endParse
)) )
291 p
+= endParse
- str
.begin();
293 //else: all formats failed
298 } // anonymous namespace
300 // ----------------------------------------------------------------------------
301 // wxDateTime to/from text representations
302 // ----------------------------------------------------------------------------
304 wxString
wxDateTime::Format(const wxString
& format
, const TimeZone
& tz
) const
306 wxCHECK_MSG( !format
.empty(), wxEmptyString
,
307 _T("NULL format in wxDateTime::Format") );
309 // we have to use our own implementation if the date is out of range of
310 // strftime() or if we use non standard specificators
312 time_t time
= GetTicks();
314 if ( (time
!= (time_t)-1) && !wxStrstr(format
, _T("%l")) )
319 if ( tz
.GetOffset() == -GetTimeZone() )
321 // we are working with local time
322 tm
= wxLocaltime_r(&time
, &tmstruct
);
324 // should never happen
325 wxCHECK_MSG( tm
, wxEmptyString
, _T("wxLocaltime_r() failed") );
329 time
+= (int)tz
.GetOffset();
331 #if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
332 int time2
= (int) time
;
338 tm
= wxGmtime_r(&time
, &tmstruct
);
340 // should never happen
341 wxCHECK_MSG( tm
, wxEmptyString
, _T("wxGmtime_r() failed") );
345 tm
= (struct tm
*)NULL
;
351 return CallStrftime(format
, tm
);
354 //else: use generic code below
355 #endif // HAVE_STRFTIME
357 // we only parse ANSI C format specifications here, no POSIX 2
358 // complications, no GNU extensions but we do add support for a "%l" format
359 // specifier allowing to get the number of milliseconds
362 // used for calls to strftime() when we only deal with time
363 struct tm tmTimeOnly
;
364 tmTimeOnly
.tm_hour
= tm
.hour
;
365 tmTimeOnly
.tm_min
= tm
.min
;
366 tmTimeOnly
.tm_sec
= tm
.sec
;
367 tmTimeOnly
.tm_wday
= 0;
368 tmTimeOnly
.tm_yday
= 0;
369 tmTimeOnly
.tm_mday
= 1; // any date will do
370 tmTimeOnly
.tm_mon
= 0;
371 tmTimeOnly
.tm_year
= 76;
372 tmTimeOnly
.tm_isdst
= 0; // no DST, we adjust for tz ourselves
374 wxString tmp
, res
, fmt
;
375 for ( wxString::const_iterator p
= format
.begin(); p
!= format
.end(); ++p
)
385 // set the default format
386 switch ( (*++p
).GetValue() )
388 case _T('Y'): // year has 4 digits
392 case _T('j'): // day of year has 3 digits
393 case _T('l'): // milliseconds have 3 digits
397 case _T('w'): // week day as number has only one
402 // it's either another valid format specifier in which case
403 // the format is "%02d" (for all the rest) or we have the
404 // field width preceding the format in which case it will
405 // override the default format anyhow
414 // start of the format specification
415 switch ( (*p
).GetValue() )
417 case _T('a'): // a weekday name
419 // second parameter should be true for abbreviated names
420 res
+= GetWeekDayName(tm
.GetWeekDay(),
421 *p
== _T('a') ? Name_Abbr
: Name_Full
);
424 case _T('b'): // a month name
426 res
+= GetMonthName(tm
.mon
,
427 *p
== _T('b') ? Name_Abbr
: Name_Full
);
430 case _T('c'): // locale default date and time representation
431 case _T('x'): // locale default date representation
434 // the problem: there is no way to know what do these format
435 // specifications correspond to for the current locale.
437 // the solution: use a hack and still use strftime(): first
438 // find the YEAR which is a year in the strftime() range (1970
439 // - 2038) whose Jan 1 falls on the same week day as the Jan 1
440 // of the real year. Then make a copy of the format and
441 // replace all occurrences of YEAR in it with some unique
442 // string not appearing anywhere else in it, then use
443 // strftime() to format the date in year YEAR and then replace
444 // YEAR back by the real year and the unique replacement
445 // string back with YEAR. Notice that "all occurrences of YEAR"
446 // means all occurrences of 4 digit as well as 2 digit form!
448 // the bugs: we assume that neither of %c nor %x contains any
449 // fields which may change between the YEAR and real year. For
450 // example, the week number (%U, %W) and the day number (%j)
451 // will change if one of these years is leap and the other one
454 // find the YEAR: normally, for any year X, Jan 1 of the
455 // year X + 28 is the same weekday as Jan 1 of X (because
456 // the weekday advances by 1 for each normal X and by 2
457 // for each leap X, hence by 5 every 4 years or by 35
458 // which is 0 mod 7 every 28 years) but this rule breaks
459 // down if there are years between X and Y which are
460 // divisible by 4 but not leap (i.e. divisible by 100 but
461 // not 400), hence the correction.
463 int yearReal
= GetYear(tz
);
464 int mod28
= yearReal
% 28;
466 // be careful to not go too far - we risk to leave the
471 year
= 1988 + mod28
; // 1988 == 0 (mod 28)
475 year
= 1970 + mod28
- 10; // 1970 == 10 (mod 28)
478 int nCentury
= year
/ 100,
479 nCenturyReal
= yearReal
/ 100;
481 // need to adjust for the years divisble by 400 which are
482 // not leap but are counted like leap ones if we just take
483 // the number of centuries in between for nLostWeekDays
484 int nLostWeekDays
= (nCentury
- nCenturyReal
) -
485 (nCentury
/ 4 - nCenturyReal
/ 4);
487 // we have to gain back the "lost" weekdays: note that the
488 // effect of this loop is to not do anything to
489 // nLostWeekDays (which we won't use any more), but to
490 // (indirectly) set the year correctly
491 while ( (nLostWeekDays
% 7) != 0 )
493 nLostWeekDays
+= year
++ % 4 ? 1 : 2;
496 // finally move the year below 2000 so that the 2-digit
497 // year number can never match the month or day of the
498 // month when we do the replacements below
502 wxASSERT_MSG( year
>= 1970 && year
< 2000,
503 _T("logic error in wxDateTime::Format") );
506 // use strftime() to format the same date but in supported
509 // NB: we assume that strftime() doesn't check for the
510 // date validity and will happily format the date
511 // corresponding to Feb 29 of a non leap year (which
512 // may happen if yearReal was leap and year is not)
513 struct tm tmAdjusted
;
515 tmAdjusted
.tm_hour
= tm
.hour
;
516 tmAdjusted
.tm_min
= tm
.min
;
517 tmAdjusted
.tm_sec
= tm
.sec
;
518 tmAdjusted
.tm_wday
= tm
.GetWeekDay();
519 tmAdjusted
.tm_yday
= GetDayOfYear();
520 tmAdjusted
.tm_mday
= tm
.mday
;
521 tmAdjusted
.tm_mon
= tm
.mon
;
522 tmAdjusted
.tm_year
= year
- 1900;
523 tmAdjusted
.tm_isdst
= 0; // no DST, already adjusted
524 wxString str
= CallStrftime(*p
== _T('c') ? _T("%c")
528 // now replace the replacement year with the real year:
529 // notice that we have to replace the 4 digit year with
530 // a unique string not appearing in strftime() output
531 // first to prevent the 2 digit year from matching any
532 // substring of the 4 digit year (but any day, month,
533 // hours or minutes components should be safe because
534 // they are never in 70-99 range)
535 wxString
replacement("|");
536 while ( str
.find(replacement
) != wxString::npos
)
539 str
.Replace(wxString::Format("%d", year
),
541 str
.Replace(wxString::Format("%d", year
% 100),
542 wxString::Format("%d", yearReal
% 100));
543 str
.Replace(replacement
,
544 wxString::Format("%d", yearReal
));
548 #else // !HAVE_STRFTIME
549 // Use "%m/%d/%y %H:%M:%S" format instead
550 res
+= wxString::Format(wxT("%02d/%02d/%04d %02d:%02d:%02d"),
551 tm
.mon
+1,tm
.mday
, tm
.year
, tm
.hour
, tm
.min
, tm
.sec
);
552 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
555 case _T('d'): // day of a month (01-31)
556 res
+= wxString::Format(fmt
, tm
.mday
);
559 case _T('H'): // hour in 24h format (00-23)
560 res
+= wxString::Format(fmt
, tm
.hour
);
563 case _T('I'): // hour in 12h format (01-12)
565 // 24h -> 12h, 0h -> 12h too
566 int hour12
= tm
.hour
> 12 ? tm
.hour
- 12
567 : tm
.hour
? tm
.hour
: 12;
568 res
+= wxString::Format(fmt
, hour12
);
572 case _T('j'): // day of the year
573 res
+= wxString::Format(fmt
, GetDayOfYear(tz
));
576 case _T('l'): // milliseconds (NOT STANDARD)
577 res
+= wxString::Format(fmt
, GetMillisecond(tz
));
580 case _T('m'): // month as a number (01-12)
581 res
+= wxString::Format(fmt
, tm
.mon
+ 1);
584 case _T('M'): // minute as a decimal number (00-59)
585 res
+= wxString::Format(fmt
, tm
.min
);
588 case _T('p'): // AM or PM string
590 res
+= CallStrftime(_T("%p"), &tmTimeOnly
);
591 #else // !HAVE_STRFTIME
592 res
+= (tmTimeOnly
.tm_hour
> 12) ? wxT("pm") : wxT("am");
593 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
596 case _T('S'): // second as a decimal number (00-61)
597 res
+= wxString::Format(fmt
, tm
.sec
);
600 case _T('U'): // week number in the year (Sunday 1st week day)
601 res
+= wxString::Format(fmt
, GetWeekOfYear(Sunday_First
, tz
));
604 case _T('W'): // week number in the year (Monday 1st week day)
605 res
+= wxString::Format(fmt
, GetWeekOfYear(Monday_First
, tz
));
608 case _T('w'): // weekday as a number (0-6), Sunday = 0
609 res
+= wxString::Format(fmt
, tm
.GetWeekDay());
612 // case _T('x'): -- handled with "%c"
614 case _T('X'): // locale default time representation
615 // just use strftime() to format the time for us
617 res
+= CallStrftime(_T("%X"), &tmTimeOnly
);
618 #else // !HAVE_STRFTIME
619 res
+= wxString::Format(wxT("%02d:%02d:%02d"),tm
.hour
, tm
.min
, tm
.sec
);
620 #endif // HAVE_STRFTIME/!HAVE_STRFTIME
623 case _T('y'): // year without century (00-99)
624 res
+= wxString::Format(fmt
, tm
.year
% 100);
627 case _T('Y'): // year with century
628 res
+= wxString::Format(fmt
, tm
.year
);
631 case _T('Z'): // timezone name
633 res
+= CallStrftime(_T("%Z"), &tmTimeOnly
);
638 // is it the format width?
640 while ( *p
== _T('-') || *p
== _T('+') ||
641 *p
== _T(' ') || wxIsdigit(*p
) )
648 // we've only got the flags and width so far in fmt
649 fmt
.Prepend(_T('%'));
657 // no, it wasn't the width
658 wxFAIL_MSG(_T("unknown format specificator"));
660 // fall through and just copy it nevertheless
662 case _T('%'): // a percent sign
666 case 0: // the end of string
667 wxFAIL_MSG(_T("missing format at the end of string"));
669 // just put the '%' which was the last char in format
679 // this function parses a string in (strict) RFC 822 format: see the section 5
680 // of the RFC for the detailed description, but briefly it's something of the
681 // form "Sat, 18 Dec 1999 00:48:30 +0100"
683 // this function is "strict" by design - it must reject anything except true
684 // RFC822 time specs.
686 wxDateTime::ParseRfc822Date(const wxString
& date
, wxString::const_iterator
*end
)
688 wxString::const_iterator p
= date
.begin();
691 static const int WDAY_LEN
= 3;
692 const wxString::const_iterator endWday
= p
+ WDAY_LEN
;
693 const wxString
wday(p
, endWday
);
694 if ( GetWeekDayFromName(wday
, Name_Abbr
, DateLang_English
) == Inv_WeekDay
)
695 return wxAnyStrPtr();
696 //else: ignore week day for now, we could also check that it really
697 // corresponds to the specified date
701 // 2. separating comma
702 if ( *p
++ != ',' || *p
++ != ' ' )
703 return wxAnyStrPtr();
706 if ( !wxIsdigit(*p
) )
707 return wxAnyStrPtr();
709 wxDateTime_t day
= (wxDateTime_t
)(*p
++ - '0');
713 day
= (wxDateTime_t
)(day
+ (*p
++ - '0'));
717 return wxAnyStrPtr();
720 static const int MONTH_LEN
= 3;
721 const wxString::const_iterator endMonth
= p
+ MONTH_LEN
;
722 const wxString
monName(p
, endMonth
);
723 Month mon
= GetMonthFromName(monName
, Name_Abbr
, DateLang_English
);
724 if ( mon
== Inv_Month
)
725 return wxAnyStrPtr();
730 return wxAnyStrPtr();
733 if ( !wxIsdigit(*p
) )
734 return wxAnyStrPtr();
736 int year
= *p
++ - '0';
737 if ( !wxIsdigit(*p
) ) // should have at least 2 digits in the year
738 return wxAnyStrPtr();
743 // is it a 2 digit year (as per original RFC 822) or a 4 digit one?
749 if ( !wxIsdigit(*p
) )
751 // no 3 digit years please
752 return wxAnyStrPtr();
760 return wxAnyStrPtr();
762 // 6. time in hh:mm:ss format with seconds being optional
763 if ( !wxIsdigit(*p
) )
764 return wxAnyStrPtr();
766 wxDateTime_t hour
= (wxDateTime_t
)(*p
++ - '0');
768 if ( !wxIsdigit(*p
) )
769 return wxAnyStrPtr();
772 hour
= (wxDateTime_t
)(hour
+ (*p
++ - '0'));
775 return wxAnyStrPtr();
777 if ( !wxIsdigit(*p
) )
778 return wxAnyStrPtr();
780 wxDateTime_t min
= (wxDateTime_t
)(*p
++ - '0');
782 if ( !wxIsdigit(*p
) )
783 return wxAnyStrPtr();
786 min
+= (wxDateTime_t
)(*p
++ - '0');
788 wxDateTime_t sec
= 0;
792 if ( !wxIsdigit(*p
) )
793 return wxAnyStrPtr();
795 sec
= (wxDateTime_t
)(*p
++ - '0');
797 if ( !wxIsdigit(*p
) )
798 return wxAnyStrPtr();
801 sec
+= (wxDateTime_t
)(*p
++ - '0');
805 return wxAnyStrPtr();
807 // 7. now the interesting part: the timezone
808 int offset
wxDUMMY_INITIALIZE(0);
809 if ( *p
== '-' || *p
== '+' )
811 // the explicit offset given: it has the form of hhmm
812 bool plus
= *p
++ == '+';
814 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
815 return wxAnyStrPtr();
819 offset
= MIN_PER_HOUR
*(10*(*p
- '0') + (*(p
+ 1) - '0'));
823 if ( !wxIsdigit(*p
) || !wxIsdigit(*(p
+ 1)) )
824 return wxAnyStrPtr();
827 offset
+= 10*(*p
- '0') + (*(p
+ 1) - '0');
836 // the symbolic timezone given: may be either military timezone or one
837 // of standard abbreviations
840 // military: Z = UTC, J unused, A = -1, ..., Y = +12
841 static const int offsets
[26] =
843 //A B C D E F G H I J K L M
844 -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
845 //N O P R Q S T U V W Z Y Z
846 +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
849 if ( *p
< _T('A') || *p
> _T('Z') || *p
== _T('J') )
850 return wxAnyStrPtr();
852 offset
= offsets
[*p
++ - 'A'];
857 const wxString
tz(p
, date
.end());
858 if ( tz
== _T("UT") || tz
== _T("UTC") || tz
== _T("GMT") )
860 else if ( tz
== _T("AST") )
862 else if ( tz
== _T("ADT") )
864 else if ( tz
== _T("EST") )
866 else if ( tz
== _T("EDT") )
868 else if ( tz
== _T("CST") )
870 else if ( tz
== _T("CDT") )
872 else if ( tz
== _T("MST") )
874 else if ( tz
== _T("MDT") )
876 else if ( tz
== _T("PST") )
878 else if ( tz
== _T("PDT") )
881 return wxAnyStrPtr();
887 offset
*= MIN_PER_HOUR
;
891 // the spec was correct, construct the date from the values we found
892 Set(day
, mon
, year
, hour
, min
, sec
);
893 MakeFromTimezone(TimeZone::Make(offset
*SEC_PER_MIN
));
898 return wxAnyStrPtr(date
, p
);
903 // returns the string containing strftime() format used for short dates in the
904 // current locale or an empty string
905 static wxString
GetLocaleDateFormat()
909 // there is no setlocale() under Windows CE, so just always query the
912 if ( strcmp(setlocale(LC_ALL
, NULL
), "C") != 0 )
915 // The locale was programatically set to non-C. We assume that this was
916 // done using wxLocale, in which case thread's current locale is also
917 // set to correct LCID value and we can use GetLocaleInfo to determine
918 // the correct formatting string:
920 LCID lcid
= LOCALE_USER_DEFAULT
;
922 LCID lcid
= GetThreadLocale();
924 // according to MSDN 80 chars is max allowed for short date format
926 if ( ::GetLocaleInfo(lcid
, LOCALE_SSHORTDATE
, fmt
, WXSIZEOF(fmt
)) )
928 wxChar chLast
= _T('\0');
929 size_t lastCount
= 0;
930 for ( const wxChar
*p
= fmt
; /* NUL handled inside */; p
++ )
940 // these characters come in groups, start counting them
950 // first deal with any special characters we have had
960 // these two are the same as we
961 // don't distinguish between 1 and
975 wxFAIL_MSG( _T("too many 'd's") );
984 // as for 'd' and 'dd' above
997 wxFAIL_MSG( _T("too many 'M's") );
1002 switch ( lastCount
)
1014 wxFAIL_MSG( _T("wrong number of 'y's") );
1019 // strftime() doesn't have era string,
1020 // ignore this format
1021 wxASSERT_MSG( lastCount
<= 2,
1022 _T("too many 'g's") );
1026 wxFAIL_MSG( _T("unreachable") );
1033 // not a special character so must be just a separator,
1035 if ( *p
!= _T('\0') )
1037 if ( *p
== _T('%') )
1039 // this one needs to be escaped
1047 if ( *p
== _T('\0') )
1051 //else: GetLocaleInfo() failed, leave fmtDate value unchanged and
1052 // try our luck with the default formats
1054 //else: default C locale, default formats should work
1059 #endif // __WINDOWS__
1062 wxDateTime::ParseFormat(const wxString
& date
,
1063 const wxString
& format
,
1064 const wxDateTime
& dateDef
,
1065 wxString::const_iterator
*end
)
1067 wxCHECK_MSG( !format
.empty(), wxAnyStrPtr(), "format can't be empty" );
1072 // what fields have we found?
1073 bool haveWDay
= false,
1083 bool hourIsIn12hFormat
= false, // or in 24h one?
1084 isPM
= false; // AM by default
1086 // and the value of the items we have (init them to get rid of warnings)
1087 wxDateTime_t msec
= 0,
1091 WeekDay wday
= Inv_WeekDay
;
1092 wxDateTime_t yday
= 0,
1094 wxDateTime::Month mon
= Inv_Month
;
1097 wxString::const_iterator input
= date
.begin();
1098 for ( wxString::const_iterator fmt
= format
.begin(); fmt
!= format
.end(); ++fmt
)
1100 if ( *fmt
!= _T('%') )
1102 if ( wxIsspace(*fmt
) )
1104 // a white space in the format string matches 0 or more white
1105 // spaces in the input
1106 while ( wxIsspace(*input
) )
1113 // any other character (not whitespace, not '%') must be
1114 // matched by itself in the input
1115 if ( *input
++ != *fmt
)
1118 return wxAnyStrPtr();
1122 // done with this format char
1126 // start of a format specification
1128 // parse the optional width
1130 while ( wxIsdigit(*++fmt
) )
1133 width
+= *fmt
- '0';
1136 // the default widths for the various fields
1139 switch ( (*fmt
).GetValue() )
1141 case _T('Y'): // year has 4 digits
1145 case _T('j'): // day of year has 3 digits
1146 case _T('l'): // milliseconds have 3 digits
1150 case _T('w'): // week day as number has only one
1155 // default for all other fields
1160 // then the format itself
1161 switch ( (*fmt
).GetValue() )
1163 case _T('a'): // a weekday name
1166 wday
= GetWeekDayFromName
1168 GetAlphaToken(input
),
1169 *fmt
== 'a' ? Name_Abbr
: Name_Full
,
1172 if ( wday
== Inv_WeekDay
)
1175 return wxAnyStrPtr();
1181 case _T('b'): // a month name
1184 mon
= GetMonthFromName
1186 GetAlphaToken(input
),
1187 *fmt
== 'b' ? Name_Abbr
: Name_Full
,
1190 if ( mon
== Inv_Month
)
1193 return wxAnyStrPtr();
1199 case _T('c'): // locale default date and time representation
1201 #ifdef HAVE_STRPTIME
1204 // try using strptime() -- it may fail even if the input is
1205 // correct but the date is out of range, so we will fall back
1206 // to our generic code anyhow
1207 if ( CallStrptime(date
, input
, "%c", &tm
) )
1213 year
= 1900 + tm
.tm_year
;
1214 mon
= (Month
)tm
.tm_mon
;
1217 else // strptime() failed; try generic heuristic code
1218 #endif // HAVE_STRPTIME
1221 // try the format which corresponds to ctime() output
1222 // first, then the generic date/time formats
1223 const wxDateTime dt
= ParseFormatAt
1227 wxS("%a %b %d %H:%M:%S %Y"),
1231 if ( !dt
.IsValid() )
1232 return wxAnyStrPtr();
1245 haveDay
= haveMon
= haveYear
=
1246 haveHour
= haveMin
= haveSec
= true;
1250 case _T('d'): // day of a month (01-31)
1251 if ( !GetNumericToken(width
, input
, &num
) ||
1252 (num
> 31) || (num
< 1) )
1255 return wxAnyStrPtr();
1258 // we can't check whether the day range is correct yet, will
1259 // do it later - assume ok for now
1261 mday
= (wxDateTime_t
)num
;
1264 case _T('H'): // hour in 24h format (00-23)
1265 if ( !GetNumericToken(width
, input
, &num
) || (num
> 23) )
1268 return wxAnyStrPtr();
1272 hour
= (wxDateTime_t
)num
;
1275 case _T('I'): // hour in 12h format (01-12)
1276 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
1279 return wxAnyStrPtr();
1283 hourIsIn12hFormat
= true;
1284 hour
= (wxDateTime_t
)(num
% 12); // 12 should be 0
1287 case _T('j'): // day of the year
1288 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 366) )
1291 return wxAnyStrPtr();
1295 yday
= (wxDateTime_t
)num
;
1298 case _T('l'): // milliseconds (0-999)
1299 if ( !GetNumericToken(width
, input
, &num
) )
1300 return wxAnyStrPtr();
1303 msec
= (wxDateTime_t
)num
;
1306 case _T('m'): // month as a number (01-12)
1307 if ( !GetNumericToken(width
, input
, &num
) || !num
|| (num
> 12) )
1310 return wxAnyStrPtr();
1314 mon
= (Month
)(num
- 1);
1317 case _T('M'): // minute as a decimal number (00-59)
1318 if ( !GetNumericToken(width
, input
, &num
) || (num
> 59) )
1321 return wxAnyStrPtr();
1325 min
= (wxDateTime_t
)num
;
1328 case _T('p'): // AM or PM string
1330 wxString am
, pm
, token
= GetAlphaToken(input
);
1332 // some locales have empty AM/PM tokens and thus when formatting
1333 // dates with the %p specifier nothing is generated; when trying to
1334 // parse them back, we get an empty token here... but that's not
1339 GetAmPmStrings(&am
, &pm
);
1340 if (am
.empty() && pm
.empty())
1341 return wxAnyStrPtr(); // no am/pm strings defined
1342 if ( token
.CmpNoCase(pm
) == 0 )
1346 else if ( token
.CmpNoCase(am
) != 0 )
1349 return wxAnyStrPtr();
1354 case _T('r'): // time as %I:%M:%S %p
1357 if ( !dt
.ParseFormat(wxString(input
, date
.end()),
1358 wxS("%I:%M:%S %p"), &input
) )
1359 return wxAnyStrPtr();
1361 haveHour
= haveMin
= haveSec
= true;
1370 case _T('R'): // time as %H:%M
1373 dt
= ParseFormatAt(input
, date
.end(), wxS("%H:%M"));
1374 if ( !dt
.IsValid() )
1375 return wxAnyStrPtr();
1386 case _T('S'): // second as a decimal number (00-61)
1387 if ( !GetNumericToken(width
, input
, &num
) || (num
> 61) )
1390 return wxAnyStrPtr();
1394 sec
= (wxDateTime_t
)num
;
1397 case _T('T'): // time as %H:%M:%S
1400 dt
= ParseFormatAt(input
, date
.end(), wxS("%H:%M:%S"));
1401 if ( !dt
.IsValid() )
1402 return wxAnyStrPtr();
1415 case _T('w'): // weekday as a number (0-6), Sunday = 0
1416 if ( !GetNumericToken(width
, input
, &num
) || (wday
> 6) )
1419 return wxAnyStrPtr();
1423 wday
= (WeekDay
)num
;
1426 case _T('x'): // locale default date representation
1427 #ifdef HAVE_STRPTIME
1428 // try using strptime() -- it may fail even if the input is
1429 // correct but the date is out of range, so we will fall back
1430 // to our generic code anyhow
1434 if ( CallStrptime(date
, input
, "%x", &tm
) )
1436 haveDay
= haveMon
= haveYear
= true;
1438 year
= 1900 + tm
.tm_year
;
1439 mon
= (Month
)tm
.tm_mon
;
1445 #endif // HAVE_STRPTIME
1452 // The above doesn't work for all locales, try to query
1453 // Windows for the right way of formatting the date:
1454 fmtDate
= GetLocaleDateFormat();
1455 if ( fmtDate
.empty() )
1456 #endif // __WINDOWS__
1458 if ( IsWestEuropeanCountry(GetCountry()) ||
1459 GetCountry() == Russia
)
1461 fmtDate
= _T("%d/%m/%y");
1462 fmtDateAlt
= _T("%m/%d/%y");
1466 fmtDate
= _T("%m/%d/%y");
1467 fmtDateAlt
= _T("%d/%m/%y");
1472 dt
= ParseFormatAt(input
, date
.end(),
1473 fmtDate
, fmtDateAlt
);
1474 if ( !dt
.IsValid() )
1475 return wxAnyStrPtr();
1490 case _T('X'): // locale default time representation
1491 #ifdef HAVE_STRPTIME
1493 // use strptime() to do it for us (FIXME !Unicode friendly)
1495 if ( !CallStrptime(date
, input
, "%X", &tm
) )
1496 return wxAnyStrPtr();
1498 haveHour
= haveMin
= haveSec
= true;
1504 #else // !HAVE_STRPTIME
1505 // TODO under Win32 we can query the LOCALE_ITIME system
1506 // setting which says whether the default time format is
1509 // try to parse what follows as "%H:%M:%S" and, if this
1510 // fails, as "%I:%M:%S %p" - this should catch the most
1513 dt
= ParseFormatAt(input
, date
.end(), "%T", "%r");
1514 if ( !dt
.IsValid() )
1515 return wxAnyStrPtr();
1526 #endif // HAVE_STRPTIME/!HAVE_STRPTIME
1529 case _T('y'): // year without century (00-99)
1530 if ( !GetNumericToken(width
, input
, &num
) || (num
> 99) )
1533 return wxAnyStrPtr();
1538 // TODO should have an option for roll over date instead of
1539 // hard coding it here
1540 year
= (num
> 30 ? 1900 : 2000) + (wxDateTime_t
)num
;
1543 case _T('Y'): // year with century
1544 if ( !GetNumericToken(width
, input
, &num
) )
1547 return wxAnyStrPtr();
1551 year
= (wxDateTime_t
)num
;
1554 case _T('Z'): // timezone name
1555 wxFAIL_MSG(_T("TODO"));
1558 case _T('%'): // a percent sign
1559 if ( *input
++ != _T('%') )
1562 return wxAnyStrPtr();
1566 case 0: // the end of string
1567 wxFAIL_MSG(_T("unexpected format end"));
1571 default: // not a known format spec
1572 return wxAnyStrPtr();
1576 // format matched, try to construct a date from what we have now
1578 if ( dateDef
.IsValid() )
1580 // take this date as default
1581 tmDef
= dateDef
.GetTm();
1583 else if ( IsValid() )
1585 // if this date is valid, don't change it
1590 // no default and this date is invalid - fall back to Today()
1591 tmDef
= Today().GetTm();
1607 // TODO we don't check here that the values are consistent, if both year
1608 // day and month/day were found, we just ignore the year day and we
1609 // also always ignore the week day
1612 if ( mday
> GetNumberOfDays(tm
.mon
, tm
.year
) )
1613 return wxAnyStrPtr();
1617 else if ( haveYDay
)
1619 if ( yday
> GetNumberOfDays(tm
.year
) )
1620 return wxAnyStrPtr();
1622 Tm tm2
= wxDateTime(1, Jan
, tm
.year
).SetToYearDay(yday
).GetTm();
1629 if ( haveHour
&& hourIsIn12hFormat
&& isPM
)
1631 // translate to 24hour format
1634 //else: either already in 24h format or no translation needed
1657 // finally check that the week day is consistent -- if we had it
1658 if ( haveWDay
&& GetWeekDay() != wday
)
1659 return wxAnyStrPtr();
1664 return wxAnyStrPtr(date
, input
);
1668 wxDateTime::ParseDateTime(const wxString
& date
, wxString::const_iterator
*end
)
1670 // Set to current day and hour, so strings like '14:00' becomes today at
1671 // 14, not some other random date
1672 wxDateTime dtDate
= wxDateTime::Today();
1673 wxDateTime dtTime
= wxDateTime::Today();
1675 wxString::const_iterator
1680 // If we got a date in the beginning, see if there is a time specified
1682 if ( dtDate
.ParseDate(date
, &endDate
) )
1684 // Skip spaces, as the ParseTime() function fails on spaces
1685 while ( endDate
!= date
.end() && wxIsspace(*endDate
) )
1688 const wxString
timestr(endDate
, date
.end());
1689 if ( !dtTime
.ParseTime(timestr
, &endTime
) )
1690 return wxAnyStrPtr();
1692 endBoth
= endDate
+ (endTime
- timestr
.begin());
1694 else // no date in the beginning
1696 // check if we have a time followed by a date
1697 if ( !dtTime
.ParseTime(date
, &endTime
) )
1698 return wxAnyStrPtr();
1700 while ( endTime
!= date
.end() && wxIsspace(*endTime
) )
1703 const wxString
datestr(endTime
, date
.end());
1704 if ( !dtDate
.ParseDate(datestr
, &endDate
) )
1705 return wxAnyStrPtr();
1707 endBoth
= endTime
+ (endDate
- datestr
.begin());
1710 Set(dtDate
.GetDay(), dtDate
.GetMonth(), dtDate
.GetYear(),
1711 dtTime
.GetHour(), dtTime
.GetMinute(), dtTime
.GetSecond(),
1712 dtTime
.GetMillisecond());
1714 // Return endpoint of scan
1718 return wxAnyStrPtr(date
, endBoth
);
1722 wxDateTime::ParseDate(const wxString
& date
, wxString::const_iterator
*end
)
1724 // this is a simplified version of ParseDateTime() which understands only
1725 // "today" (for wxDate compatibility) and digits only otherwise (and not
1726 // all esoteric constructions ParseDateTime() knows about)
1728 const wxString::const_iterator pBegin
= date
.begin();
1730 wxString::const_iterator p
= pBegin
;
1731 while ( wxIsspace(*p
) )
1734 // some special cases
1738 int dayDiffFromToday
;
1741 { wxTRANSLATE("today"), 0 },
1742 { wxTRANSLATE("yesterday"), -1 },
1743 { wxTRANSLATE("tomorrow"), 1 },
1746 for ( size_t n
= 0; n
< WXSIZEOF(literalDates
); n
++ )
1748 const wxString dateStr
= wxGetTranslation(literalDates
[n
].str
);
1749 size_t len
= dateStr
.length();
1751 const wxString::const_iterator pEnd
= p
+ len
;
1752 if ( wxString(p
, pEnd
).CmpNoCase(dateStr
) == 0 )
1754 // nothing can follow this, so stop here
1758 int dayDiffFromToday
= literalDates
[n
].dayDiffFromToday
;
1760 if ( dayDiffFromToday
)
1762 *this += wxDateSpan::Days(dayDiffFromToday
);
1768 return wxAnyStrPtr(date
, pEnd
);
1772 // We try to guess what we have here: for each new (numeric) token, we
1773 // determine if it can be a month, day or a year. Of course, there is an
1774 // ambiguity as some numbers may be days as well as months, so we also
1775 // have the ability to back track.
1778 bool haveDay
= false, // the months day?
1779 haveWDay
= false, // the day of week?
1780 haveMon
= false, // the month?
1781 haveYear
= false; // the year?
1783 // and the value of the items we have (init them to get rid of warnings)
1784 WeekDay wday
= Inv_WeekDay
;
1785 wxDateTime_t day
= 0;
1786 wxDateTime::Month mon
= Inv_Month
;
1789 // tokenize the string
1791 static const wxStringCharType
*dateDelimiters
= wxS(".,/-\t\r\n ");
1792 wxStringTokenizer
tok(wxString(p
, date
.end()), dateDelimiters
);
1793 while ( tok
.HasMoreTokens() )
1795 wxString token
= tok
.GetNextToken();
1801 if ( token
.ToULong(&val
) )
1803 // guess what this number is
1809 if ( !haveMon
&& val
> 0 && val
<= 12 )
1811 // assume it is month
1814 else // not the month
1818 // this can only be the year
1821 else // may be either day or year
1823 // use a leap year if we don't have the year yet to allow
1824 // dates like 2/29/1976 which would be rejected otherwise
1825 wxDateTime_t max_days
= (wxDateTime_t
)(
1827 ? GetNumberOfDays(mon
, haveYear
? year
: 1976)
1832 if ( (val
== 0) || (val
> (unsigned long)max_days
) )
1837 else // yes, suppose it's the day
1851 year
= (wxDateTime_t
)val
;
1860 day
= (wxDateTime_t
)val
;
1866 mon
= (Month
)(val
- 1);
1869 else // not a number
1871 // be careful not to overwrite the current mon value
1872 Month mon2
= GetMonthFromName
1875 Name_Full
| Name_Abbr
,
1876 DateLang_Local
| DateLang_English
1878 if ( mon2
!= Inv_Month
)
1883 // but we already have a month - maybe we guessed wrong?
1886 // no need to check in month range as always < 12, but
1887 // the days are counted from 1 unlike the months
1888 day
= (wxDateTime_t
)(mon
+ 1);
1893 // could possible be the year (doesn't the year come
1894 // before the month in the japanese format?) (FIXME)
1903 else // not a valid month name
1905 WeekDay wday2
= GetWeekDayFromName
1908 Name_Full
| Name_Abbr
,
1909 DateLang_Local
| DateLang_English
1911 if ( wday2
!= Inv_WeekDay
)
1923 else // not a valid weekday name
1926 static const char *ordinals
[] =
1928 wxTRANSLATE("first"),
1929 wxTRANSLATE("second"),
1930 wxTRANSLATE("third"),
1931 wxTRANSLATE("fourth"),
1932 wxTRANSLATE("fifth"),
1933 wxTRANSLATE("sixth"),
1934 wxTRANSLATE("seventh"),
1935 wxTRANSLATE("eighth"),
1936 wxTRANSLATE("ninth"),
1937 wxTRANSLATE("tenth"),
1938 wxTRANSLATE("eleventh"),
1939 wxTRANSLATE("twelfth"),
1940 wxTRANSLATE("thirteenth"),
1941 wxTRANSLATE("fourteenth"),
1942 wxTRANSLATE("fifteenth"),
1943 wxTRANSLATE("sixteenth"),
1944 wxTRANSLATE("seventeenth"),
1945 wxTRANSLATE("eighteenth"),
1946 wxTRANSLATE("nineteenth"),
1947 wxTRANSLATE("twentieth"),
1948 // that's enough - otherwise we'd have problems with
1949 // composite (or not) ordinals
1953 for ( n
= 0; n
< WXSIZEOF(ordinals
); n
++ )
1955 if ( token
.CmpNoCase(ordinals
[n
]) == 0 )
1961 if ( n
== WXSIZEOF(ordinals
) )
1963 // stop here - something unknown
1970 // don't try anything here (as in case of numeric day
1971 // above) - the symbolic day spec should always
1972 // precede the month/year
1978 day
= (wxDateTime_t
)(n
+ 1);
1983 nPosCur
= tok
.GetPosition();
1986 // either no more tokens or the scan was stopped by something we couldn't
1987 // parse - in any case, see if we can construct a date from what we have
1988 if ( !haveDay
&& !haveWDay
)
1989 return wxAnyStrPtr();
1991 if ( haveWDay
&& (haveMon
|| haveYear
|| haveDay
) &&
1992 !(haveDay
&& haveMon
&& haveYear
) )
1994 // without adjectives (which we don't support here) the week day only
1995 // makes sense completely separately or with the full date
1996 // specification (what would "Wed 1999" mean?)
1997 return wxAnyStrPtr();
2000 if ( !haveWDay
&& haveYear
&& !(haveDay
&& haveMon
) )
2002 // may be we have month and day instead of day and year?
2003 if ( haveDay
&& !haveMon
)
2007 // exchange day and month
2008 mon
= (wxDateTime::Month
)(day
- 1);
2010 // we're in the current year then
2011 if ( (year
> 0) && (year
<= (int)GetNumberOfDays(mon
, Inv_Year
)) )
2013 day
= (wxDateTime_t
)year
;
2018 //else: no, can't exchange, leave haveMon == false
2023 return wxAnyStrPtr();
2028 mon
= GetCurrentMonth();
2033 year
= GetCurrentYear();
2038 // normally we check the day above but the check is optimistic in case
2039 // we find the day before its month/year so we have to redo it now
2040 if ( day
> GetNumberOfDays(mon
, year
) )
2041 return wxAnyStrPtr();
2043 Set(day
, mon
, year
);
2047 // check that it is really the same
2048 if ( GetWeekDay() != wday
)
2049 return wxAnyStrPtr();
2056 SetToWeekDayInSameWeek(wday
);
2059 // return the pointer to the first unparsed char
2061 if ( nPosCur
&& wxStrchr(dateDelimiters
, *(p
- 1)) )
2063 // if we couldn't parse the token after the delimiter, put back the
2064 // delimiter as well
2071 return wxAnyStrPtr(date
, p
);
2075 wxDateTime::ParseTime(const wxString
& time
, wxString::const_iterator
*end
)
2077 // first try some extra things
2084 { wxTRANSLATE("noon"), 12 },
2085 { wxTRANSLATE("midnight"), 00 },
2089 for ( size_t n
= 0; n
< WXSIZEOF(stdTimes
); n
++ )
2091 const wxString timeString
= wxGetTranslation(stdTimes
[n
].name
);
2092 const wxString::const_iterator p
= time
.begin() + timeString
.length();
2093 if ( timeString
.CmpNoCase(wxString(time
.begin(), p
)) == 0 )
2095 // casts required by DigitalMars
2096 Set(stdTimes
[n
].hour
, wxDateTime_t(0), wxDateTime_t(0));
2101 return wxAnyStrPtr(time
, p
);
2105 // try all time formats we may think about in the order from longest to
2107 static const char *timeFormats
[] =
2109 "%I:%M:%S %p", // 12hour with AM/PM
2110 "%H:%M:%S", // could be the same or 24 hour one so try it too
2111 "%I:%M %p", // 12hour with AM/PM but without seconds
2112 "%H:%M:%S", // and a possibly 24 hour version without seconds
2113 "%X", // possibly something from above or maybe something
2114 // completely different -- try it last
2116 // TODO: parse timezones
2119 for ( size_t nFmt
= 0; nFmt
< WXSIZEOF(timeFormats
); nFmt
++ )
2121 const wxAnyStrPtr result
= ParseFormat(time
, timeFormats
[nFmt
], end
);
2126 return wxAnyStrPtr();
2129 // ----------------------------------------------------------------------------
2130 // Workdays and holidays support
2131 // ----------------------------------------------------------------------------
2133 bool wxDateTime::IsWorkDay(Country
WXUNUSED(country
)) const
2135 return !wxDateTimeHolidayAuthority::IsHoliday(*this);
2138 // ============================================================================
2140 // ============================================================================
2142 wxDateSpan WXDLLIMPEXP_BASE
operator*(int n
, const wxDateSpan
& ds
)
2145 return ds1
.Multiply(n
);
2148 // ============================================================================
2150 // ============================================================================
2152 wxTimeSpan WXDLLIMPEXP_BASE
operator*(int n
, const wxTimeSpan
& ts
)
2154 return wxTimeSpan(ts
).Multiply(n
);
2157 // this enum is only used in wxTimeSpan::Format() below but we can't declare
2158 // it locally to the method as it provokes an internal compiler error in egcs
2159 // 2.91.60 when building with -O2
2170 // not all strftime(3) format specifiers make sense here because, for example,
2171 // a time span doesn't have a year nor a timezone
2173 // Here are the ones which are supported (all of them are supported by strftime
2175 // %H hour in 24 hour format
2176 // %M minute (00 - 59)
2177 // %S second (00 - 59)
2180 // Also, for MFC CTimeSpan compatibility, we support
2181 // %D number of days
2183 // And, to be better than MFC :-), we also have
2184 // %E number of wEeks
2185 // %l milliseconds (000 - 999)
2186 wxString
wxTimeSpan::Format(const wxString
& format
) const
2188 // we deal with only positive time spans here and just add the sign in
2189 // front for the negative ones
2192 wxString
str(Negate().Format(format
));
2196 wxCHECK_MSG( !format
.empty(), wxEmptyString
,
2197 _T("NULL format in wxTimeSpan::Format") );
2200 str
.Alloc(format
.length());
2202 // Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
2204 // Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
2205 // question is what should ts.Format("%S") do? The code here returns "3273"
2206 // in this case (i.e. the total number of seconds, not just seconds % 60)
2207 // because, for me, this call means "give me entire time interval in
2208 // seconds" and not "give me the seconds part of the time interval"
2210 // If we agree that it should behave like this, it is clear that the
2211 // interpretation of each format specifier depends on the presence of the
2212 // other format specs in the string: if there was "%H" before "%M", we
2213 // should use GetMinutes() % 60, otherwise just GetMinutes() &c
2215 // we remember the most important unit found so far
2216 TimeSpanPart partBiggest
= Part_MSec
;
2218 for ( wxString::const_iterator pch
= format
.begin(); pch
!= format
.end(); ++pch
)
2222 if ( ch
== _T('%') )
2224 // the start of the format specification of the printf() below
2225 wxString
fmtPrefix(_T('%'));
2230 // the number of digits for the format string, 0 if unused
2231 unsigned digits
= 0;
2233 ch
= *++pch
; // get the format spec char
2237 wxFAIL_MSG( _T("invalid format character") );
2243 // skip the part below switch
2248 if ( partBiggest
< Part_Day
)
2254 partBiggest
= Part_Day
;
2259 partBiggest
= Part_Week
;
2265 if ( partBiggest
< Part_Hour
)
2271 partBiggest
= Part_Hour
;
2278 n
= GetMilliseconds().ToLong();
2279 if ( partBiggest
< Part_MSec
)
2283 //else: no need to reset partBiggest to Part_MSec, it is
2284 // the least significant one anyhow
2291 if ( partBiggest
< Part_Min
)
2297 partBiggest
= Part_Min
;
2304 n
= GetSeconds().ToLong();
2305 if ( partBiggest
< Part_Sec
)
2311 partBiggest
= Part_Sec
;
2320 fmtPrefix
<< _T("0") << digits
;
2323 str
+= wxString::Format(fmtPrefix
+ _T("ld"), n
);
2327 // normal character, just copy
2335 #endif // wxUSE_DATETIME