Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qttemporalpattern.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4#include "private/qttemporalpattern_p.h"
5
6#include "private/qlocale_p.h"
7#include "private/qtparseqttemporalformat_p.h"
8#if QT_CONFIG(datetimeparser)
9# include "private/qtparsetemporal_p.h"
10#endif
11
12#include <bitset>
13
14QT_BEGIN_NAMESPACE
15
17/*!
18 \internal
19 \since 6.12
20 \namespace QtTemporalPattern
21 \brief Supporting types and functions for temporal patterns.
22
23 Temporal patterns describe how a date, time or datetime may be serialized as
24 text or parsed from text. This namespace provides the common tools used by
25 the classes describing such patterns: \l QDateTimePattern, \l QTimePattern
26 and \l QDatePattern.
27*/
28
29/*
30 Future Directions
31
32 QTBUG-70516, QTBUG-81056: For now (Qt 6.12) it suffices to cover everything
33 that the existing Qt datetime format strings are capable of. However, the
34 intent is to eventually expand this to fully support CLDR's datetime formats
35 so that we can switch from converting those to Qt formats when we scan CLDR
36 to actually storing the CLDR format in the qlocale_data_p.h tables and
37 constructing our Q(Date|Time)+Pattern objects from those formats. See
38 comment in header for a link to the relevant parts of LDML.
39
40 QTBUG-114172: RFC 9557 defines some optional suffixes for time zones of
41 datetimes. We shall need to add support for accepting those and for some
42 mechanism for reporting what they said in the return from parsing. Some may
43 be expressible just by setting the zone of the returned datetime but others,
44 such as indications of what calendar should be used when displaying the data
45 to a user, shall need some other mechanism.
46
47 QTBUG-114525: The ECMAScript standard now includes Temporal, a replacement
48 for Date (which is too badly designed to fix). The QML V4 engine shall need
49 support for whatever formats Temporal defines.
50*/
51
52/*!
53 \enum QtTemporalPattern::TemporalFieldCategory
54
55 This enumeration characterizes the information supplied by a field.
56
57 For the details of how that information is conveyed, see \l
58 {QtTemporalPattern::}{TemporalFieldFlag}. For the classification of fields
59 by whether they specify date, time or zone, see \l
60 {QtTemporalPattern::}{DateTimePart}.
61
62 \value Literal Describes a text fragment that frames the data, such as
63 separators and delimiters.
64 \value TimeZone Identifies the timezone or offset from UTC of a datetime.
65 \value SecondFraction The fraction of a second (an optional time field).
66 \value Second The second within the minute (an optional time field).
67 \value Minute The minute within the hour (a time field).
68 \value PeriodInDay A subdivision of the day, such as before noon vs after
69 noon (a time field). May serve to disambiguate the hour
70 when specified only modulo 12. (Currently only the am/pm
71 distinction is supported.)
72 \value HourMod12 The hour in the range 1 through 12 (a time field). May be
73 ambiguous on its own.
74 \value Hour The hour in the range from 0 through 23 (a time field).
75
76 \value DayOfWeek The day within the week (a date field). Usually specified
77 by name. Some locales may use numbers for their Narrow
78 Verbal and/or Standalone forms. No form is supported for
79 Numeric | DayOfWeek.
80 \value DayOfMonth The day number within the month (a date field). Runs from
81 1 for the first day of the month up to the length of the
82 month. Always numeric, regardless of field flags.
83
84 \value Month The month within the year (a date field). When specified
85 numerically, the first month of the year is numbered 1; there
86 is no month 0. Some locales may use numbers for their Narrow
87 Verbal form.
88
89 \value YearWithinCentury The two-digit year number (a date field). Widely
90 used in date formats, despite its potential for
91 ambiguity. May be disambiguated by other fields or
92 by specifying base year for the hundred years
93 presumed when only two digits are given and other
94 fields don't disambiguate.
95 \value Year The full year number (a date field).
96
97 Fields identified as numbers, along with hour, minute, second and fraction
98 of second, are always given in numeric form (regardless of Numeric, Verbal
99 or Standalone flags). Where a field is given in numeric form, its field
100 width is the smallest number of digits that can match it. Further digits are
101 accepted, up to the greatest number of significant digits that can appear in
102 a valid value for it. (If the field width exceeds this, fields of this width
103 are accepted, provided the numeric value is valid. This may require
104 zero-padding.)
105
106 The SecondFraction field describes the digits immediately following the
107 fractional-part separator in a decimal representation of the seconds with
108 fractional part. It is up to the format to position it suitably in relation
109 to a Second field and a Literal field for the separator. Leading zeros are
110 significant and not considered to be padding: trailing zeros are understood
111 as padding.
112
113 As QTime and QDateTime only handle times to millisecond precision, normally
114 their allowed range of values runs from 0 to 999 and no more than three
115 digits are accepted, or the field width if greater. If the \l
116 {QtTemporalPattern::TemporalFieldFlag} {RoundFraction} flag is passed,
117 digits beyond this are accepted and will affect the result only via
118 appropriate rounding. (If fewer than three digits are parsed, the value is
119 implicitly extended on the right with zeros to obtain milliseconds
120 precision. Whether such a field is accepted will depend on the setting of
121 the \c width of the field and the absence of \l
122 {QtTemporalPattern::TemporalFieldFlag} {ZeroPad} from its \l
123 {QtTemporalPattern::TemporalField} {\c options}, in the usual ways.)
124
125 Where a SecondFraction field accepts more than three digits (either because
126 its field width exceeds three or because the RoundFraction flag is
127 specified), the resulting fractional part is rounded to three significant
128 digits. If rounding would require increasing the Second field, however, the
129 Second field is retained unchanged and the fractional part is rounded to 999
130 milliseconds. For example, 29.9997 seconds is rounded to 29.999 seconds, to
131 preserve the fact that the time is strictly before the 30 second mark.
132
133 \note For negative years, the YearWithinCentury will be understood as the
134 number of completed years since the start of the most recent year that is a
135 multiple of 100. Thus year -1 (which Qt understands, when using the
136 Gregorian calendar, to mean 1 BCE) has a YearWithinCentury value of 99,
137 since the last year that's a multiple of 100 is -100 (for Gregorian, 100
138 BCE).
139
140 \omitvalue EndCategories
141
142 \sa {QtTemporalPattern::}{TemporalFieldFlag}, {QtTemporalPattern::}{DateTimePart}
143*/
144
145/* For numbers as narrow days of the week, at least three different numberings
146 are used, all of which are used in locales whose "first day of the week" is
147 Monday. (Furthermore, some locales with digits as narrow names only do that
148 for some days, with letters for others.) So there is no way to determine how
149 days of the week are numbered from one locale to the next, except in so far
150 as their narrow Verbal or Standalone forms use digits. A Numeric version of
151 the day of the week field would thus either not know what to do for most
152 locales, be inconsistent between locales or be inconsistent, for some
153 locales, between Narrow Verbal / Standalone formats and Numeric format.
154 Hence the lack of a meaning of Numeric for DayOfWeek.
155
156 Some locales use month numbers for the narrow format of months; but none are
157 known to do so inconsistently with the usual month numbering (although Pashto
158 does this only partially, using non-numeric narrow standalone forms for the
159 first two months). This does still conflict with the numeric form of months,
160 at least in some cases, that use ASCII digits for narrow forms of month
161 numbers but locale-appropriate digits for their numeric forms. However, the
162 conflict is only in how the numbers are represented, not in the numeric
163 values used for months.
164*/
165
166/*!
167 \internal
168 \namespace QtTemporalPattern::FieldGroup
169 \brief Masks identifying mutually-exclusive families of options.
170
171 Each constant in this namespace is of type \l {QtTemporalPattern::}
172 {TemporalFieldFlags} and combines a mutually-exclusive family of \l
173 {QtTemporalPattern::} {TemporalFieldFlag} values into a mask by which to
174 identify that family. Within each such family, if none of the flags is
175 specified, any of them may be applied but if any of them are specified then
176 only one of those specified may be applied.
177
178 \value FormMask The three general forms of a field: numeric, verbal and
179 standalone.
180 \value WidthMask The four field widths: wide, short, abbreviated, and
181 narrow.
182 \value UtcPrefixMask The two options for prefixes on offset forms of
183 timezones, with and without a UTC prefix.
184 \value PaddingMask The two padding options for when fields don't fill the
185 width allotted to them: spaces and zeros.
186 \value SeasonMask The three perspectives from which to describe a timezone:
187 the generic, regardless of the time of year, the standard,
188 and how it's described when exercising daylight-saving
189 time (if it does at all).
190*/
191/* Namespace QtParseCommon has helper functions, defined in qtparsetimezone_p.h,
192 to apply the above rule related to these masks.
193*/
194
195/*!
196 \enum QtTemporalPattern::TemporalFieldFlag
197
198 This enumeration describes how datetime fields are expressed in text.
199
200 A combination of these flags is used to qualify a \l {QtTemporalPattern::}
201 {TemporalFieldCategory}, indicating whether it is conveyed by words or
202 numbers, how tersely or in which terms, depending on the field
203 category. Interpretation of a flag in this enumeration varies with the field
204 category it is qualifying and with other flags combined with it.
205
206 Some flags, such as the four width options, are mutually exclusive. For each
207 group of mutually-exclusive flags, a mask constant is defined in namespace
208 QtTemporalPattern::FieldGroup, of type \l {QtTemporalPattern::}
209 {TemporalFieldFlags}, that combines the members of that group. If no member
210 of such a group is set in a flags variable, it is treated as if all members
211 of that group were set. When serializing, the behavior when two or more
212 conflicting flags, in a group relevant to the field, are combined is
213 unspecified. It may depend on other fields or variables passed to the
214 serialization function. When parsing, such conflicting flags allow the
215 parser to match any of the conflicting options specified. If this leads to
216 ambiguity, parsing prefers the option that consumes more of the text to
217 parse.
218
219 Unless otherwise indicated, fields are localized. For example, ZeroPad pads
220 with, and Numeric uses, locale-appropriate digits when localized, and the
221 names of months, days of the week and timezones are translated into the
222 appropriate language (if possible).
223
224 The primary distinction in how fields are expressed is the form of the
225 field. These first three options are mutually incompatible and are grouped
226 together as the \l {QtTemporalPattern::FieldGroup::} {FormMask} constant:
227
228 \value Numeric Express the field numerically as a series of digits.
229 \value Verbal Name the field value in its usual in-format grammatical form.
230 \value Standalone Name the field value in its stand-alone grammatical form.
231
232 Next comes the width of the field. The meanings of these fields depends on
233 other flags and the field category, where relevant. Some field categories
234 may ignore these entirely, others may draw fewer distinctions and use the
235 same meaning for some widths. These four options are mutually exclusive and
236 grouped together as the \l {QtTemporalPattern::FieldGroup::} {WidthMask}
237 constant:
238
239 \value Narrow Use a the narrowest supported form for the field. In some
240 locales, the Narrow Verbal forms of some fields may use
241 numbers, potentially conflicting with one of its Numeric
242 forms.
243 \value Abbreviated Use an abbreviated form of the field.
244 \value Short Use a short form of the field.
245 \value Wide Use a wide form of the field.
246
247 \section2 Padding
248
249 Where a \c width is specified for a field but the field's value is naturally
250 shorter, it is necessary to indicate how to pad it to the desired width.
251 These two options are mutually exclusive and grouped together as the \l
252 {QtTemporalPattern::FieldGroup::} {PaddingMask} constant:
253
254 \value ZeroPad Only for numeric fields: pad to \c width with zeros. When
255 parsing, accept zeros that don't affect value, reject fields
256 that are narrower than their specified \c width.
257 \value SpacePad For a field with a positive \c width, pad to that \c width
258 with spaces. When parsing, allow leading and trailing
259 spacing characters.
260
261 If neither form of padding is indicated, the natural representation of a
262 value is used even if it fails to reach the \c width specified and parsing
263 will accept a narrower field (although it will prefer a match with full
264 width). In a \l {QtTemporalPattern::TemporalFieldCategory} {TimeZone} field
265 (see below) using an offset form, SpacePad is ignored and ZeroPad or its
266 absence only has its usual meaning for hour fields, while controlling the
267 presence of zero minute and second offsets following the hour field.
268
269 \section2 Space
270
271 Where a text to be matched (for example, a literal or the name of a month or
272 day of the week) contains spaces, by default plain space (ASCII SPACE,
273 U+0020) and the various Unicode spacing characters outside the ASCII range
274 (of various widths, some of them non-breaking) are all accepted as matches
275 for one another, while the number and placement of such short horizontal
276 spaces must match. Other spacing characters (newline, tab, etc.) must match
277 exactly. Since users commonly do not distinguish the short horizontal
278 spaces, this default usually suffices. In some cases, there may be reason to
279 insist on exact matching of spaces, without treating short horizontal spaces
280 as equivalent. Where the text to be parsed is taken from a larger text,
281 however, it's also possible that this larger text has been flowed, as a
282 paragraph, which may have turned some spaces into line breaks, possibly with
283 added indentation, or the text may be split across a page boundary. Coping
284 with such cases is supported by the options
285
286 \value FlexSpace Where a field to be matched contains spacing characters, or
287 a run of them, any spacing character or run of them will be
288 accepted as matching. A character is deemed to be a spacing
289 character if \l QChar::isSpace() is true for it.
290 \value StrictSpace Spacing characters must be matched exactly.
291 Ignored if FlexSpace is also set.
292
293 \section2 Letter case
294
295 The following options are only relevant to Verbal and Standalone
296 fields. They are not treated as a group or descrbed by a mask, as the locale
297 provides relevant fields with the appropriate (possibly mixed) case for the
298 lcoale. By default, the locale's form is used when serializing and matched
299 (case-sensitively) when parsing. The first two of these are mutually
300 exclusive. They change that default, forcing the case when serializing and
301 requiring the specified case (or one of the specified cases) when
302 parsing. The third has no effect when serializing and overrides the other
303 two, if either is present, when parsing.
304
305 \value LowerCase When serializing, force lower-case.
306 \value UpperCase When serializing, force upper-case.
307 \value IgnoreCase When parsing, match the field case-insensitively.
308
309 \section2 Extended fields
310
311 The following options modify the handling of specific fields where there is
312 no intrinsic limit to the number of significant digits in a valid value.
313 They are described in more detail below.
314
315 \value RoundFraction Allows excess precision in a fractional part.
316 \value YearSignIso8601 Requires a sign if there are extra digits in a year.
317
318 By default a \l {QtTemporalPattern::TemporalFieldCategory} {SecondFraction}
319 field only accepts up to three digits or as many digits as its field width
320 specifies. The RoundFraction modifies the field to allow more digits than
321 this, using the excess precision only to resolve rounding to the appropriate
322 precision, as described above for the SecondFraction field.
323
324 Modern revisions of ISO 8601 permit years outside the range from 0 through
325 9999 but require that they have a sign. By default a + sign on a positive
326 year is allowed and silently ignored (without counting towards its \c
327 width), but the YearSignIso8601 applies a modified version of the ISO rule:
328 the year field will only match a text with more digits than its specified \c
329 width if that text starts with a sign. When the field's \c width is 4, this
330 implements the ISO rule, but it can be applied to other widths, if needed.
331
332 In contrast to ISO's use of year 0000 to indicate 1 BCE, with negative year
333 values representing successively earlier years, where the calendar in use
334 has no year zero, Qt describes the year before year 1 as year -1, skipping
335 over 0 and treating 0 as an invalid value for the year. In particular, this
336 applies to the Gregorian calendar, which is used by default: 1 CE is
337 represented as year 1, with 1 BC as year -1. If the calendar in use reports
338 \c true from \l {QCalendar::} {hasYearZero()}, Qt duly accepts a year 0
339 between years -1 and +1. ISO also specifies that years before 1583 (the
340 first full year after the Gregorian calendar came into play) or after 9999
341 should not be used except by prior agreement between the producer and
342 consumer of the serialized date or datetime. Qt leaves such agreement as a
343 matter between the user and those they communicate with, simply accepting
344 any year number within the range of QDate or QDateTime, as appropriate.
345
346 \section2 Timezone representation
347
348 The following options are only relevant to timezones. If used with other
349 categories of field, they are ignored. By default, when the other fields of
350 a timestamp determine a datetime, the zone's localized name in effect at
351 that datetime is used when serializing and matched when parsing.
352
353 There are both localized and international standard formats available. The
354 following pair of options select which of those to use. They are grouped
355 together as the \l {QtTemporalPattern::FieldGroup::} {LocalizationMask}
356 constant:
357
358 \value LocalizedZone For a TimeZone, use localized forms.
359 \value Iso8601 For a TimeZone, use an ISO 8601 offset format.
360
361 When both are specified, or neither is, localized forms are preferred. See
362 \l {Locale-independent offset forms}, below, for details of the ISO
363 8601-based formats. See \c{Standalone | Short} below for the IANA DB and
364 \l{Local time} for a system-dependent form, both of which ignore the choice
365 between LocalizedZone and Iso8601.
366
367 The following three options, selecting seasonal variations, are mutually
368 exclusive and only relevant to Verbal or Standalone forms. They are
369 independent of the choice between LocalizedZone and Iso8601. They are
370 grouped together as the \l {QtTemporalPattern::FieldGroup::} {SeasonMask}
371 constant:
372
373 \value GenericTime For a non-Numeric TimeZone, use its generic name.
374 \value StandardTime For a non-Numeric TimeZone, use its standard-time name.
375 \value DaylightSavingTime For a non-Numeric TimeZone, use its
376 daylight-saving name.
377
378 For localized timezones, Numeric selects a basic offset format or an offset
379 format with a base prefix (typically a localized form of UTC or GMT), Verbal
380 selects a form of the zone's name, and Standalone selects the IANA ID or a
381 localized name based on a city that serves as exemplar for the zone (for the
382 given locale). The effects of the width options above then depend on which
383 of these is used. When LocalizedZone is set, the following forms are
384 available:
385
386 \list
387 \li For Numeric, the timezone offset is used:
388 \list
389 \li Wide uses the hour, minute and second, as for Short, but when
390 parsing it will accept a fractional part of the seconds (following
391 the locale-appropriate separator, after the whole number part of
392 the seconds), if present. As Qt only supports whole numbers of
393 seconds as offsets, this fractional part's only effect is to round
394 up the second part if it is at least a half second. (See note on
395 rounding in the next section.)
396 \li Short uses the hour, minute and second, rounding to the nearest
397 second if the offset is not a whole number of seconds.
398 \li Abbreviated uses the hour and minute, rounding to the nearest
399 minute if the offset is not a whole number of minutes.
400 \li Narrow uses the hour, rounding to nearest if the actual offset is
401 not a whole number of hours.
402 \endlist
403 \li For Verbal, the zone name is used:
404 \list
405 \li Wide uses the full name of the zone, e.g. "Pacific Time", "Pacific
406 Standard Time" or "Pacific Daylight Time", depending on season.
407 \li Short is treated as Wide.
408 \li Abbreviated uses the zone abbreviation, e.g. "PT", "PST" or "PDT".
409 Note that these cannot be reliably parsed.
410 \li Narrow is treated as Abbreviated.
411 \endlist
412 \li For Standalone, the city name:
413 \list
414 \li Wide uses the locale's generic location format, such as "Los
415 Angeles Time".
416 \li Short uses the full IANA ID, such as America/Los_Angeles.
417 This is not localized (the LocalizedZone flag is ignored).
418 \li Abbreviated just gives the localized exemplar city, e.g. "Los
419 Angeles".
420 \li Narrow is treated as Abbreviated.
421 \endlist
422 \endlist
423
424 Where a timezone is specified simply in terms of an offset from UTC, it does
425 not necessarily have an associated city or a name other than its offset
426 representations. For such zones, when serializing, Verbal and Standalone are
427 treated as Numeric, with the exception of \c{Staldalone | Short}, as the
428 IANA ID is not localized and this form, like an IANA ID, is accepted by the
429 QTimeZone(QByteArray) constructor. (Note that these do not include ZeroPad:
430 see the next section for its effect on offset forms.) When parsing,
431 therefore, these offset formats are accepted for the Verbal and Standalone
432 forms that would map to them for offset zones. This applies to \l
433 {QTimeZone::fromDurationAheadOfUtc()} lightweight time representations (for
434 which \l {QTimeZone::}{isUtcOrFixedOffset()} is true) as well as to those,
435 with a UTC-offset backend, constructed by QTimeZone(int) or, with an ID of
436 form \c{"UTC"} or \c{"UTC±HH:mm"}, by QTimeZone(QByteArray),
437
438 \section3 Offset modifiers
439
440 In the various timezone offset formats (both above and below), there are
441 potentially hour, minute and second parts of the offset, depending on the
442 width option selected. The minute and second parts, when present, always use
443 two digits, rendering the usual meaning of ZeroPad redundant. Instead, for
444 these parts, ZeroPad controls whether trailing zero parts are included.
445 When ZeroPad is set they are included when serializing and required to be
446 present when parsing. When ZeroPad is not set, they are omitted when
447 serializing and, if trailng parts are missing when parsing, they are taken
448 to have value zero. Zero parts are always accepted when parsing, even when
449 ZeroPad is not set.
450
451 The hour part of an offset is never omitted when serializing and is always
452 required when parsing. When ZeroPad is not set, when parsing offset formats
453 with separators between parts, a single-digit hour is accepted. (For the
454 localized offset formats above, whether there are separators between parts
455 depends on the locale.) When ZeroPad is not set, serialization only produces
456 a single-digit hour if there are no later parts (typically because they were
457 all zero, hence omitted). Otherwise, the hour part is always serialized with
458 two digits and parsing requires it to have two digits.
459
460 As ever, if more than one width is specified, any given is allowed. On
461 serializing, narrower formats are preferred unless they lose precision in
462 the offset that an allowed longer format would include. Thus \c{Narrow |
463 Short} would include only the hours for a whole-hour offset, but would
464 include hours, minutes and seconds for an hour-and-a-half offset (albeit
465 omitting the zero seconds unless ZeroPad is set). Where the width thus
466 selected requires rounding due to omitting a part of the offset that isn't
467 zero, exact halves round away from zero. On parsing, the longest allowed
468 form for which a match is found will be used.
469
470 Offset formats may also include a prefix (localized in the forms above) that
471 identifies the offset as being relative to UTC or GMT. The following pair of
472 mutually exclusive options control whether that is omitted or included.
473 They are grouped together as the \l {QtTemporalPattern::FieldGroup::}
474 {UtcPrefixMask} constant:
475
476 \value AcceptUtcPrefix Include a UTC prefix on offsets when serializing and
477 require it when parsing.
478 \value NeedNoUtcPrefix Leave off the UTC prefix when serializing and reject
479 it when parsing.
480
481 If neither or both of these are specified, serializing omits the prefix and
482 parsing permits it but does not require it.
483
484 \section3 Locale-independent offset forms
485
486 In addition to these localized forms, a timestamp may also represent its
487 zone in a locale-independent offset form. In effect, this use the C locale,
488 with ASCII digits 0 through 9, the ASCII + and - as signs, and the ASCII
489 colon as separator (where relevant). These are selected by the \c Iso8601
490 flag.
491
492 \value AllowZSuffix Modifies Iso8601 to allow use of a \c{Z} suffix to
493 denote a zero UTC offset. See RFC 9557 note below.
494
495 If AllowZSuffix is set and ZeroPad is not, serialization will use \c{Z} to
496 represent a zero offset. When ZeroPad is set, serialization ignores
497 AllowZSuffix. If AllowZSufix is set, regardless of ZeroPad, parsing will
498 accept a \c{Z} suffix as meaning zero offset.
499
500 The Iso8601 format is modified by other flags as follows (when not using
501 \c{Z} to represent a zero offset):
502 \list
503 \li With Numeric it uses a basic format (with no separators), with Verbal
504 or Standalone it uses separators between hours, minutes and seconds,
505 in so far as these appear.
506 \li The width options Wide, Short, Abbreviated and Narrow have the same
507 meanings as for Numeric localized offset formats, modified by the
508 ZeroPad option, as described above.
509 \endlist
510
511 \note In some contexts, notably where \l
512 {https://www.rfc-editor.org/rfc/rfc9557.html} {RFC 9557} is used, a zone
513 indicator on a timestamp may be understood as giving context to the
514 information in which it appears, as opposed to only indicating the zone with
515 respect to which the timestamp itself is expressed. In such contexts, a
516 \c{Z} suffix, applied by \c AllowZSuffix, only indicates that the timestamp
517 itself is given with respect to UTC and does not give any context to the
518 information in which it appears. For contrast, in such contexts, a +00:00
519 suffix does indicate not only that the timestamp is given in UTC but also
520 that UTC is the relevant zone for the context of the information. Prior to
521 RFC 9557, some RFCs (incompatibly with ISO 8601) proposed using -00:00 to
522 indicate what RFC 9557 has specified as the meaning for a \c{Z}
523 suffix. Nothing in Qt attends to this distinction.
524
525 \section3 Local time
526
527 Where Qt can determine how the local system describes its local time, Qt has
528 no control over the form in which the system supplies it, nor does Qt know
529 whether, or how, it is localized, with the result that this representation
530 is system-dependent. As another system may be using a different local time,
531 or representing it differently, there is no guarantee that what one system
532 supplies for local time can be successfully understood on another system. To
533 opt in to using this system-dependent representation of local time, supply
534 the following option. Even then, when serializing, if the options given
535 permit any other available representation of the timezone, that is preferred
536 over this.
537
538 \value LocalTimeName Allow the system-supplied local time name to describe
539 the system's local time.
540
541 The system local time may come in separate forms for standard time and
542 daylight-saving time. When it does, the options above for selecting between
543 these affect LocalTimeName as usual, with GenericTime ignored.
544
545 \sa {QtTemporalPattern::}{TemporalFieldCategory}, {QtTemporalPattern::}{TemporalFieldFlags}
546*/
547// RFC 9557: see QTBUG-114172
548
549// TemporalFieldFlags and DateTimeParts: docs taken care of automagically by
550// QDoc, recognizing QFLAG() usage.
551
552/*!
553 \fn constexpr bool QtTemporalPattern::matchesFlagWithin(QtTemporalPattern::TemporalFieldFlags flags, QtTemporalPattern::TemporalFieldFlag sought, QtTemporalPattern::TemporalFieldFlags group)
554
555 Tests \a flags for a \a sought flag within a \a group.
556
557 Implements the per-flag check for a single TemporalFieldFlag with respect to
558 its FieldGroup entry. If no flag in a group is given in \a flags, then all
559 flags in the group are allowed; otherwise, only the given flags in the group
560 match.
561*/
562
563/*!
564 \fn constexpr bool QtTemporalPattern::matchesFlagsWithin(QtTemporalPattern::TemporalFieldFlags flags, QtTemporalPattern::TemporalFieldFlags sought, QtTemporalPattern::TemporalFieldFlags group)
565
566 Similar to \l matchesFlagWithin(), but if any of those \a sought is found in
567 \a flags, or if none of group are, it's counted as a match.
568
569 In some contexts, some flags are treated as equivalent, so to check for what
570 they represent pass the equivalent flags |-joined as \a sought.
571*/
572
573
574/*!
575 \enum QtTemporalPattern::DateTimePart
576 \brief This enumeraction classifies the various field categories.
577
578 The classification addresses which parts of a datetime a field contributes
579 data to.
580
581 \value None A literal field contributes no data.
582 \value Date Various fields contribute to the date.
583 \value Time Various fields contribute to the time.
584 \value Zone Only the \l {QtTemporalPattern::TemporalFieldFlag::}{TimeZone}
585 field contributes information about the timezone.
586
587 These may be combined in a \l {QtTemporalPattern::}{DateTimeParts} to
588 express a set of parts that a set of fields might suffice to describe,
589 whether fully or only in part.
590
591 \sa {QtTemporalPattern::}{TemporalFieldCategory}, {QtTemporalPattern::}{supports()}
592*/
593
594/*!
595 \fn QtTemporalPattern::classify(QtTemporalPattern::TemporalFieldCategory category) noexcept
596 \brief Classify a field category according to the part of a datetime it contributes to.
597
598 This maps a \l {QtTemporalPattern::}{TemporalFieldCategory} to the \l
599 {QtTemporalPattern::}{DateTimePart} for which it supplies data.
600*/
601
602/*!
603 \class QtTemporalPattern::TemporalField
604 \brief Describes one field in a temporal pattern.
605
606 A single field is characterized by its \l
607 {QtTemporalPattern::TemporalFieldCategory}{category}, some \l
608 {QtTemporalPattern::TemporalFieldFlags}{options} identifying how the field
609 is to be expressed and, where relevant, a datum. For a Literal field, the
610 datum is the string to be matched.
611
612 For numeric fields, a width may optionally be specified, indicating
613 the expected number of digits in the field. If options specifies
614 zero-padding, this is a minimum number of digits; otherwise, shorter fields
615 are accepted. In any case, longer values are accepted, where the resulting
616 numeric value is valid for the field. A zero width does not mean an empty
617 field will be accepted: it is effectively equivalent to a width of 1.
618
619 \note in some locales, the digits may require surrogate pairs to encode, so
620 the UTF-16 length of the field may exceed the number of digits. In a year
621 field with a sign, the sign does not count towards the width of the
622 field. The width only counts digits. The width is, in any case, a lower
623 bound: more digits may be read, if present and not consumed by some later
624 field. The \c endIndex of any parse result is the only reliable source of
625 truth on the UTF-16 end of the text parsed.
626*/
627// TODO: should we support digit grouping in year numbers, at least with > 4 digits ?
628
629/*!
630 \fn QtTemporalPattern::hasFieldsFor(QSpan<const QtTemporalPattern::TemporalField> range)
631 \brief Identify the parts to which the given fields contribute data.
632
633 Takes a \a range of TemporalField instances and returns a \l
634 {QtTemporalPattern::}{DateTimeParts} indicating which parts \l classify()
635 says any of the fields contribute to. Note that this only tessts for
636 contribution to a part, not for full coverage of the part. See \l supports()
637 for that.
638
639 \sa classify(), supports()
640*/
641
642/*!
643 \enum QtTemporalPattern::SupportType
644 \brief This enumeration identifies how well some fields describe requested datetime parts.
645
646 The fields of a pattern may contain partial or complete data on each of the
647 \l {QtTemporalPattern::TemporalFieldPart}{parts of} a datetime. When parsing
648 or serializing only a date or only a time, fields for the other or for
649 timezone are extraneous, making the pattern unable to serialize just the
650 intended type, as it lacks the data for those fields. It would also, when
651 parsing, be obliged discard some of the data it parses, as the type it
652 returns cannot express it.
653
654 When serializing a datetime, if the fields present do not suffice to fully
655 encode the date or time, it will not be possible for a reader of the
656 resulting text to unambiguously determine the datetime. If timezone is not
657 specified, it is possible to convert the datetime to some specific choice of
658 zone: provided both ends of the communication use the same zone, it is then
659 possible to recover the exact point in time, albeit without knowing the
660 timezone originally used to encode it.
661
662 Where data is partially supplied, it is possible that the partial data
663 suffices to meet the readers needs, although this typically involves the
664 reader in making some default assumptions about the missing fields. For
665 example, a two-digit year may need some assumptions about the century
666 (possibly aided by information about the date and day of the week) to
667 determine what year to presume the sender intended.
668
669 \value None No fields were found.
670 \value HasStrays Some field not relevant to the requested parts was present.
671 \value Partial Either some requested part is present and some other is
672 missing or some fields for a requested part are present but
673 not enough to fully describe that part.
674 \value Clear Enough fields of the requested parts were found to fully
675 determine them and no fields of unwanted parts were present.
676
677 Where partial fields for the requested parts were found along with fields
678 for unwanted parts, HasStrays is used in preference to Partial, as it is
679 considered a more significant defect.
680
681 \sa {QtTemporalPattern::}{TemporalFieldPart}, {QtTemporalPattern::}{supports()}
682*/
683
684/*!
685 \fn QtTemporalPattern::supports(QtTemporalPattern::DateTimeParts wanted, QSpan<QtTemporalPattern::TemporalField> range, bool hasBaseYear) noexcept
686 \brief Assess how well the given fields support the \a wanted parts.
687
688 If any field in \a range belongs to a part not included in \a wanted,
689 returns \l {SupportType::}{HasStrays}. Otherwise,
690
691 \list
692 \li If no fields are present, aside from \l
693 {TemporalFieldCategory::}{Literal} ones, returns \l
694 {SupportType::}{None}.
695 \li If the fields present completely specify all parts in \a wanted,
696 returns \l {SupportType::}{Clear}.
697 \li If some fields are specified but some \a wanted part is inadequately
698 specified, or entirely unspecified, returns \l
699 {SupportType::}{Partial}.
700 \endlist
701
702 For these purposes,
703
704 \list
705 \li The \l {DateTimePart::}{Zone} part is specified by the \l
706 {TemporalFieldCategory::}{TimeZone}.
707 \li The \l {DateTimePart::}{Time} part is specified by any combination of
708 fields that identify the hour and minute. If the \l
709 {TemporalFieldCategory::}{SecondFractions} field is present, the part is
710 considered incompletely specified unless the \l
711 {TemporalFieldCategory::}{Seconds} field is also present.
712 \li The \l {DateTimePart::}{Date} part is specified by any combination of
713 fields that identify a date. This usually means \l
714 {TemporalFieldCategory::}{Year}, \l {TemporalFieldCategory::}{Month}
715 and \l {TemporalFieldCategory::}{DayOfMonth} although Year may be
716 indirectly specified by \l
717 {TemporalFieldCategory::}{YearWithinCentury} if the presence of \l
718 {TemporalFieldCategory::}{DayOfWeek} enables disambiguation among
719 centuries close to the present, given the other date fields.
720 \endlist
721*/
722
723template <typename Enum, size_t Size>
725{
726 std::bitset<Size> bits;
727 static size_t map(Enum cat) { return qToUnderlying(cat); }
728public:
729 void set(Enum cat) { bits[map(cat)] = true; }
730 bool test(Enum cat) const { return bits[map(cat)]; }
731};
732
733SupportType supports(DateTimeParts wanted, QSpan<const TemporalField> range,
734 bool hasBaseYear) noexcept
735{
736 // TODO: may need to take into account calendar (and perhaps locale).
737 SupportType support = SupportType::HasStrays;
738 SupportType zone = SupportType::None;
739 EnumIndexedBitSet<TemporalFieldCategory, EndTemporalFieldCategories> categories;
740 for (const TemporalField &field : range) {
741 const DateTimePart part = field.part();
742 switch (part) {
743 case DateTimePart::None: // Literal contributes no data.
744 continue;
745 case DateTimePart::Date:
746 case DateTimePart::Time:
747 categories.set(field.category);
748 break;
749 case DateTimePart::Zone:
750 if (field.options.testAnyFlags(TemporalFieldFlag::Wide | TemporalFieldFlag::Short)
751 || field.options.testAnyFlags(TemporalFieldFlag::Numeric
752 | TemporalFieldFlag::Standalone
753 | TemporalFieldFlag::Iso8601)) {
754 zone = SupportType::Clear;
755 } else if (zone == SupportType::None) {
756 // Zone name abbreviation: does not uniquely identify zone.
757 zone = SupportType::Partial;
758 }
759 break;
760 }
761 if (!wanted.testFlag(part))
762 return support;
763 }
764
765 bool partsSeen = wanted.testFlag(DateTimePart::Zone);
766 support = partsSeen ? zone : SupportType::None;
767
768 constexpr auto join = [](SupportType lhs, SupportType rhs) -> SupportType {
769 Q_PRE(lhs != SupportType::HasStrays);
770 Q_PRE(rhs != SupportType::HasStrays);
771 // For combining SupportTypes from different Parts to determine support
772 // for their composite. Simplest case is when they're the same:
773 if (lhs == rhs)
774 return lhs;
775 // Every combination of distinct values among the other three is partial:
776 return SupportType::Partial;
777 };
778
779#define CHECK(field) (categories.test(TemporalFieldCategory::field))
780
781 if (wanted.testFlag(DateTimePart::Date)) {
782 const SupportType hasDate = [&] {
783 // if (CHECK(JulianDay)) return SupportType::Clear;
784 int fields = 0;
785 bool partial = false;
786 if (CHECK(Year)) {
787 ++fields;
788 } else if (CHECK(YearWithinCentury)) {
789 if (hasBaseYear) {
790 ++fields;
791 // } else if (CHECK(Century)) { ++fields;
792 } else if (CHECK(DayOfWeek) && CHECK(DayOfMonth) && CHECK(Month)) {
793 // We can infer century from those three by assuming it's
794 // close to the present.
795 ++fields;
796 } else {
797 partial = true;
798 }
799 // } else if (CHECK(Century)) { partial = true;
800 }
801 if (CHECK(Month))
802 ++fields;
803 if (CHECK(DayOfMonth))
804 ++fields;
805 else if (CHECK(DayOfWeek))
806 partial = true;
807 if (fields == 3 && !partial)
808 return SupportType::Clear;
809 if (fields || partial)
810 return SupportType::Partial;
811 return SupportType::None;
812 }();
813 support = partsSeen ? join(support, hasDate) : hasDate;
814 partsSeen = true;
815 }
816
817 if (wanted.testFlag(DateTimePart::Time)) {
818 const SupportType hasTime = [&] {
819 // if (CHECK(MillisecondInDay)) return SupportType::Clear;
820 int fields = 0;
821 bool partial = false;
822 if (CHECK(Hour)) {
823 ++fields;
824 } else if (CHECK(HourMod12)) {
825 if (CHECK(PeriodInDay))
826 ++fields;
827 else
828 partial = true;
829 } else if (CHECK(PeriodInDay)) {
830 partial = true;
831 }
832 if (CHECK(Minute))
833 ++fields;
834 // Hour and minute are required, but seconds and later are optional;
835 // however, having a finer field without an coarser one leaves a gap => Partial.
836 if (CHECK(Second))
837 partial = fields < 2;
838 else if (CHECK(SecondFraction))
839 partial = true;
840 if (fields == 2 && !partial)
841 return SupportType::Clear;
842 if (fields || partial)
843 return SupportType::Partial;
844 return SupportType::None;
845 }();
846 support = partsSeen ? join(support, hasTime) : hasTime;
847 partsSeen = true;
848 }
849
850#undef CHECK
851
852 // Shall still be None if we've seen no fields:
853 Q_ASSERT(partsSeen || support == SupportType::None);
854 return support;
855}
856
857} // namespace QtTemporalPattern
858
859/*!
860 \internal
861 \since 6.12
862 \class QDateTimePattern
863 \brief A description of a serialization format for a datetime
864*/
865
866/*!
867 \fn QDateTimePattern::forLocale(const QLocale &locale, QLocale::FormatType format)
868 Construct a QDateTimePattern appropriate to the given \a locale.
869
870 The \a format can be used to select how compact or expansive the pattern is.
871
872 \sa fromQtFormat()
873*/
874
875/*!
876 \fn QDateTimePattern::isNull() const noexcept
877
878 Returns \c true if this pattern has no fields, otherwise \a false.
879
880 \sa fromQtFormat()
881*/
882
883/*
884//! [is-valid]
885 Returns \c true if this pattern can be used to reliably transmit {\1}s.
886
887 Returns \c false if there is unresolved ambiguity in the texts it will
888 produce when serializing or the texts that will match it when parsing.
889 Some apparent ambiguities may be resolved by interactions between other
890 fields or the \c{defaults} parameter to \l{parse()}.
891//! [is-valid]
892*/
893
894// TODO: currently (see supports(), above) doesn't take locale or calendar into account.
895/*!
896 \fn QDateTimePattern::isValid() const noexcept
897
898 \include qttemporalpattern.cpp {is-valid} {datetime}
899 \include qttemporalpattern.cpp base-year-disambiguates
900
901 Timezone abbreviations are ambiguous.
902
903 \sa isNull()
904*/
905
906/*!
907 \fn QDateTimePattern::setLocale(const QLocale &loc) noexcept
908
909//! [set-locale]
910 Sets the locale, for use for fields whose representation depends on locale,
911 to \a loc. By default the application's current default locale is used.
912
913 \sa QLocale::setDefault()
914//! [set-locale]
915*/
916
917/*!
918 \fn QDateTimePattern::locale() const noexcep
919
920 Returns the current locale in use by this pattern.
921
922 \sa setLocale()
923*/
924
925/*!
926 \fn QDateTimePattern::setCalendar(QCalendar calendar) noexcept
927
928 \include qttemporalpattern.cpp set-calendar
929*/
930
931/*!
932 \fn QDateTimePattern::calendar(QCalendar calendar) const noexcept
933
934 Returns the current calendar in use by this pattern.
935
936 \sa setCalendar()
937*/
938
939/*!
940 \fn QDateTimePattern::setBaseYear(int centuryStart) noexcept
941
942 \include qttemporalpattern.cpp set-base-year
943*/
944
945/*!
946 \fn QDateTimePattern::clearBaseYear() noexcept
947
948 \include qttemporalpattern.cpp clear-base-year
949*/
950
951/*!
952 \fn QDateTimePattern::baseYear() const noexcept
953
954 \include qttemporalpattern.cpp get-base-year
955*/
956
957/*!
958 Parse and return the datetime represented by \a text.
959
960//! [parser-defaults]
961 If \a defaults is provided and valid, any fields the format described by
962 this pattern does not provide will be copied from \a defaults to construct
963 the returned value.
964//! [parser-defaults]
965*/
966
967QtTemporalPattern::ParseResult<QDateTime>
968QDateTimePattern::parse(QStringView text, const QDateTime &defaults) const
969{
970#if QT_CONFIG(datetimeparser)
971 const auto seen = QtParseTemporal::prefix(text, m_fields, m_locale, m_calendar, m_baseYear);
972 if (!m_fields.isEmpty() && !seen) // Failed to parse.
973 return {};
974
975 const QDate date = seen.date(m_calendar, defaults.date());
976 const QTime time = seen.time(defaults.time());
977
978 if (QDateTime result(date, time, seen.zone, seen.resolveType()); result.isValid())
979 return {std::move(result), seen.size()};
980 // Fall back to default transition resolution:
981 return {QDateTime(date, time, seen.zone), seen.size()};
982#else
983 Q_UNUSED(text);
984 Q_UNUSED(defaults);
985 return {};
986#endif // datetimeparser
987}
988
989/*!
990 Serialize the given \a datetime to a string representation.
991*/
992
993QString QDateTimePattern::serialize(const QDateTime &datetime) const
994{
995 Q_UNUSED(datetime);
996 return {};
997}
998
999/*!
1000 Construct a QDateTimePattern described by the given \a format string.
1001
1002 If the format is empty or malformed, the returned pattern's \c isNull() shall
1003 be \c true. Otherwise, \c isNull() shall be \c false.
1004
1005 \sa forLocale(), isNull()
1006*/
1007
1008QDateTimePattern QDateTimePattern::fromQtFormat(QStringView format)
1009{
1010 using namespace QtTemporalPattern;
1011 constexpr DateTimeParts form = DateTimePart::Date | DateTimePart::Time | DateTimePart::Zone;
1012 const auto qt = QtParseQtTemporalFormat::prefix(format, form);
1013 if (qt.size() == format.size())
1014 return QDateTimePattern(qt.fields);
1015 return QDateTimePattern({});
1016}
1017
1018/*!
1019 \internal
1020 \since 6.12
1021 \class QTimePattern
1022 \brief A description of a serialization format for a time
1023*/
1024
1025/*!
1026 \fn QTimePattern::forLocale(const QLocale &locale, QLocale::FormatType format)
1027 Construct a QTimePattern appropriate to the given \a locale.
1028
1029 The \a format can be used to select how compact or expansive the pattern is.
1030
1031 \sa fromQtFormat()
1032*/
1033
1034/*!
1035 \fn QTimePattern::isNull() const noexcept
1036
1037 Returns \c true if this pattern has no fields, otherwise \a false.
1038
1039 \sa fromQtFormat()
1040*/
1041
1042/*!
1043 \fn QTimePattern::isValid() const noexcept
1044
1045 \include qttemporalpattern.cpp {is-valid} {time}
1046
1047 \sa isNull()
1048*/
1049
1050/*!
1051 \fn QTimePattern::setLocale(const QLocale &loc) noexcept
1052
1053 \include qttemporalpattern.cpp set-locale
1054*/
1055
1056/*!
1057 \fn QTimePattern::locale() const noexcep
1058
1059 Returns the current locale in use by this pattern.
1060
1061 \sa setLocale()
1062*/
1063
1064/*!
1065 Parse and return the time represented by \a text.
1066
1067 \include qttemporalpattern.cpp parser-defaults
1068*/
1069
1070QtTemporalPattern::ParseResult<QTime>
1071QTimePattern::parse(QStringView text, QTime defaults) const
1072{
1073#if QT_CONFIG(datetimeparser)
1074 const auto seen = QtParseTemporal::prefix(text, m_fields, m_locale, QCalendar());
1075 if (!m_fields.isEmpty() && !seen) // Failed to parse.
1076 return {};
1077 return {seen.time(defaults), seen.size()};
1078#else
1079 Q_UNUSED(text);
1080 Q_UNUSED(defaults);
1081 return {};
1082#endif // datetimeparser
1083}
1084
1085/*!
1086 Serialize the given \a time to a string representation.
1087*/
1088
1089QString QTimePattern::serialize(const QTime &time) const
1090{
1091 Q_UNUSED(time);
1092 return {};
1093}
1094
1095/*!
1096 Construct a QTimePattern described by the given \a format string.
1097
1098 If the format is empty or malformed, the returned pattern's \c isNull() shall
1099 be \c true. Otherwise, \c isNull() shall be \c false.
1100
1101 \sa forLocale(), isNull()
1102*/
1103
1104QTimePattern QTimePattern::fromQtFormat(QStringView format)
1105{
1106 using namespace QtTemporalPattern;
1107 constexpr DateTimeParts form{DateTimePart::Time};
1108 const auto qt = QtParseQtTemporalFormat::prefix(format, form);
1109 if (qt.size() == format.size())
1110 return QTimePattern(qt.fields);
1111 return QTimePattern({});
1112}
1113
1114/*!
1115 \internal
1116 \since 6.12
1117 \class QDatePattern
1118 \brief A description of a serialization format for a date
1119*/
1120
1121/*!
1122 \fn QDatePattern::forLocale(const QLocale &locale, QLocale::FormatType format)
1123 Construct a QDatePattern appropriate to the given \a locale.
1124
1125 The \a format can be used to select how compact or expansive the pattern is.
1126
1127 \sa fromQtFormat()
1128*/
1129
1130/*!
1131 \fn QDatePattern::isNull() const noexcept
1132
1133 Returns \c true if this pattern has no fields, otherwise \a false.
1134
1135 \sa fromQtFormat()
1136*/
1137
1138/*!
1139 \fn QDatePattern::isValid() const noexcept
1140
1141 \include qttemporalpattern.cpp {is-valid} {date}
1142
1143//! [base-year-disambiguates]
1144 The ambiguity of two-digit years may be resolved by configuring the hundred
1145 years among which to select a matching years.
1146//! [base-year-disambiguates]
1147
1148 \sa setBaseYear(), isNull()
1149*/
1150
1151/*!
1152 \fn QDatePattern::setLocale(const QLocale &loc) noexcept
1153
1154 \include qttemporalpattern.cpp set-locale
1155*/
1156
1157/*!
1158 \fn QDatePattern::locale() const noexcep
1159
1160 Returns the current locale in use by this pattern.
1161
1162 \sa setLocale()
1163*/
1164
1165/*!
1166 \fn QDatePattern::setCalendar(QCalendar calendar) noexcept
1167
1168//! [set-calendar]
1169 Sets the calendar used by this pattern. This influences the names and
1170 lengths of months and how these vary from year to year. In some cases it may
1171 also influence the number of months in the year or even the pattern and
1172 names of days of the week.
1173
1174 By default the Gregorian calendar is used.
1175
1176 \sa getCalendar(), QCalendar
1177//! [set-calendar]
1178*/
1179
1180/*!
1181 \fn QDatePattern::calendar(QCalendar calendar) const noexcept
1182
1183 Returns the current calendar in use by this pattern.
1184
1185 \sa setCalendar()
1186*/
1187
1188/*!
1189 \fn QDatePattern::setBaseYear(int centuryStart) noexcept
1190
1191//! [set-base-year]
1192 Configures the handling of two-digit years, if any are present in the pattern.
1193
1194 If a two-digit year is present, the year ending in those two digits in the
1195 range from \a centuryStart to \c {centuryStart + 99} shall be its default
1196 interpretation. This may be amended if the month, day of the month and day
1197 of the week indicate some other nearby century.
1198
1199 \note the years here, including \a centuryStart, are expressed with respect
1200 to \c{calendar()}, whose year numbering need not match that of the Gregorian
1201 calendar.
1202
1203 Calling this method makes no difference unless the pattern does in fact use
1204 a two-digit year, nor does it affect serialization.
1205
1206 \sa clearBaseYear()
1207//! [set-base-year]
1208*/
1209
1210// TODO: should the default state be clear or some specific year ?
1211// That year could depend on the present, e.g. present minus 49 years.
1212
1213/*!
1214 \fn QDatePattern::clearBaseYear() noexcept
1215
1216//! [clear-base-year]
1217 Leaves the handling of two-digit years to other fields to disambiguate.
1218
1219 This is the default state, so has no effect unless \l setBaseYear() has
1220 previously been called.
1221
1222 If a two-digit year is present, this leaves unspecified which hundred years
1223 to presume it lies within. If a two-digit year is present and other fields
1224 of the pattern do not suffice to make clear which hundred years to select
1225 based on the given last two digits, the text produced when serializing with
1226 this format shall generally be ambiguous. While readers of the text may be
1227 able to disambiguate the year anyway, there is scope for misunderstanding if
1228 their heuristics for doing so do not match your expectation. On parsing, the
1229 pattern may deliver a result that is off by some whole number of centuries
1230 from what the parsed text's author intended.
1231
1232 \sa setBaseYear(), isValid()
1233//! [clear-base-year]
1234*/
1235
1236/*!
1237 \fn QDatePattern::baseYear() const noexcept
1238
1239//! [get-base-year]
1240
1241 Returns the current base year, with respect to \c{calendar()}, used by this
1242 pattern if it needs to resolve a two-digit year. The result is \c
1243 {std::nullopt} when no base year is set, which is the default state.
1244
1245 \sa setBaseYear()
1246//! [get-base-year]
1247*/
1248
1249/*!
1250 Parse and return the date represented by \a text.
1251
1252 \include qttemporalpattern.cpp parser-defaults
1253*/
1254
1255QtTemporalPattern::ParseResult<QDate>
1256QDatePattern::parse(QStringView text, QDate defaults) const
1257{
1258#if QT_CONFIG(datetimeparser)
1259 const auto seen = QtParseTemporal::prefix(text, m_fields, m_locale, m_calendar, m_baseYear);
1260 if (!m_fields.isEmpty() && !seen) // Failed to parse.
1261 return {};
1262 return {seen.date(m_calendar, defaults), seen.size()};
1263#else
1264 Q_UNUSED(text);
1265 Q_UNUSED(defaults);
1266 return {};
1267#endif // datetimeparser
1268}
1269
1270/*!
1271 Serialize the given \a date to a string representation.
1272
1273 \sa parse()
1274*/
1275
1276QString QDatePattern::serialize(const QDate &date) const
1277{
1278 Q_UNUSED(date);
1279 return {};
1280}
1281
1282/*!
1283 Construct a QDatePattern described by the given \a format string.
1284
1285 If the format is empty or malformed, the returned pattern's \c isNull() shall
1286 be \c true. Otherwise, \c isNull() shall be \c false.
1287
1288 \sa forLocale(), isNull()
1289*/
1290
1291QDatePattern QDatePattern::fromQtFormat(QStringView format)
1292{
1293 using namespace QtTemporalPattern;
1294 constexpr DateTimeParts form{DateTimePart::Date};
1295 const auto qt = QtParseQtTemporalFormat::prefix(format, form);
1296 if (qt.size() == format.size())
1297 return QDatePattern(qt.fields);
1298 return QDatePattern({});
1299}
1300
1301QT_END_NAMESPACE
Supporting types and functions for temporal patterns.
SupportType supports(DateTimeParts wanted, QSpan< const TemporalField > range, bool hasBaseYear) noexcept
#define CHECK(cvref)