Skip to main content

jiff/fmt/temporal/
mod.rs

1/*!
2A hybrid format derived from [RFC 3339], [RFC 9557] and [ISO 8601].
3
4This module provides an implementation of the [Temporal ISO 8601 grammar]. The
5API is spread out over parsers and printers for datetimes and spans.
6
7Note that for most use cases, you should be using the corresponding
8[`Display`](std::fmt::Display) or [`FromStr`](std::str::FromStr) trait
9implementations for printing and parsing respectively. This module provides
10a "lower level" API for configuring the behavior of printing and parsing,
11including the ability to parse from byte strings (i.e., `&[u8]`).
12
13# Date and time format
14
15The specific format supported depends on what kind of type you're trying to
16parse into. Here are some examples to give a general idea:
17
18* `02:21:58` parses into a [`civil::Time`].
19* `2020-08-21` parses into a [`civil::Date`].
20* `2020-08-21T02:21:58` and `2020-08-21 02:21:58` both parse into a
21  [`civil::DateTime`].
22* `2020-08-21T02:21:58-04` parses into an [`Timestamp`].
23* `2020-08-21T02:21:58-04[America/New_York]` parses into a [`ZonedDateTime`].
24
25Smaller types can generally be parsed from strings representing a bigger type.
26For example, a `civil::Date` can be parsed from `2020-08-21T02:21:58`.
27
28As mentioned above, the datetime format supported by Jiff is a hybrid of the
29"best" parts of [RFC 3339], [RFC 9557] and [ISO 8601]. Generally speaking, [RFC
303339] and [RFC 9557] are supported in their entirety, but not all of ISO 8601
31is. For example, `2024-06-16T10.5` is a valid ISO 8601 datetime, but isn't
32supported by Jiff. (Only fractional seconds are supported.)
33
34Some additional details worth noting:
35
36* Parsing `ZonedDateTime` values requires a datetime string with a time zone
37annotation like `[America/New_York]` or `[-07:00]`. If you need to parse a
38datetime without a time zone annotation (but with an offset), then you should
39parse it as an [`Timestamp`]. From there, it can be converted to a
40`ZonedDateTime` via [`Timestamp::to_zoned_datetime`].
41* When parsing `ZonedDateTime` values, ambiguous datetimes are handled via the
42[`DateTimeParser::disambiguation`] configuration. By default, a "compatible"
43mode is used where the earlier time is selected in a backward transition, while
44the later time is selected in a forward transition.
45* When parsing `ZonedDateTime` values, conflicts between the offset and the
46time zone in the datetime string are handled via the
47[`DateTimeParser::offset_conflict`] configuration. By default, any
48inconsistency between the offset and the time zone results in a parse error.
49* When parsing civil types like `civil::DateTime`, it's always an error if the
50datetime string has a `Z` (Zulu) offset. It's an error since interpreting such
51strings as civil time is usually a bug.
52* In all cases, the `T` designator separating the date and time may be an ASCII
53space instead.
54
55The complete datetime format supported is described by the
56[Temporal ISO 8601 grammar].
57
58# Span format
59
60To a first approximation, the span format supported roughly corresponds to this
61regular expression:
62
63```text
64P(\d+y)?(\d+m)?(\d+w)?(\d+d)?(T(\d+h)?(\d+m)?(\d+s)?)?
65```
66
67But there are some details not easily captured by a simple regular expression:
68
69* At least one unit must be specified. To write a zero span, specify `0` for
70any unit. For example, `P0d` and `PT0s` are equivalent.
71* The format is case insensitive. The printer will by default capitalize all
72designators, but the unit designators can be configured to use lowercase with
73[`SpanPrinter::lowercase`]. For example, `P3y1m10dT5h` instead of
74`P3Y1M10DT5H`. You might prefer lowercase since you may find it easier to read.
75However, it is an extension to ISO 8601 and isn't as broadly supported.
76* Hours, minutes or seconds may be fractional. And the only units that may be
77fractional are the lowest units.
78* A span like `P99999999999y` is invalid because it exceeds the allowable range
79of time representable by a [`Span`].
80
81This is, roughly speaking, a subset of what [ISO 8601] specifies. It isn't
82strictly speaking a subset since Jiff (like Temporal) permits week units to be
83mixed with other units.
84
85Here are some examples:
86
87```
88use jiff::{Span, ToSpan};
89
90let spans = [
91    ("P40D", 40.days()),
92    ("P1y1d", 1.year().days(1)),
93    ("P3dT4h59m", 3.days().hours(4).minutes(59)),
94    ("PT2H30M", 2.hours().minutes(30)),
95    ("P1m", 1.month()),
96    ("P1w", 1.week()),
97    ("P1w4d", 1.week().days(4)),
98    ("PT1m", 1.minute()),
99    ("PT0.0021s", 2.milliseconds().microseconds(100)),
100    ("PT0s", 0.seconds()),
101    ("P0d", 0.seconds()),
102    (
103        "P1y1m1dT1h1m1.1s",
104        1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
105    ),
106];
107for (string, span) in spans {
108    let parsed: Span = string.parse()?;
109    assert_eq!(
110        span.fieldwise(),
111        parsed.fieldwise(),
112        "result of parsing {string:?}",
113    );
114}
115
116# Ok::<(), Box<dyn std::error::Error>>(())
117```
118
119One can also parse ISO 8601 durations into a [`SignedDuration`], but units are
120limited to hours or smaller:
121
122```
123use jiff::SignedDuration;
124
125let durations = [
126    ("PT2H30M", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
127    ("PT2.5h", SignedDuration::from_secs(2 * 60 * 60 + 30 * 60)),
128    ("PT1m", SignedDuration::from_mins(1)),
129    ("PT1.5m", SignedDuration::from_secs(90)),
130    ("PT0.0021s", SignedDuration::new(0, 2_100_000)),
131    ("PT0s", SignedDuration::ZERO),
132    ("PT0.000000001s", SignedDuration::from_nanos(1)),
133];
134for (string, duration) in durations {
135    let parsed: SignedDuration = string.parse()?;
136    assert_eq!(duration, parsed, "result of parsing {string:?}");
137}
138
139# Ok::<(), Box<dyn std::error::Error>>(())
140```
141
142The complete span format supported is described by the [Temporal ISO 8601
143grammar].
144
145# Differences with Temporal
146
147Jiff implements Temporal's grammar pretty closely, but there are a few
148differences at the time of writing. It is a specific goal that all differences
149should be rooted in what Jiff itself supports, and not in the grammar itself.
150
151* The maximum UTC offset value expressible is `25:59:59` in Jiff, where as in
152Temporal it's `23:59:59.999999999`. Jiff supports a slightly bigger maximum
153to account for all valid values of POSIX time zone strings. Jiff also lacks
154nanosecond precision for UTC offsets, as it's not clear how useful that is in
155practice.
156* Jiff doesn't support a datetime range as big as Temporal. For example,
157in Temporal, `+202024-06-14T17:30[America/New_York]` is valid. But in Jiff,
158since the maximum supported year is `9999`, parsing will fail. Jiff's datetime
159range may be expanded in the future, but it is a non-goal to match Temporal's
160range precisely.
161* Jiff doesn't support RFC 9557 calendar annotations because Jiff only supports
162the Gregorian calendar.
163
164There is some more [background on Temporal's format] available.
165
166[Temporal ISO 8601 grammar]: https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar
167[RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339
168[RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
169[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
170[background on Temporal's format]: https://github.com/tc39/proposal-temporal/issues/2843
171*/
172
173use crate::{
174    SignedDuration, Timestamp, ZonedDateTime,
175    civil::{self, ISOWeekDate},
176    error::Error,
177    fmt::Write,
178    span::Span,
179    tz::{Disambiguation, Offset, OffsetConflict, TimeZone, TimeZoneDatabase},
180};
181
182pub use self::pieces::{
183    Pieces, PiecesNumericOffset, PiecesOffset, TimeZoneAnnotation,
184    TimeZoneAnnotationKind, TimeZoneAnnotationName,
185};
186
187mod parser;
188mod pieces;
189mod printer;
190
191/// The default date time parser that we use throughout Jiff.
192pub(crate) static DEFAULT_DATETIME_PARSER: DateTimeParser =
193    DateTimeParser::new();
194
195/// The default date time printer that we use throughout Jiff.
196pub(crate) static DEFAULT_DATETIME_PRINTER: DateTimePrinter =
197    DateTimePrinter::new();
198
199/// The default date time parser that we use throughout Jiff.
200pub(crate) static DEFAULT_SPAN_PARSER: SpanParser = SpanParser::new();
201
202/// The default date time printer that we use throughout Jiff.
203pub(crate) static DEFAULT_SPAN_PRINTER: SpanPrinter = SpanPrinter::new();
204
205/// A parser for Temporal datetimes.
206///
207/// This parser converts a machine (but also human) readable format of a
208/// datetime to the various types found in Jiff: [`ZonedDateTime`],
209/// [`Timestamp`], [`civil::DateTime`], [`civil::Date`] or [`civil::Time`].
210/// Note that all of those types provide [`FromStr`](core::str::FromStr)
211/// implementations that utilize the default configuration of this parser.
212/// However, this parser can be configured to behave differently and can also
213/// parse directly from a `&[u8]`.
214///
215/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
216/// more information on the specific format used.
217///
218/// # Example
219///
220/// This example shows how to parse a `ZonedDateTime` datetime from a byte
221/// string. (That is, `&[u8]` and not a `&str`.)
222///
223/// ```
224/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
225///
226/// // A parser can be created in a const context.
227/// static PARSER: DateTimeParser = DateTimeParser::new();
228///
229/// let zdt =
230///     PARSER.parse_zoned_datetime(b"2024-06-15T07-04[America/New_York]")?;
231/// assert_eq!(zdt.datetime(), date(2024, 6, 15).at(7, 0, 0, 0));
232/// assert_eq!(zdt.time_zone(), &tz::db().get("America/New_York")?);
233///
234/// # Ok::<(), Box<dyn std::error::Error>>(())
235/// ```
236///
237/// Note that an ASCII space instead of the `T` separator is automatically
238/// supported too:
239///
240/// ```
241/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
242///
243/// // A parser can be created in a const context.
244/// static PARSER: DateTimeParser = DateTimeParser::new();
245///
246/// let zdt =
247///     PARSER.parse_zoned_datetime(b"2024-06-15 07-04[America/New_York]")?;
248/// assert_eq!(zdt.datetime(), date(2024, 6, 15).at(7, 0, 0, 0));
249/// assert_eq!(zdt.time_zone(), &tz::db().get("America/New_York")?);
250///
251/// # Ok::<(), Box<dyn std::error::Error>>(())
252/// ```
253#[derive(#[automatically_derived]impl ::core::fmt::Debug for DateTimeParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "DateTimeParser p offset_conflict disambiguation", &self.p,
            &self.offset_conflict, &&self.disambiguation)
    }
}Debug)]
254pub struct DateTimeParser {
255    p: parser::DateTimeParser,
256    offset_conflict: OffsetConflict,
257    disambiguation: Disambiguation,
258}
259
260impl DateTimeParser {
261    /// Create a new Temporal datetime parser with the default configuration.
262    #[inline]
263    pub const fn new() -> DateTimeParser {
264        DateTimeParser {
265            p: parser::DateTimeParser::new(),
266            offset_conflict: OffsetConflict::Reject,
267            disambiguation: Disambiguation::Compatible,
268        }
269    }
270
271    /// Set the conflict resolution strategy for when an offset in a datetime
272    /// string is inconsistent with the time zone.
273    ///
274    /// See the documentation on [`OffsetConflict`] for more details about the
275    /// different strategies one can choose.
276    ///
277    /// This only applies when parsing [`ZonedDateTime`] values.
278    ///
279    /// The default is [`OffsetConflict::Reject`], which results in an error
280    /// whenever parsing a datetime with an offset that is inconsistent with
281    /// the time zone.
282    ///
283    /// # Example: respecting offsets even when they're invalid
284    ///
285    /// ```
286    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
287    ///
288    /// static PARSER: DateTimeParser = DateTimeParser::new()
289    ///     .offset_conflict(tz::OffsetConflict::AlwaysOffset);
290    ///
291    /// let zdt = PARSER
292    ///     .parse_zoned_datetime("2024-06-09T07:00-05[America/New_York]")?;
293    /// // Notice that the time *and* offset have been corrected. The offset
294    /// // given was invalid for `America/New_York` at the given time, so
295    /// // it cannot be kept, but the instant returned is equivalent to
296    /// // `2024-06-09T07:00-05`. It is just adjusted automatically to be
297    /// // correct in the `America/New_York` time zone.
298    /// assert_eq!(zdt.datetime(), date(2024, 6, 9).at(8, 0, 0, 0));
299    /// assert_eq!(zdt.offset(), tz::offset(-4));
300    ///
301    /// # Ok::<(), Box<dyn std::error::Error>>(())
302    /// ```
303    ///
304    /// # Example: all offsets are invalid for gaps in civil time by default
305    ///
306    /// When parsing a datetime with an offset for a gap in civil time, the
307    /// offset is treated as invalid. This results in parsing failing. For
308    /// example, some parts of Indiana in the US didn't start using daylight
309    /// saving time until 2006. If a datetime for 2006 were serialized before
310    /// the updated daylight saving time rules were known, then this parse
311    /// error will prevent you from silently changing the originally intended
312    /// time:
313    ///
314    /// ```
315    /// use jiff::{fmt::temporal::DateTimeParser};
316    ///
317    /// static PARSER: DateTimeParser = DateTimeParser::new();
318    ///
319    /// // DST in Indiana/Vevay began at 2006-04-02T02:00 local time.
320    /// // The last time Indiana/Vevay observed DST was in 1972.
321    /// let result = PARSER.parse_zoned_datetime(
322    ///     "2006-04-02T02:30-05[America/Indiana/Vevay]",
323    /// );
324    /// assert_eq!(
325    ///     result.unwrap_err().to_string(),
326    ///     "datetime could not resolve to timestamp since `reject` \
327    ///      conflict resolution was chosen, and because datetime \
328    ///      has offset `-05`, but the time zone `America/Indiana/Vevay` \
329    ///      for the given datetime falls in a gap (between offsets \
330    ///      `-05` and `-04`), and all offsets for a gap are \
331    ///      regarded as invalid",
332    /// );
333    /// ```
334    ///
335    /// If one doesn't want an error here, then you can either prioritize the
336    /// instant in time by respecting the offset:
337    ///
338    /// ```
339    /// use jiff::{fmt::temporal::DateTimeParser, tz};
340    ///
341    /// static PARSER: DateTimeParser = DateTimeParser::new()
342    ///     .offset_conflict(tz::OffsetConflict::AlwaysOffset);
343    ///
344    /// let zdt = PARSER.parse_zoned_datetime(
345    ///     "2006-04-02T02:30-05[America/Indiana/Vevay]",
346    /// )?;
347    /// assert_eq!(
348    ///     zdt.to_string(),
349    ///     "2006-04-02T03:30:00-04:00[America/Indiana/Vevay]",
350    /// );
351    ///
352    /// # Ok::<(), Box<dyn std::error::Error>>(())
353    /// ```
354    ///
355    /// or you can force your own disambiguation rules, e.g., by taking the
356    /// earlier time:
357    ///
358    /// ```
359    /// use jiff::{fmt::temporal::DateTimeParser, tz};
360    ///
361    /// static PARSER: DateTimeParser = DateTimeParser::new()
362    ///     .disambiguation(tz::Disambiguation::Earlier)
363    ///     .offset_conflict(tz::OffsetConflict::AlwaysTimeZone);
364    ///
365    /// let zdt = PARSER.parse_zoned_datetime(
366    ///     "2006-04-02T02:30-05[America/Indiana/Vevay]",
367    /// )?;
368    /// assert_eq!(
369    ///     zdt.to_string(),
370    ///     "2006-04-02T01:30:00-05:00[America/Indiana/Vevay]",
371    /// );
372    ///
373    /// # Ok::<(), Box<dyn std::error::Error>>(())
374    /// ```
375    ///
376    /// # Example: a `Z` never results in an offset conflict
377    ///
378    /// [RFC 9557] specifies that `Z` indicates that the offset from UTC to
379    /// get local time is unknown. Since it doesn't prescribe a particular
380    /// offset, when a `Z` is parsed with a time zone annotation, the
381    /// `OffsetConflict::ALwaysOffset` strategy is used regardless of what
382    /// is set here. For example:
383    ///
384    /// ```
385    /// use jiff::fmt::temporal::DateTimeParser;
386    ///
387    /// // NOTE: The default is reject.
388    /// static PARSER: DateTimeParser = DateTimeParser::new();
389    ///
390    /// let zdt = PARSER.parse_zoned_datetime(
391    ///     "2025-06-20T17:30Z[America/New_York]",
392    /// )?;
393    /// assert_eq!(
394    ///     zdt.to_string(),
395    ///     "2025-06-20T13:30:00-04:00[America/New_York]",
396    /// );
397    ///
398    /// # Ok::<(), Box<dyn std::error::Error>>(())
399    /// ```
400    ///
401    /// Conversely, if the `+00:00` offset was used, then an error would
402    /// occur because of the offset conflict:
403    ///
404    /// ```
405    /// use jiff::fmt::temporal::DateTimeParser;
406    ///
407    /// // NOTE: The default is reject.
408    /// static PARSER: DateTimeParser = DateTimeParser::new();
409    ///
410    /// let result = PARSER.parse_zoned_datetime(
411    ///     "2025-06-20T17:30+00[America/New_York]",
412    /// );
413    /// assert_eq!(
414    ///     result.unwrap_err().to_string(),
415    ///     "datetime could not resolve to a timestamp since `reject` \
416    ///      conflict resolution was chosen, and because datetime has \
417    ///      offset `+00`, but the time zone `America/New_York` \
418    ///      for the given datetime unambiguously has offset `-04`",
419    /// );
420    /// ```
421    ///
422    /// [RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/
423    #[inline]
424    pub const fn offset_conflict(
425        self,
426        strategy: OffsetConflict,
427    ) -> DateTimeParser {
428        DateTimeParser { offset_conflict: strategy, ..self }
429    }
430
431    /// Set the disambiguation strategy for when a datetime falls into a time
432    /// zone transition "fold" or "gap."
433    ///
434    /// The most common manifestation of such time zone transitions is daylight
435    /// saving time. In most cases, the transition into daylight saving time
436    /// moves the civil time ("the time you see on the clock") ahead one hour.
437    /// This is called a "gap" because an hour on the clock is skipped. While
438    /// the transition out of daylight saving time moves the civil time back
439    /// one hour. This is called a "fold" because an hour on the clock is
440    /// repeated.
441    ///
442    /// In the case of a gap, an ambiguous datetime manifests as a time that
443    /// never appears on a clock. (For example, `02:30` on `2024-03-10` in New
444    /// York.) In the case of a fold, an ambiguous datetime manifests as a
445    /// time that repeats itself. (For example, `01:30` on `2024-11-03` in New
446    /// York.) So when a fold occurs, you don't know whether it's the "first"
447    /// occurrence of that time or the "second."
448    ///
449    /// Time zone transitions are not just limited to daylight saving time,
450    /// although those are the most common. In other cases, a transition occurs
451    /// because of a change in the offset of the time zone itself. (See the
452    /// examples below.)
453    ///
454    /// # Example
455    ///
456    /// This example shows how to set the disambiguation configuration while
457    /// parsing a [`ZonedDateTime`] datetime. In this example, we always prefer
458    /// the earlier time.
459    ///
460    /// ```
461    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
462    ///
463    /// static PARSER: DateTimeParser = DateTimeParser::new()
464    ///     .disambiguation(tz::Disambiguation::Earlier);
465    ///
466    /// let zdt = PARSER
467    ///     .parse_zoned_datetime("2024-03-10T02:05[America/New_York]")?;
468    /// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(1, 5, 0, 0));
469    /// assert_eq!(zdt.offset(), tz::offset(-5));
470    ///
471    /// # Ok::<(), Box<dyn std::error::Error>>(())
472    /// ```
473    ///
474    /// # Example: time zone offset change
475    ///
476    /// In this example, we explore a time zone offset change in Hawaii that
477    /// occurred on `1947-06-08`. Namely, Hawaii went from a `-10:30` offset
478    /// to a `-10:00` offset at `02:00`. This results in a 30 minute gap in
479    /// civil time.
480    ///
481    /// ```
482    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz, ToSpan};
483    ///
484    /// static PARSER: DateTimeParser = DateTimeParser::new()
485    ///     .disambiguation(tz::Disambiguation::Later);
486    ///
487    /// // 02:05 didn't exist on clocks on 1947-06-08.
488    /// let zdt = PARSER
489    ///     .parse_zoned_datetime("1947-06-08T02:05[Pacific/Honolulu]")?;
490    /// // Our parser is configured to select the later time, so we jump to
491    /// // 02:35. But if we used `Disambiguation::Earlier`, then we'd get
492    /// // 01:35.
493    /// assert_eq!(zdt.datetime(), date(1947, 6, 8).at(2, 35, 0, 0));
494    /// assert_eq!(zdt.offset(), tz::offset(-10));
495    ///
496    /// // If we subtract 10 minutes from 02:35, notice that we (correctly)
497    /// // jump to 01:55 *and* our offset is corrected to -10:30.
498    /// let zdt = zdt.checked_sub(10.minutes())?;
499    /// assert_eq!(zdt.datetime(), date(1947, 6, 8).at(1, 55, 0, 0));
500    /// assert_eq!(zdt.offset(), tz::offset(-10).saturating_sub(30.minutes())?);
501    ///
502    /// # Ok::<(), Box<dyn std::error::Error>>(())
503    /// ```
504    #[inline]
505    pub const fn disambiguation(
506        self,
507        strategy: Disambiguation,
508    ) -> DateTimeParser {
509        DateTimeParser { disambiguation: strategy, ..self }
510    }
511
512    /// Parse a datetime string with a time zone annotation into a
513    /// [`ZonedDateTime`] value using the system time zone database.
514    ///
515    /// # Errors
516    ///
517    /// This returns an error if the datetime string given is invalid or if it
518    /// is valid but doesn't fit in the datetime range supported by Jiff.
519    ///
520    /// The [`DateTimeParser::offset_conflict`] and
521    /// [`DateTimeParser::disambiguation`] settings can also influence
522    /// whether an error occurs or not. Namely, if [`OffsetConflict::Reject`]
523    /// is used (which is the default), then an error occurs when there
524    /// is an inconsistency between the offset and the time zone. And if
525    /// [`Disambiguation::Reject`] is used, then an error occurs when the civil
526    /// time in the string is ambiguous.
527    ///
528    /// # Example: parsing without an IANA time zone
529    ///
530    /// Note that when parsing a `ZonedDateTime` value, it is required for the
531    /// datetime string to contain a time zone annotation in brackets. For
532    /// example, this fails to parse even though it refers to a precise instant
533    /// in time:
534    ///
535    /// ```
536    /// use jiff::fmt::temporal::DateTimeParser;
537    ///
538    /// static PARSER: DateTimeParser = DateTimeParser::new();
539    ///
540    /// assert!(PARSER.parse_zoned_datetime("2024-06-08T07:00-04").is_err());
541    /// ```
542    ///
543    /// While it is better to include a time zone name, if the only thing
544    /// that's available is an offset, the offset can be repeated as a time
545    /// zone annotation:
546    ///
547    /// ```
548    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
549    ///
550    /// static PARSER: DateTimeParser = DateTimeParser::new();
551    ///
552    /// let zdt = PARSER.parse_zoned_datetime("2024-06-08T07:00-04[-04]")?;
553    /// assert_eq!(zdt.datetime(), date(2024, 6, 8).at(7, 0, 0, 0));
554    /// assert_eq!(zdt.offset(), tz::offset(-4));
555    ///
556    /// # Ok::<(), Box<dyn std::error::Error>>(())
557    /// ```
558    ///
559    /// Otherwise, if you need to be able to parse something like
560    /// `2024-06-08T07:00-04` as-is, you should parse it into an [`Timestamp`]:
561    ///
562    /// ```
563    /// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
564    ///
565    /// static PARSER: DateTimeParser = DateTimeParser::new();
566    ///
567    /// let timestamp = PARSER.parse_timestamp("2024-06-08T07:00-04")?;
568    /// let zdt = timestamp.to_zoned_datetime(tz::TimeZone::UTC);
569    /// assert_eq!(zdt.datetime(), date(2024, 6, 8).at(11, 0, 0, 0));
570    /// assert_eq!(zdt.offset(), tz::offset(0));
571    ///
572    /// # Ok::<(), Box<dyn std::error::Error>>(())
573    /// ```
574    ///
575    /// If you _really_ need to parse something like `2024-06-08T07:00-04` into
576    /// a `ZonedDateTime` with a fixed offset of `-04:00` as its `TimeZone`,
577    /// then you'll need to use lower level parsing routines. See the
578    /// documentation on [`Pieces`] for a case study of how to achieve this.
579    pub fn parse_zoned_datetime<I: AsRef<[u8]>>(
580        &self,
581        input: I,
582    ) -> Result<ZonedDateTime, Error> {
583        self.parse_zoned_datetime_with(crate::tz::db(), input)
584    }
585
586    /// Parse a datetime string with a time zone annotation into a
587    /// [`ZonedDateTime`] value using the time zone database given.
588    ///
589    /// # Errors
590    ///
591    /// This returns an error if the datetime string given is invalid or if it
592    /// is valid but doesn't fit in the datetime range supported by Jiff.
593    ///
594    /// The [`DateTimeParser::offset_conflict`] and
595    /// [`DateTimeParser::disambiguation`] settings can also influence
596    /// whether an error occurs or not. Namely, if [`OffsetConflict::Reject`]
597    /// is used (which is the default), then an error occurs when there
598    /// is an inconsistency between the offset and the time zone. And if
599    /// [`Disambiguation::Reject`] is used, then an error occurs when the civil
600    /// time in the string is ambiguous.
601    ///
602    /// # Example
603    ///
604    /// This example demonstrates the utility of this routine by parsing a
605    /// datetime using an older copy of the IANA Time Zone Database. This
606    /// example leverages the fact that the 2018 copy of `tzdb` preceded
607    /// Brazil's announcement that daylight saving time would be abolished.
608    /// This meant that datetimes in the future, when parsed with the older
609    /// copy of `tzdb`, would still follow the old daylight saving time rules.
610    /// But a mere update of `tzdb` would otherwise change the meaning of the
611    /// datetime.
612    ///
613    /// This scenario can come up if one stores datetimes in the future.
614    /// This is also why the default offset conflict resolution strategy
615    /// is [`OffsetConflict::Reject`], which prevents one from silently
616    /// re-interpreting datetimes to a different timestamp.
617    ///
618    /// ```no_run
619    /// use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}};
620    ///
621    /// static PARSER: DateTimeParser = DateTimeParser::new();
622    ///
623    /// // Open a version of tzdb from before Brazil announced its abolition
624    /// // of daylight saving time.
625    /// let tzdb2018 = TimeZoneDatabase::from_dir("path/to/tzdb-2018b")?;
626    /// // Open the system tzdb.
627    /// let tzdb = tz::db();
628    ///
629    /// // Parse the same datetime string with the same parser, but using two
630    /// // different versions of tzdb.
631    /// let dt = "2020-01-15T12:00[America/Sao_Paulo]";
632    /// let zdt2018 = PARSER.parse_zoned_datetime_with(&tzdb2018, dt)?;
633    /// let zdt = PARSER.parse_zoned_datetime_with(tzdb, dt)?;
634    ///
635    /// // Before DST was abolished, 2020-01-15 was in DST, which corresponded
636    /// // to UTC offset -02. Since DST rules applied to datetimes in the
637    /// // future, the 2018 version of tzdb would lead one to interpret
638    /// // 2020-01-15 as being in DST.
639    /// assert_eq!(zdt2018.offset(), tz::offset(-2));
640    /// // But DST was abolished in 2019, which means that 2020-01-15 was no
641    /// // no longer in DST. So after a tzdb update, the same datetime as above
642    /// // now has a different offset.
643    /// assert_eq!(zdt.offset(), tz::offset(-3));
644    ///
645    /// // So if you try to parse a datetime serialized from an older copy of
646    /// // tzdb, you'll get an error under the default configuration because
647    /// // of `OffsetConflict::Reject`. This would succeed if you parsed it
648    /// // using tzdb2018!
649    /// assert!(
650    ///     PARSER
651    ///         .parse_zoned_datetime_with(tzdb, zdt2018.to_string())
652    ///         .is_err()
653    /// );
654    ///
655    /// # Ok::<(), Box<dyn std::error::Error>>(())
656    /// ```
657    pub fn parse_zoned_datetime_with<I: AsRef<[u8]>>(
658        &self,
659        db: &TimeZoneDatabase,
660        input: I,
661    ) -> Result<ZonedDateTime, Error> {
662        let input = input.as_ref();
663        let parsed = self.p.parse_temporal_datetime(input)?;
664        let dt = parsed.into_full()?;
665        let zoned = dt.to_zoned_datetime(
666            db,
667            self.offset_conflict,
668            self.disambiguation,
669        )?;
670        Ok(zoned)
671    }
672
673    /// Parse a datetime string into a [`Timestamp`].
674    ///
675    /// The datetime string must correspond to a specific instant in time. This
676    /// requires an offset in the datetime string.
677    ///
678    /// # Errors
679    ///
680    /// This returns an error if the datetime string given is invalid or if it
681    /// is valid but doesn't fit in the datetime range supported by Jiff.
682    ///
683    /// # Example
684    ///
685    /// This shows a basic example of parsing an `Timestamp`.
686    ///
687    /// ```
688    /// use jiff::fmt::temporal::DateTimeParser;
689    ///
690    /// static PARSER: DateTimeParser = DateTimeParser::new();
691    ///
692    /// let timestamp = PARSER.parse_timestamp("2024-03-10T02:05-04")?;
693    /// assert_eq!(timestamp.to_string(), "2024-03-10T06:05:00Z");
694    ///
695    /// # Ok::<(), Box<dyn std::error::Error>>(())
696    /// ```
697    ///
698    /// # Example: parsing a timestamp from a datetime with a time zone
699    ///
700    /// A timestamp can also be parsed from a time zone aware datetime string.
701    /// The time zone is ignored and the offset is always used.
702    ///
703    /// ```
704    /// use jiff::fmt::temporal::DateTimeParser;
705    ///
706    /// static PARSER: DateTimeParser = DateTimeParser::new();
707    ///
708    /// let timestamp = PARSER.parse_timestamp(
709    ///     "2024-03-10T02:05-04[America/New_York]",
710    /// )?;
711    /// assert_eq!(timestamp.to_string(), "2024-03-10T06:05:00Z");
712    ///
713    /// # Ok::<(), Box<dyn std::error::Error>>(())
714    /// ```
715    pub fn parse_timestamp<I: AsRef<[u8]>>(
716        &self,
717        input: I,
718    ) -> Result<Timestamp, Error> {
719        let input = input.as_ref();
720        let parsed = self.p.parse_temporal_datetime(input)?;
721        let dt = parsed.into_full()?;
722        let timestamp = dt.to_timestamp()?;
723        Ok(timestamp)
724    }
725
726    /// Parse a civil datetime string into a [`civil::DateTime`].
727    ///
728    /// A civil datetime can be parsed from anything that contains a datetime.
729    /// For example, a time zone aware string.
730    ///
731    /// # Errors
732    ///
733    /// This returns an error if the datetime string given is invalid or if it
734    /// is valid but doesn't fit in the datetime range supported by Jiff.
735    ///
736    /// This also returns an error if a `Z` (Zulu) offset is found, since
737    /// interpreting such strings as civil time is usually a bug.
738    ///
739    /// # Example
740    ///
741    /// This shows a basic example of parsing a `civil::DateTime`.
742    ///
743    /// ```
744    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
745    ///
746    /// static PARSER: DateTimeParser = DateTimeParser::new();
747    ///
748    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05")?;
749    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
750    ///
751    /// # Ok::<(), Box<dyn std::error::Error>>(())
752    /// ```
753    ///
754    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
755    ///
756    /// Because parsing a datetime with a `Z` offset and interpreting it as
757    /// a civil time is usually a bug, it is forbidden:
758    ///
759    /// ```
760    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
761    ///
762    /// static PARSER: DateTimeParser = DateTimeParser::new();
763    ///
764    /// assert!(PARSER.parse_datetime("2024-03-10T02:05Z").is_err());
765    ///
766    /// // Note though that -00 and +00 offsets parse successfully.
767    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05+00")?;
768    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
769    /// let datetime = PARSER.parse_datetime("2024-03-10T02:05-00")?;
770    /// assert_eq!(datetime, date(2024, 3, 10).at(2, 5, 0, 0));
771    ///
772    /// # Ok::<(), Box<dyn std::error::Error>>(())
773    /// ```
774    pub fn parse_datetime<I: AsRef<[u8]>>(
775        &self,
776        input: I,
777    ) -> Result<civil::DateTime, Error> {
778        let input = input.as_ref();
779        let parsed = self.p.parse_temporal_datetime(input)?;
780        let dt = parsed.into_full()?;
781        let datetime = dt.to_datetime()?;
782        Ok(datetime)
783    }
784
785    /// Parse a civil date string into a [`civil::Date`].
786    ///
787    /// A civil date can be parsed from anything that contains a date. For
788    /// example, a time zone aware string.
789    ///
790    /// # Errors
791    ///
792    /// This returns an error if the date string given is invalid or if it
793    /// is valid but doesn't fit in the date range supported by Jiff.
794    ///
795    /// This also returns an error if a `Z` (Zulu) offset is found, since
796    /// interpreting such strings as civil date or time is usually a bug.
797    ///
798    /// # Example
799    ///
800    /// This shows a basic example of parsing a `civil::Date`.
801    ///
802    /// ```
803    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
804    ///
805    /// static PARSER: DateTimeParser = DateTimeParser::new();
806    ///
807    /// let d = PARSER.parse_date("2024-03-10")?;
808    /// assert_eq!(d, date(2024, 3, 10));
809    ///
810    /// # Ok::<(), Box<dyn std::error::Error>>(())
811    /// ```
812    ///
813    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
814    ///
815    /// Because parsing a date with a `Z` offset and interpreting it as
816    /// a civil date or time is usually a bug, it is forbidden:
817    ///
818    /// ```
819    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
820    ///
821    /// static PARSER: DateTimeParser = DateTimeParser::new();
822    ///
823    /// assert!(PARSER.parse_date("2024-03-10T00:00:00Z").is_err());
824    ///
825    /// // Note though that -00 and +00 offsets parse successfully.
826    /// let d = PARSER.parse_date("2024-03-10T00:00:00+00")?;
827    /// assert_eq!(d, date(2024, 3, 10));
828    /// let d = PARSER.parse_date("2024-03-10T00:00:00-00")?;
829    /// assert_eq!(d, date(2024, 3, 10));
830    ///
831    /// # Ok::<(), Box<dyn std::error::Error>>(())
832    /// ```
833    pub fn parse_date<I: AsRef<[u8]>>(
834        &self,
835        input: I,
836    ) -> Result<civil::Date, Error> {
837        let input = input.as_ref();
838        let parsed = self.p.parse_temporal_datetime(input)?;
839        let dt = parsed.into_full()?;
840        let date = dt.to_date()?;
841        Ok(date)
842    }
843
844    /// Parse a civil time string into a [`civil::Time`].
845    ///
846    /// A civil time can be parsed from anything that contains a time.
847    /// For example, a time zone aware string.
848    ///
849    /// # Errors
850    ///
851    /// This returns an error if the time string given is invalid or if it
852    /// is valid but doesn't fit in the time range supported by Jiff.
853    ///
854    /// This also returns an error if a `Z` (Zulu) offset is found, since
855    /// interpreting such strings as civil time is usually a bug.
856    ///
857    /// # Example
858    ///
859    /// This shows a basic example of parsing a `civil::Time`.
860    ///
861    /// ```
862    /// use jiff::{civil::time, fmt::temporal::DateTimeParser};
863    ///
864    /// static PARSER: DateTimeParser = DateTimeParser::new();
865    ///
866    /// let t = PARSER.parse_time("02:05")?;
867    /// assert_eq!(t, time(2, 5, 0, 0));
868    ///
869    /// # Ok::<(), Box<dyn std::error::Error>>(())
870    /// ```
871    ///
872    /// # Example: parsing fails if a `Z` (Zulu) offset is encountered
873    ///
874    /// Because parsing a time with a `Z` offset and interpreting it as
875    /// a civil time is usually a bug, it is forbidden:
876    ///
877    /// ```
878    /// use jiff::{civil::time, fmt::temporal::DateTimeParser};
879    ///
880    /// static PARSER: DateTimeParser = DateTimeParser::new();
881    ///
882    /// assert!(PARSER.parse_time("02:05Z").is_err());
883    ///
884    /// // Note though that -00 and +00 offsets parse successfully.
885    /// let t = PARSER.parse_time("02:05+00")?;
886    /// assert_eq!(t, time(2, 5, 0, 0));
887    /// let t = PARSER.parse_time("02:05-00")?;
888    /// assert_eq!(t, time(2, 5, 0, 0));
889    ///
890    /// # Ok::<(), Box<dyn std::error::Error>>(())
891    /// ```
892    pub fn parse_time<I: AsRef<[u8]>>(
893        &self,
894        input: I,
895    ) -> Result<civil::Time, Error> {
896        let input = input.as_ref();
897        let parsed = self.p.parse_temporal_time(input)?;
898        let parsed_time = parsed.into_full()?;
899        let time = parsed_time.to_time();
900        Ok(time)
901    }
902
903    /// Parses a string representing a time zone into a [`TimeZone`].
904    ///
905    /// This will parse one of three different categories of strings:
906    ///
907    /// 1. An IANA Time Zone Database identifier. For example,
908    /// `America/New_York` or `UTC`.
909    /// 2. A fixed offset. For example, `-05:00` or `-00:44:30`.
910    /// 3. A POSIX time zone string. For example, `EST5EDT,M3.2.0,M11.1.0`.
911    ///
912    /// # Example
913    ///
914    /// This shows a few examples of parsing different kinds of time zones:
915    ///
916    /// ```
917    /// use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZone}};
918    ///
919    /// static PARSER: DateTimeParser = DateTimeParser::new();
920    ///
921    /// assert_eq!(
922    ///     PARSER.parse_time_zone("-05:00")?,
923    ///     TimeZone::fixed(tz::offset(-5)),
924    /// );
925    /// assert_eq!(
926    ///     PARSER.parse_time_zone("+05:00:01")?,
927    ///     TimeZone::fixed(tz::Offset::from_seconds(5 * 60 * 60 + 1).unwrap()),
928    /// );
929    /// assert_eq!(
930    ///     PARSER.parse_time_zone("America/New_York")?,
931    ///     TimeZone::get("America/New_York")?,
932    /// );
933    /// assert_eq!(
934    ///     PARSER.parse_time_zone("Asia/Jerusalem")?,
935    ///     TimeZone::get("Asia/Jerusalem")?,
936    /// );
937    /// assert_eq!(
938    ///     PARSER.parse_time_zone("EST5EDT,M3.2.0,M11.1.0")?,
939    ///     TimeZone::posix("EST5EDT,M3.2.0,M11.1.0")?,
940    /// );
941    ///
942    /// // Some error cases!
943    /// assert!(PARSER.parse_time_zone("Z").is_err());
944    /// assert!(PARSER.parse_time_zone("05:00").is_err());
945    /// assert!(PARSER.parse_time_zone("+05:00:01.5").is_err());
946    /// assert!(PARSER.parse_time_zone("Does/Not/Exist").is_err());
947    ///
948    /// # Ok::<(), Box<dyn std::error::Error>>(())
949    /// ```
950    pub fn parse_time_zone<'i, I: AsRef<[u8]>>(
951        &self,
952        input: I,
953    ) -> Result<TimeZone, Error> {
954        self.parse_time_zone_with(crate::tz::db(), input)
955    }
956
957    /// Parses a string representing a time zone into a [`TimeZone`] and
958    /// performs any time zone database lookups using the [`TimeZoneDatabase`]
959    /// given.
960    ///
961    /// This is like [`DateTimeParser::parse_time_zone`], but uses the time
962    /// zone database given instead of the implicit global time zone database.
963    ///
964    /// This will parse one of three different categories of strings:
965    ///
966    /// 1. An IANA Time Zone Database identifier. For example,
967    /// `America/New_York` or `UTC`.
968    /// 2. A fixed offset. For example, `-05:00` or `-00:44:30`.
969    /// 3. A POSIX time zone string. For example, `EST5EDT,M3.2.0,M11.1.0`.
970    ///
971    /// # Example
972    ///
973    /// ```
974    /// use jiff::{fmt::temporal::DateTimeParser, tz::TimeZone};
975    ///
976    /// static PARSER: DateTimeParser = DateTimeParser::new();
977    ///
978    /// let db = jiff::tz::db();
979    /// assert_eq!(
980    ///     PARSER.parse_time_zone_with(db, "America/New_York")?,
981    ///     TimeZone::get("America/New_York")?,
982    /// );
983    ///
984    /// # Ok::<(), Box<dyn std::error::Error>>(())
985    /// ```
986    ///
987    /// See also the example for [`DateTimeParser::parse_zoned_datetime_with`]
988    /// for a more interesting example using a time zone database other than
989    /// the default.
990    pub fn parse_time_zone_with<'i, I: AsRef<[u8]>>(
991        &self,
992        db: &TimeZoneDatabase,
993        input: I,
994    ) -> Result<TimeZone, Error> {
995        let input = input.as_ref();
996        let parsed = self.p.parse_time_zone(input)?.into_full()?;
997        parsed.into_time_zone(db)
998    }
999
1000    /// Parse a Temporal datetime string into [`Pieces`].
1001    ///
1002    /// This is a lower level routine meant to give callers raw access to the
1003    /// individual "pieces" of a parsed Temporal ISO 8601 datetime string.
1004    /// Note that this only includes strings that have a date component.
1005    ///
1006    /// The benefit of this routine is that it only checks that the datetime is
1007    /// itself valid. It doesn't do any automatic diambiguation, offset
1008    /// conflict resolution or attempt to prevent you from shooting yourself in
1009    /// the foot. For example, this routine will let you parse a fixed offset
1010    /// datetime into a `ZonedDateTime` without a time zone abbreviation.
1011    ///
1012    /// Note that when using this routine, the
1013    /// [`DateTimeParser::offset_conflict`] and
1014    /// [`DateTimeParser::disambiguation`] configuration knobs are completely
1015    /// ignored. This is because with the lower level `Pieces`, callers must
1016    /// handle offset conflict resolution (if they want it) themselves. See
1017    /// the [`Pieces`] documentation for a case study on how to do this if
1018    /// you need it.
1019    ///
1020    /// # Errors
1021    ///
1022    /// This returns an error if the datetime string given is invalid or if it
1023    /// is valid but doesn't fit in the date range supported by Jiff.
1024    ///
1025    /// # Example
1026    ///
1027    /// This shows how to parse a fixed offset timestamp into a
1028    /// `ZonedDateTime`.
1029    ///
1030    /// ```
1031    /// use jiff::{fmt::temporal::DateTimeParser, tz::TimeZone};
1032    ///
1033    /// static PARSER: DateTimeParser = DateTimeParser::new();
1034    ///
1035    /// let timestamp = "2025-01-02T15:13-05";
1036    ///
1037    /// // Normally this operation will fail.
1038    /// assert_eq!(
1039    ///     PARSER.parse_zoned_datetime(timestamp).unwrap_err().to_string(),
1040    ///     "failed to find time zone annotation in square brackets, \
1041    ///      which is required for parsing a zoned datetime",
1042    /// );
1043    ///
1044    /// // But you can work-around this with `Pieces`, which gives you direct
1045    /// // access to the components parsed from the string.
1046    /// let pieces = PARSER.parse_pieces(timestamp)?;
1047    /// let time = pieces.time().unwrap_or_else(jiff::civil::Time::midnight);
1048    /// let dt = pieces.date().to_datetime(time);
1049    /// let tz = match pieces.to_time_zone()? {
1050    ///     Some(tz) => tz,
1051    ///     None => {
1052    ///         let Some(offset) = pieces.to_numeric_offset() else {
1053    ///             let msg = format!(
1054    ///                 "timestamp `{timestamp}` has no time zone \
1055    ///                  or offset, and thus cannot be parsed into \
1056    ///                  an instant",
1057    ///             );
1058    ///             return Err(msg.into());
1059    ///         };
1060    ///         TimeZone::fixed(offset)
1061    ///     }
1062    /// };
1063    /// // We don't bother with offset conflict resolution. And note that
1064    /// // this uses automatic "compatible" disambiguation in the case of
1065    /// // discontinuities. Of course, this is all moot if `TimeZone` is
1066    /// // fixed. The above code handles the case where it isn't!
1067    /// let zdt = tz.to_zoned_datetime(dt)?;
1068    /// assert_eq!(zdt.to_string(), "2025-01-02T15:13:00-05:00[-05:00]");
1069    ///
1070    /// # Ok::<(), Box<dyn std::error::Error>>(())
1071    /// ```
1072    ///
1073    /// # Example: work around errors when a `Z` (Zulu) offset is encountered
1074    ///
1075    /// Because parsing a date with a `Z` offset and interpreting it as
1076    /// a civil date or time is usually a bug, it is forbidden:
1077    ///
1078    /// ```
1079    /// use jiff::{civil::date, fmt::temporal::DateTimeParser};
1080    ///
1081    /// static PARSER: DateTimeParser = DateTimeParser::new();
1082    ///
1083    /// assert_eq!(
1084    ///     PARSER.parse_date("2024-03-10T00:00:00Z").unwrap_err().to_string(),
1085    ///     "cannot parse civil date/time from string with a Zulu offset, \
1086    ///      parse as a `jiff::Timestamp` first and convert to a civil date/time instead",
1087    /// );
1088    ///
1089    /// # Ok::<(), Box<dyn std::error::Error>>(())
1090    /// ```
1091    ///
1092    /// But this sort of error checking doesn't happen when you parse into a
1093    /// [`Pieces`]. You just get what was parsed, which lets you extract a
1094    /// date even if the higher level APIs forbid it:
1095    ///
1096    /// ```
1097    /// use jiff::{civil, fmt::temporal::DateTimeParser, tz::Offset};
1098    ///
1099    /// static PARSER: DateTimeParser = DateTimeParser::new();
1100    ///
1101    /// let pieces = PARSER.parse_pieces("2024-03-10T00:00:00Z")?;
1102    /// assert_eq!(pieces.date(), civil::date(2024, 3, 10));
1103    /// assert_eq!(pieces.time(), Some(civil::time(0, 0, 0, 0)));
1104    /// assert_eq!(pieces.to_numeric_offset(), Some(Offset::UTC));
1105    /// assert_eq!(pieces.to_time_zone()?, None);
1106    ///
1107    /// # Ok::<(), Box<dyn std::error::Error>>(())
1108    /// ```
1109    ///
1110    /// This is usually not the right thing to do. It isn't even suggested in
1111    /// the error message above. But if you know it's the right thing, then
1112    /// `Pieces` will let you do it.
1113    pub fn parse_pieces<'i, I: ?Sized + AsRef<[u8]> + 'i>(
1114        &self,
1115        input: &'i I,
1116    ) -> Result<Pieces<'i>, Error> {
1117        let input = input.as_ref();
1118        let parsed = self.p.parse_temporal_datetime(input)?.into_full()?;
1119        let pieces = parsed.to_pieces()?;
1120        Ok(pieces)
1121    }
1122
1123    /// Parses an ISO 8601 week date.
1124    ///
1125    /// This isn't exported because it's not clear that it's worth it.
1126    /// Moreover, this isn't part of the Temporal spec, so it's a little odd
1127    /// to have it here. If this really needs to be exported, we probably need
1128    /// a new module that wraps and re-uses this module's internal parser to
1129    /// avoid too much code duplication.
1130    pub(crate) fn parse_iso_week_date<I: AsRef<[u8]>>(
1131        &self,
1132        input: I,
1133    ) -> Result<ISOWeekDate, Error> {
1134        let input = input.as_ref();
1135        let wd = self.p.parse_iso_week_date(input)?.into_full()?;
1136        Ok(wd)
1137    }
1138}
1139
1140/// A printer for Temporal datetimes.
1141///
1142/// This printer converts an in memory representation of a datetime related
1143/// type to a machine (but also human) readable format. Using this printer, one
1144/// can convert [`ZonedDateTime`], [`Timestamp`], [`civil::DateTime`],
1145/// [`civil::Date`] or [`civil::Time`] values to a string. Note that all of
1146/// those types provide [`Display`](core::fmt::Display) implementations that
1147/// utilize the default configuration of this printer. However, this printer
1148/// can be configured to behave differently and can also print directly to
1149/// anything that implements the [`fmt::Write`](Write) trait.
1150///
1151/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
1152/// more information on the specific format used. Note that the Temporal
1153/// datetime parser is strictly more flexible than what is supported by this
1154/// printer. For example, parsing `2024-06-15T07:00-04[America/New_York]` will
1155/// work just fine, even though the seconds are omitted. However, this printer
1156/// provides no way to write a datetime without the second component.
1157///
1158/// # Example
1159///
1160/// This example shows how to print a `ZonedDateTime` value with a space
1161/// separating the date and time instead of the more standard `T` separator.
1162///
1163/// ```
1164/// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1165///
1166/// // A printer can be created in a const context.
1167/// const PRINTER: DateTimePrinter = DateTimePrinter::new().separator(b' ');
1168///
1169/// let zdt = date(2024, 6, 15).at(7, 0, 0, 123456789).in_tz("America/New_York")?;
1170///
1171/// let mut buf = String::new();
1172/// // Printing to a `String` can never fail.
1173/// PRINTER.print_zoned_datetime(&zdt, &mut buf).unwrap();
1174/// assert_eq!(buf, "2024-06-15 07:00:00.123456789-04:00[America/New_York]");
1175///
1176/// # Ok::<(), Box<dyn std::error::Error>>(())
1177/// ```
1178///
1179/// # Example: using adapters with `std::io::Write` and `std::fmt::Write`
1180///
1181/// By using the [`StdIoWrite`](super::StdIoWrite) and
1182/// [`StdFmtWrite`](super::StdFmtWrite) adapters, one can print datetimes
1183/// directly to implementations of `std::io::Write` and `std::fmt::Write`,
1184/// respectively. The example below demonstrates writing to anything
1185/// that implements `std::io::Write`. Similar code can be written for
1186/// `std::fmt::Write`.
1187///
1188/// ```no_run
1189/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
1190///
1191/// use jiff::{civil::date, fmt::{StdIoWrite, temporal::DateTimePrinter}};
1192///
1193/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1194///
1195/// let path = Path::new("/tmp/output");
1196/// let mut file = BufWriter::new(File::create(path)?);
1197/// DateTimePrinter::new()
1198///     .print_zoned_datetime(&zdt, StdIoWrite(&mut file))
1199///     .unwrap();
1200/// file.flush()?;
1201/// assert_eq!(
1202///     std::fs::read_to_string(path)?,
1203///     "2024-06-15T07:00:00-04:00[America/New_York]",
1204/// );
1205///
1206/// # Ok::<(), Box<dyn std::error::Error>>(())
1207/// ```
1208#[derive(#[automatically_derived]impl ::core::fmt::Debug for DateTimePrinter {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DateTimePrinter p", &&self.p)
    }
}Debug)]
1209pub struct DateTimePrinter {
1210    p: printer::DateTimePrinter,
1211}
1212
1213impl DateTimePrinter {
1214    /// Create a new Temporal datetime printer with the default configuration.
1215    pub const fn new() -> DateTimePrinter {
1216        DateTimePrinter { p: printer::DateTimePrinter::new() }
1217    }
1218
1219    /// Use lowercase for the datetime separator and the `Z` (Zulu) UTC offset.
1220    ///
1221    /// This is disabled by default.
1222    ///
1223    /// # Example
1224    ///
1225    /// This example shows how to print a `ZonedDateTime` value with a
1226    /// lowercase datetime separator.
1227    ///
1228    /// ```
1229    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1230    ///
1231    /// const PRINTER: DateTimePrinter = DateTimePrinter::new().lowercase(true);
1232    ///
1233    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1234    ///
1235    /// let mut buf = String::new();
1236    /// // Printing to a `String` can never fail.
1237    /// PRINTER.print_zoned_datetime(&zdt, &mut buf).unwrap();
1238    /// assert_eq!(buf, "2024-06-15t07:00:00-04:00[America/New_York]");
1239    ///
1240    /// # Ok::<(), Box<dyn std::error::Error>>(())
1241    /// ```
1242    #[inline]
1243    pub const fn lowercase(mut self, yes: bool) -> DateTimePrinter {
1244        self.p = self.p.lowercase(yes);
1245        self
1246    }
1247
1248    /// Use the given ASCII character to separate the date and time when
1249    /// printing [`ZonedDateTime`], [`Timestamp`] or [`civil::DateTime`]
1250    /// values.
1251    ///
1252    /// This is set to `T` by default.
1253    ///
1254    /// # Example
1255    ///
1256    /// This example shows how to print a `ZonedDateTime` value with a
1257    /// different datetime separator.
1258    ///
1259    /// ```
1260    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1261    ///
1262    /// // We use a weird non-standard character here, but typically one would
1263    /// // use this method with an ASCII space.
1264    /// const PRINTER: DateTimePrinter = DateTimePrinter::new().separator(b'~');
1265    ///
1266    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1267    ///
1268    /// let mut buf = String::new();
1269    /// // Printing to a `String` can never fail.
1270    /// PRINTER.print_zoned_datetime(&zdt, &mut buf).unwrap();
1271    /// assert_eq!(buf, "2024-06-15~07:00:00-04:00[America/New_York]");
1272    ///
1273    /// # Ok::<(), Box<dyn std::error::Error>>(())
1274    /// ```
1275    #[inline]
1276    pub const fn separator(mut self, ascii_char: u8) -> DateTimePrinter {
1277        self.p = self.p.separator(ascii_char);
1278        self
1279    }
1280
1281    /// Set the precision to use for formatting the fractional second component
1282    /// of a time.
1283    ///
1284    /// The default is `None`, which will automatically set the precision based
1285    /// on the value.
1286    ///
1287    /// When the precision is set to `N`, you'll always get precisely `N`
1288    /// digits after a decimal point (unless `N==0`, then no fractional
1289    /// component is printed), even if they are `0`.
1290    ///
1291    /// # Example
1292    ///
1293    /// ```
1294    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1295    ///
1296    /// const PRINTER: DateTimePrinter =
1297    ///     DateTimePrinter::new().precision(Some(3));
1298    ///
1299    /// let zdt = date(2024, 6, 15)
1300    ///     .at(7, 0, 0, 123_456_789)
1301    ///     .in_tz("America/New_York")?;
1302    ///
1303    /// let mut buf = String::new();
1304    /// // Printing to a `String` can never fail.
1305    /// PRINTER.print_zoned_datetime(&zdt, &mut buf).unwrap();
1306    /// assert_eq!(buf, "2024-06-15T07:00:00.123-04:00[America/New_York]");
1307    ///
1308    /// # Ok::<(), Box<dyn std::error::Error>>(())
1309    /// ```
1310    ///
1311    /// # Example: available via formatting machinery
1312    ///
1313    /// When formatting datetime types that may contain a fractional second
1314    /// component, this can be set via Rust's formatting DSL. Specifically,
1315    /// it corresponds to the [`std::fmt::Formatter::precision`] setting.
1316    ///
1317    /// ```
1318    /// use jiff::civil::date;
1319    ///
1320    /// let zdt = date(2024, 6, 15)
1321    ///     .at(7, 0, 0, 123_000_000)
1322    ///     .in_tz("America/New_York")?;
1323    /// assert_eq!(
1324    ///     format!("{zdt:.6}"),
1325    ///     "2024-06-15T07:00:00.123000-04:00[America/New_York]",
1326    /// );
1327    /// // Precision values greater than 9 are clamped to 9.
1328    /// assert_eq!(
1329    ///     format!("{zdt:.300}"),
1330    ///     "2024-06-15T07:00:00.123000000-04:00[America/New_York]",
1331    /// );
1332    /// // A precision of 0 implies the entire fractional
1333    /// // component is always truncated.
1334    /// assert_eq!(
1335    ///     format!("{zdt:.0}"),
1336    ///     "2024-06-15T07:00:00-04:00[America/New_York]",
1337    /// );
1338    ///
1339    /// # Ok::<(), Box<dyn std::error::Error>>(())
1340    /// ```
1341    #[inline]
1342    pub const fn precision(
1343        mut self,
1344        precision: Option<u8>,
1345    ) -> DateTimePrinter {
1346        self.p = self.p.precision(precision);
1347        self
1348    }
1349
1350    /// Format a `ZonedDateTime` datetime into a string.
1351    ///
1352    /// This is a convenience routine for
1353    /// [`DateTimePrinter::print_zoned_datetime`] with a `String`.
1354    ///
1355    /// # Example
1356    ///
1357    /// ```
1358    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1359    ///
1360    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1361    ///
1362    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1363    /// assert_eq!(
1364    ///     PRINTER.zoned_datetime_to_string(&zdt),
1365    ///     "2024-06-15T07:00:00-04:00[America/New_York]",
1366    /// );
1367    ///
1368    /// # Ok::<(), Box<dyn std::error::Error>>(())
1369    /// ```
1370    #[cfg(feature = "alloc")]
1371    pub fn zoned_datetime_to_string(
1372        &self,
1373        zdt: &ZonedDateTime,
1374    ) -> alloc::string::String {
1375        let mut buf = alloc::string::String::new();
1376        // OK because writing to `String` never fails.
1377        self.print_zoned_datetime(zdt, &mut buf).unwrap();
1378        buf
1379    }
1380
1381    /// Format a `Timestamp` datetime into a string.
1382    ///
1383    /// This will always return an RFC 3339 compatible string with a `Z` or
1384    /// Zulu offset. Zulu is chosen in accordance with RFC 9557's update to
1385    /// RFC 3339 that establishes the `-00:00` offset as equivalent to Zulu:
1386    ///
1387    /// > If the time in UTC is known, but the offset to local time is
1388    /// > unknown, this can be represented with an offset of "Z".  (The
1389    /// > original version of this specification provided -00:00 for this
1390    /// > purpose, which is not allowed by ISO8601:2000 and therefore is
1391    /// > less interoperable; Section 3.3 of RFC5322 describes a related
1392    /// > convention for email, which does not have this problem).  This
1393    /// > differs semantically from an offset of +00:00, which implies that
1394    /// > UTC is the preferred reference point for the specified time.
1395    ///
1396    /// In other words, both Zulu time and `-00:00` mean "the time in UTC is
1397    /// known, but the offset to local time is unknown."
1398    ///
1399    /// If you need to format an RFC 3339 timestamp with a specific offset,
1400    /// use [`DateTimePrinter::timestamp_with_offset_to_string`].
1401    ///
1402    /// This is a convenience routine for [`DateTimePrinter::print_timestamp`]
1403    /// with a `String`.
1404    ///
1405    /// # Example
1406    ///
1407    /// ```
1408    /// use jiff::{fmt::temporal::DateTimePrinter, Timestamp};
1409    ///
1410    /// let timestamp = Timestamp::new(0, 1)
1411    ///     .expect("one nanosecond after Unix epoch is always valid");
1412    /// assert_eq!(
1413    ///     DateTimePrinter::new().timestamp_to_string(&timestamp),
1414    ///     "1970-01-01T00:00:00.000000001Z",
1415    /// );
1416    /// ```
1417    #[cfg(feature = "alloc")]
1418    pub fn timestamp_to_string(
1419        &self,
1420        timestamp: &Timestamp,
1421    ) -> alloc::string::String {
1422        let mut buf = alloc::string::String::new();
1423        // OK because writing to `String` never fails.
1424        self.print_timestamp(timestamp, &mut buf).unwrap();
1425        buf
1426    }
1427
1428    /// Format a `Timestamp` datetime into a string with the given offset.
1429    ///
1430    /// This will always return an RFC 3339 compatible string with an offset.
1431    ///
1432    /// This will never use either `Z` (for Zulu time) or `-00:00` as an
1433    /// offset. This is because Zulu time (and `-00:00`) mean "the time in UTC
1434    /// is known, but the offset to local time is unknown." Since this routine
1435    /// accepts an explicit offset, the offset is known. For example,
1436    /// `Offset::UTC` will be formatted as `+00:00`.
1437    ///
1438    /// To format an RFC 3339 string in Zulu time, use
1439    /// [`DateTimePrinter::timestamp_to_string`].
1440    ///
1441    /// This is a convenience routine for
1442    /// [`DateTimePrinter::print_timestamp_with_offset`] with a `String`.
1443    ///
1444    /// # Example
1445    ///
1446    /// ```
1447    /// use jiff::{fmt::temporal::DateTimePrinter, tz, Timestamp};
1448    ///
1449    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1450    ///
1451    /// let timestamp = Timestamp::new(0, 1)
1452    ///     .expect("one nanosecond after Unix epoch is always valid");
1453    /// assert_eq!(
1454    ///     PRINTER.timestamp_with_offset_to_string(&timestamp, tz::offset(-5)),
1455    ///     "1969-12-31T19:00:00.000000001-05:00",
1456    /// );
1457    /// ```
1458    ///
1459    /// # Example: `Offset::UTC` formats as `+00:00`
1460    ///
1461    /// ```
1462    /// use jiff::{fmt::temporal::DateTimePrinter, tz::Offset, Timestamp};
1463    ///
1464    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1465    ///
1466    /// let timestamp = Timestamp::new(0, 1)
1467    ///     .expect("one nanosecond after Unix epoch is always valid");
1468    /// assert_eq!(
1469    ///     PRINTER.timestamp_with_offset_to_string(&timestamp, Offset::UTC),
1470    ///     "1970-01-01T00:00:00.000000001+00:00",
1471    /// );
1472    /// ```
1473    #[cfg(feature = "alloc")]
1474    pub fn timestamp_with_offset_to_string(
1475        &self,
1476        timestamp: &Timestamp,
1477        offset: Offset,
1478    ) -> alloc::string::String {
1479        let mut buf = alloc::string::String::new();
1480        // OK because writing to `String` never fails.
1481        self.print_timestamp_with_offset(timestamp, offset, &mut buf).unwrap();
1482        buf
1483    }
1484
1485    /// Format a `civil::DateTime` into a string.
1486    ///
1487    /// This is a convenience routine for [`DateTimePrinter::print_datetime`]
1488    /// with a `String`.
1489    ///
1490    /// # Example
1491    ///
1492    /// ```
1493    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1494    ///
1495    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1496    ///
1497    /// let dt = date(2024, 6, 15).at(7, 0, 0, 0);
1498    /// assert_eq!(PRINTER.datetime_to_string(&dt), "2024-06-15T07:00:00");
1499    /// ```
1500    #[cfg(feature = "alloc")]
1501    pub fn datetime_to_string(
1502        &self,
1503        dt: &civil::DateTime,
1504    ) -> alloc::string::String {
1505        let mut buf = alloc::string::String::new();
1506        // OK because writing to `String` never fails.
1507        self.print_datetime(dt, &mut buf).unwrap();
1508        buf
1509    }
1510
1511    /// Format a `civil::Date` into a string.
1512    ///
1513    /// This is a convenience routine for [`DateTimePrinter::print_date`]
1514    /// with a `String`.
1515    ///
1516    /// # Example
1517    ///
1518    /// ```
1519    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1520    ///
1521    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1522    ///
1523    /// let d = date(2024, 6, 15);
1524    /// assert_eq!(PRINTER.date_to_string(&d), "2024-06-15");
1525    /// ```
1526    #[cfg(feature = "alloc")]
1527    pub fn date_to_string(&self, date: &civil::Date) -> alloc::string::String {
1528        let mut buf = alloc::string::String::new();
1529        // OK because writing to `String` never fails.
1530        self.print_date(date, &mut buf).unwrap();
1531        buf
1532    }
1533
1534    /// Format a `civil::Time` into a string.
1535    ///
1536    /// This is a convenience routine for [`DateTimePrinter::print_time`]
1537    /// with a `String`.
1538    ///
1539    /// # Example
1540    ///
1541    /// ```
1542    /// use jiff::{civil::time, fmt::temporal::DateTimePrinter};
1543    ///
1544    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1545    ///
1546    /// let t = time(7, 0, 0, 0);
1547    /// assert_eq!(PRINTER.time_to_string(&t), "07:00:00");
1548    /// ```
1549    #[cfg(feature = "alloc")]
1550    pub fn time_to_string(&self, time: &civil::Time) -> alloc::string::String {
1551        let mut buf = alloc::string::String::new();
1552        // OK because writing to `String` never fails.
1553        self.print_time(time, &mut buf).unwrap();
1554        buf
1555    }
1556
1557    /// Format a `TimeZone` into a string.
1558    ///
1559    /// This is a convenience routine for [`DateTimePrinter::print_time_zone`].
1560    ///
1561    /// # Errors
1562    ///
1563    /// In some rare cases, serialization may fail when there is no succinct
1564    /// representation of a time zone. One specific case in which this
1565    /// occurs is when `TimeZone` is a user's system time zone derived from
1566    /// `/etc/localtime`, but where an IANA time zone identifier could not
1567    /// be found. This can occur, for example, when `/etc/localtime` is not
1568    /// symlinked to an entry in `/usr/share/zoneinfo`.
1569    ///
1570    /// # Example
1571    ///
1572    /// ```
1573    /// use jiff::{fmt::temporal::DateTimePrinter, tz::TimeZone};
1574    ///
1575    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1576    ///
1577    /// // IANA time zone
1578    /// let tz = TimeZone::get("America/New_York")?;
1579    /// assert_eq!(PRINTER.time_zone_to_string(&tz)?, "America/New_York");
1580    ///
1581    /// # Ok::<(), Box<dyn std::error::Error>>(())
1582    /// ```
1583    #[cfg(feature = "alloc")]
1584    pub fn time_zone_to_string(
1585        &self,
1586        tz: &TimeZone,
1587    ) -> Result<alloc::string::String, Error> {
1588        let mut buf = alloc::string::String::new();
1589        // Writing to a `String` itself will never fail, but this could fail
1590        // as described above in the docs.
1591        self.print_time_zone(tz, &mut buf)?;
1592        Ok(buf)
1593    }
1594
1595    /// Format `Pieces` of a Temporal datetime.
1596    ///
1597    /// This is a convenience routine for [`DateTimePrinter::print_pieces`]
1598    /// with a `String`.
1599    ///
1600    /// # Example
1601    ///
1602    /// ```
1603    /// use jiff::{
1604    ///     fmt::temporal::{DateTimePrinter, Pieces},
1605    ///     tz::offset,
1606    ///     Timestamp,
1607    /// };
1608    ///
1609    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1610    ///
1611    /// let pieces = Pieces::from(Timestamp::UNIX_EPOCH);
1612    /// assert_eq!(
1613    ///     PRINTER.pieces_to_string(&pieces),
1614    ///     "1970-01-01T00:00:00Z",
1615    /// );
1616    ///
1617    /// let pieces = Pieces::from((Timestamp::UNIX_EPOCH, offset(0)));
1618    /// assert_eq!(
1619    ///     PRINTER.pieces_to_string(&pieces),
1620    ///     "1970-01-01T00:00:00+00:00",
1621    /// );
1622    ///
1623    /// let pieces = Pieces::from((Timestamp::UNIX_EPOCH, offset(-5)));
1624    /// assert_eq!(
1625    ///     PRINTER.pieces_to_string(&pieces),
1626    ///     "1969-12-31T19:00:00-05:00",
1627    /// );
1628    ///
1629    /// # Ok::<(), Box<dyn std::error::Error>>(())
1630    /// ```
1631    #[cfg(feature = "alloc")]
1632    pub fn pieces_to_string(&self, pieces: &Pieces) -> alloc::string::String {
1633        let mut buf = alloc::string::String::new();
1634        // OK because writing to `String` never fails.
1635        self.print_pieces(pieces, &mut buf).unwrap();
1636        buf
1637    }
1638
1639    /// Print a `ZonedDateTime` datetime to the given writer.
1640    ///
1641    /// # Errors
1642    ///
1643    /// This only returns an error when writing to the given [`Write`]
1644    /// implementation would fail. Some such implementations, like for `String`
1645    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1646    /// cases, it would be appropriate to call `unwrap()` on the result.
1647    ///
1648    /// # Example
1649    ///
1650    /// ```
1651    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1652    ///
1653    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1654    ///
1655    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1656    ///
1657    /// let mut buf = String::new();
1658    /// // Printing to a `String` can never fail.
1659    /// PRINTER.print_zoned_datetime(&zdt, &mut buf).unwrap();
1660    /// assert_eq!(buf, "2024-06-15T07:00:00-04:00[America/New_York]");
1661    ///
1662    /// # Ok::<(), Box<dyn std::error::Error>>(())
1663    /// ```
1664    pub fn print_zoned_datetime<W: Write>(
1665        &self,
1666        zdt: &ZonedDateTime,
1667        mut wtr: W,
1668    ) -> Result<(), Error> {
1669        self.p.print_zoned_datetime(zdt, &mut wtr)
1670    }
1671
1672    /// Print a `Timestamp` datetime to the given writer.
1673    ///
1674    /// This will always write an RFC 3339 compatible string with a `Z` or
1675    /// Zulu offset. Zulu is chosen in accordance with RFC 9557's update to
1676    /// RFC 3339 that establishes the `-00:00` offset as equivalent to Zulu:
1677    ///
1678    /// > If the time in UTC is known, but the offset to local time is
1679    /// > unknown, this can be represented with an offset of "Z".  (The
1680    /// > original version of this specification provided -00:00 for this
1681    /// > purpose, which is not allowed by ISO8601:2000 and therefore is
1682    /// > less interoperable; Section 3.3 of RFC5322 describes a related
1683    /// > convention for email, which does not have this problem).  This
1684    /// > differs semantically from an offset of +00:00, which implies that
1685    /// > UTC is the preferred reference point for the specified time.
1686    ///
1687    /// In other words, both Zulu time and `-00:00` mean "the time in UTC is
1688    /// known, but the offset to local time is unknown."
1689    ///
1690    /// If you need to write an RFC 3339 timestamp with a specific offset,
1691    /// use [`DateTimePrinter::print_timestamp_with_offset`].
1692    ///
1693    /// # Errors
1694    ///
1695    /// This only returns an error when writing to the given [`Write`]
1696    /// implementation would fail. Some such implementations, like for `String`
1697    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1698    /// cases, it would be appropriate to call `unwrap()` on the result.
1699    ///
1700    /// # Example
1701    ///
1702    /// ```
1703    /// use jiff::{fmt::temporal::DateTimePrinter, Timestamp};
1704    ///
1705    /// let timestamp = Timestamp::new(0, 1)
1706    ///     .expect("one nanosecond after Unix epoch is always valid");
1707    ///
1708    /// let mut buf = String::new();
1709    /// // Printing to a `String` can never fail.
1710    /// DateTimePrinter::new().print_timestamp(&timestamp, &mut buf).unwrap();
1711    /// assert_eq!(buf, "1970-01-01T00:00:00.000000001Z");
1712    ///
1713    /// # Ok::<(), Box<dyn std::error::Error>>(())
1714    /// ```
1715    pub fn print_timestamp<W: Write>(
1716        &self,
1717        timestamp: &Timestamp,
1718        mut wtr: W,
1719    ) -> Result<(), Error> {
1720        self.p.print_timestamp(timestamp, &mut wtr)
1721    }
1722
1723    /// Print a `Timestamp` datetime to the given writer with the given offset.
1724    ///
1725    /// This will always write an RFC 3339 compatible string with an offset.
1726    ///
1727    /// This will never write either `Z` (for Zulu time) or `-00:00` as an
1728    /// offset. This is because Zulu time (and `-00:00`) mean "the time in UTC
1729    /// is known, but the offset to local time is unknown." Since this routine
1730    /// accepts an explicit offset, the offset is known. For example,
1731    /// `Offset::UTC` will be formatted as `+00:00`.
1732    ///
1733    /// To write an RFC 3339 string in Zulu time, use
1734    /// [`DateTimePrinter::print_timestamp`].
1735    ///
1736    /// # Errors
1737    ///
1738    /// This only returns an error when writing to the given [`Write`]
1739    /// implementation would fail. Some such implementations, like for `String`
1740    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1741    /// cases, it would be appropriate to call `unwrap()` on the result.
1742    ///
1743    /// # Example
1744    ///
1745    /// ```
1746    /// use jiff::{fmt::temporal::DateTimePrinter, tz, Timestamp};
1747    ///
1748    /// let timestamp = Timestamp::new(0, 1)
1749    ///     .expect("one nanosecond after Unix epoch is always valid");
1750    ///
1751    /// let mut buf = String::new();
1752    /// // Printing to a `String` can never fail.
1753    /// DateTimePrinter::new().print_timestamp_with_offset(
1754    ///     &timestamp,
1755    ///     tz::offset(-5),
1756    ///     &mut buf,
1757    /// ).unwrap();
1758    /// assert_eq!(buf, "1969-12-31T19:00:00.000000001-05:00");
1759    ///
1760    /// # Ok::<(), Box<dyn std::error::Error>>(())
1761    /// ```
1762    ///
1763    /// # Example: `Offset::UTC` formats as `+00:00`
1764    ///
1765    /// ```
1766    /// use jiff::{fmt::temporal::DateTimePrinter, tz::Offset, Timestamp};
1767    ///
1768    /// let timestamp = Timestamp::new(0, 1)
1769    ///     .expect("one nanosecond after Unix epoch is always valid");
1770    ///
1771    /// let mut buf = String::new();
1772    /// // Printing to a `String` can never fail.
1773    /// DateTimePrinter::new().print_timestamp_with_offset(
1774    ///     &timestamp,
1775    ///     Offset::UTC, // equivalent to `Offset::from_hours(0)`
1776    ///     &mut buf,
1777    /// ).unwrap();
1778    /// assert_eq!(buf, "1970-01-01T00:00:00.000000001+00:00");
1779    ///
1780    /// # Ok::<(), Box<dyn std::error::Error>>(())
1781    /// ```
1782    pub fn print_timestamp_with_offset<W: Write>(
1783        &self,
1784        timestamp: &Timestamp,
1785        offset: Offset,
1786        mut wtr: W,
1787    ) -> Result<(), Error> {
1788        self.p.print_timestamp_with_offset(timestamp, offset, &mut wtr)
1789    }
1790
1791    /// Print a `civil::DateTime` to the given writer.
1792    ///
1793    /// # Errors
1794    ///
1795    /// This only returns an error when writing to the given [`Write`]
1796    /// implementation would fail. Some such implementations, like for `String`
1797    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1798    /// cases, it would be appropriate to call `unwrap()` on the result.
1799    ///
1800    /// # Example
1801    ///
1802    /// ```
1803    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1804    ///
1805    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1806    ///
1807    /// let d = date(2024, 6, 15).at(7, 0, 0, 0);
1808    ///
1809    /// let mut buf = String::new();
1810    /// // Printing to a `String` can never fail.
1811    /// PRINTER.print_datetime(&d, &mut buf).unwrap();
1812    /// assert_eq!(buf, "2024-06-15T07:00:00");
1813    ///
1814    /// # Ok::<(), Box<dyn std::error::Error>>(())
1815    /// ```
1816    pub fn print_datetime<W: Write>(
1817        &self,
1818        dt: &civil::DateTime,
1819        mut wtr: W,
1820    ) -> Result<(), Error> {
1821        self.p.print_datetime(dt, &mut wtr)
1822    }
1823
1824    /// Print a `civil::Date` to the given writer.
1825    ///
1826    /// # Errors
1827    ///
1828    /// This only returns an error when writing to the given [`Write`]
1829    /// implementation would fail. Some such implementations, like for `String`
1830    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1831    /// cases, it would be appropriate to call `unwrap()` on the result.
1832    ///
1833    /// # Example
1834    ///
1835    /// ```
1836    /// use jiff::{civil::date, fmt::temporal::DateTimePrinter};
1837    ///
1838    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1839    ///
1840    /// let d = date(2024, 6, 15);
1841    ///
1842    /// let mut buf = String::new();
1843    /// // Printing to a `String` can never fail.
1844    /// PRINTER.print_date(&d, &mut buf).unwrap();
1845    /// assert_eq!(buf, "2024-06-15");
1846    ///
1847    /// # Ok::<(), Box<dyn std::error::Error>>(())
1848    /// ```
1849    pub fn print_date<W: Write>(
1850        &self,
1851        date: &civil::Date,
1852        mut wtr: W,
1853    ) -> Result<(), Error> {
1854        self.p.print_date(date, &mut wtr)
1855    }
1856
1857    /// Print a `civil::Time` to the given writer.
1858    ///
1859    /// # Errors
1860    ///
1861    /// This only returns an error when writing to the given [`Write`]
1862    /// implementation would fail. Some such implementations, like for `String`
1863    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1864    /// cases, it would be appropriate to call `unwrap()` on the result.
1865    ///
1866    /// # Example
1867    ///
1868    /// ```
1869    /// use jiff::{civil::time, fmt::temporal::DateTimePrinter};
1870    ///
1871    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1872    ///
1873    /// let t = time(7, 0, 0, 0);
1874    ///
1875    /// let mut buf = String::new();
1876    /// // Printing to a `String` can never fail.
1877    /// PRINTER.print_time(&t, &mut buf).unwrap();
1878    /// assert_eq!(buf, "07:00:00");
1879    ///
1880    /// # Ok::<(), Box<dyn std::error::Error>>(())
1881    /// ```
1882    pub fn print_time<W: Write>(
1883        &self,
1884        time: &civil::Time,
1885        mut wtr: W,
1886    ) -> Result<(), Error> {
1887        self.p.print_time(time, &mut wtr)
1888    }
1889
1890    /// Print a `TimeZone`.
1891    ///
1892    /// This will emit one of three different categories of strings:
1893    ///
1894    /// 1. An IANA Time Zone Database identifier. For example,
1895    /// `America/New_York` or `UTC`.
1896    /// 2. A fixed offset. For example, `-05:00` or `-00:44:30`.
1897    /// 3. A POSIX time zone string. For example, `EST5EDT,M3.2.0,M11.1.0`.
1898    ///
1899    /// # Differences with RFC 9557 annotations
1900    ///
1901    /// Jiff's [`Offset`] has second precision. If a `TimeZone` is a fixed
1902    /// offset and has fractional minutes, then they will be expressed in the
1903    /// `[+-]HH:MM:SS` format. Otherwise, the `:SS` will be omitted.
1904    ///
1905    /// This differs from RFC 3339 and RFC 9557 because neither support
1906    /// sub-minute resolution in UTC offsets. Indeed, if one were to format a
1907    /// `ZonedDateTime` with an offset that contains fractional minutes, the
1908    /// offset would be rounded to the nearest minute to preserve compatibility
1909    /// with RFC 3339 and RFC 9557. However, this routine does no such
1910    /// rounding. This is because there is no RFC standardizing the
1911    /// serialization of a lone time zone, and there is otherwise no need to
1912    /// reduce an offset's precision.
1913    ///
1914    /// # Errors
1915    ///
1916    /// In some rare cases, serialization may fail when there is no succinct
1917    /// representation of a time zone. One specific case in which this
1918    /// occurs is when `TimeZone` is a user's system time zone derived from
1919    /// `/etc/localtime`, but where an IANA time zone identifier could not
1920    /// be found. This can occur, for example, when `/etc/localtime` is not
1921    /// symlinked to an entry in `/usr/share/zoneinfo`.
1922    ///
1923    /// An error can also occur when writing to the given [`Write`]
1924    /// implementation would fail. Some such implementations, like for `String`
1925    /// and `Vec<u8>`, never fail (unless memory allocation fails).
1926    ///
1927    /// # Example
1928    ///
1929    /// ```
1930    /// use jiff::{fmt::temporal::DateTimePrinter, tz::{self, TimeZone}};
1931    ///
1932    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1933    ///
1934    /// // IANA time zone
1935    /// let tz = TimeZone::get("America/New_York")?;
1936    /// let mut buf = String::new();
1937    /// PRINTER.print_time_zone(&tz, &mut buf)?;
1938    /// assert_eq!(buf, "America/New_York");
1939    ///
1940    /// // Fixed offset
1941    /// let tz = TimeZone::fixed(tz::offset(-5));
1942    /// let mut buf = String::new();
1943    /// PRINTER.print_time_zone(&tz, &mut buf)?;
1944    /// assert_eq!(buf, "-05:00");
1945    ///
1946    /// // POSIX time zone
1947    /// let tz = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0")?;
1948    /// let mut buf = String::new();
1949    /// PRINTER.print_time_zone(&tz, &mut buf)?;
1950    /// assert_eq!(buf, "EST5EDT,M3.2.0,M11.1.0");
1951    ///
1952    /// // The error case for a time zone that doesn't fall
1953    /// // into one of the three categories about is not easy
1954    /// // to create artificially. The only way, at time of
1955    /// // writing, to produce it is via `TimeZone::system()`
1956    /// // with a non-symlinked `/etc/timezone`. (Or `TZ` set
1957    /// // to the path of a similar file.)
1958    ///
1959    /// # Ok::<(), Box<dyn std::error::Error>>(())
1960    /// ```
1961    pub fn print_time_zone<W: Write>(
1962        &self,
1963        tz: &TimeZone,
1964        mut wtr: W,
1965    ) -> Result<(), Error> {
1966        self.p.print_time_zone(tz, &mut wtr)
1967    }
1968
1969    /// Prints a POSIX time zone string.
1970    ///
1971    /// This isn't exported because `PosixTimeZone` isn't exported. It
1972    /// probably never will be, but this is used by tests in the POSIX time
1973    /// zone parser to ensure our printing round-trips correctly. It is also
1974    /// used by way of the internal `Display` impl for `PosixTimeZone`.
1975    pub(crate) fn print_posix_time_zone<W: Write>(
1976        &self,
1977        tz: &jcore::tz::posix::TimeZone,
1978        mut wtr: W,
1979    ) -> Result<(), Error> {
1980        self.p.print_posix_time_zone(tz, &mut wtr)
1981    }
1982
1983    /// Print the `Pieces` of a Temporal datetime.
1984    ///
1985    /// # Errors
1986    ///
1987    /// This only returns an error when writing to the given [`Write`]
1988    /// implementation would fail. Some such implementations, like for `String`
1989    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
1990    /// cases, it would be appropriate to call `unwrap()` on the result.
1991    ///
1992    /// # Example
1993    ///
1994    /// ```
1995    /// use jiff::{civil::date, fmt::temporal::{DateTimePrinter, Pieces}};
1996    ///
1997    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1998    ///
1999    /// let pieces = Pieces::from(date(2024, 6, 15))
2000    ///     .with_time_zone_name("America/New_York");
2001    ///
2002    /// let mut buf = String::new();
2003    /// // Printing to a `String` can never fail.
2004    /// PRINTER.print_pieces(&pieces, &mut buf).unwrap();
2005    /// assert_eq!(buf, "2024-06-15[America/New_York]");
2006    ///
2007    /// # Ok::<(), Box<dyn std::error::Error>>(())
2008    /// ```
2009    pub fn print_pieces<W: Write>(
2010        &self,
2011        pieces: &Pieces,
2012        mut wtr: W,
2013    ) -> Result<(), Error> {
2014        self.p.print_pieces(pieces, &mut wtr)
2015    }
2016
2017    /// Prints an ISO 8601 week date.
2018    ///
2019    /// This isn't exported because it's not clear that it's worth it.
2020    /// Moreover, this isn't part of the Temporal spec, so it's a little odd
2021    /// to have it here. But it's very convenient to have the ISO 8601 week
2022    /// date parser in this module, and so we stick the printer here along
2023    /// with it.
2024    ///
2025    /// Note that this printer will use `w` when `lowercase` is enabled. (It
2026    /// isn't possible to enable this using the current Jiff public API. But
2027    /// it's probably fine.)
2028    pub(crate) fn print_iso_week_date<W: Write>(
2029        &self,
2030        iso_week_date: &ISOWeekDate,
2031        mut wtr: W,
2032    ) -> Result<(), Error> {
2033        self.p.print_iso_week_date(iso_week_date, &mut wtr)
2034    }
2035}
2036
2037/// A parser for Temporal durations.
2038///
2039/// Note that in Jiff, a "Temporal duration" is called a "span."
2040///
2041/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
2042/// more information on the specific format used.
2043///
2044/// # Example
2045///
2046/// This example shows how to parse a [`Span`] from a byte string. (That is,
2047/// `&[u8]` and not a `&str`.)
2048///
2049/// ```
2050/// use jiff::{fmt::temporal::SpanParser, ToSpan};
2051///
2052/// // A parser can be created in a const context.
2053/// static PARSER: SpanParser = SpanParser::new();
2054///
2055/// let span = PARSER.parse_span(b"P3y7m25dT7h36m")?;
2056/// assert_eq!(
2057///     span,
2058///     3.years().months(7).days(25).hours(7).minutes(36).fieldwise(),
2059/// );
2060///
2061/// # Ok::<(), Box<dyn std::error::Error>>(())
2062/// ```
2063#[derive(#[automatically_derived]impl ::core::fmt::Debug for SpanParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "SpanParser p",
            &&self.p)
    }
}Debug)]
2064pub struct SpanParser {
2065    p: parser::SpanParser,
2066}
2067
2068impl SpanParser {
2069    /// Create a new Temporal datetime printer with the default configuration.
2070    #[inline]
2071    pub const fn new() -> SpanParser {
2072        SpanParser { p: parser::SpanParser::new() }
2073    }
2074
2075    /// Parse a span string into a [`Span`] value.
2076    ///
2077    /// # Errors
2078    ///
2079    /// This returns an error if the span string given is invalid or if it
2080    /// is valid but doesn't fit in the span range supported by Jiff.
2081    ///
2082    /// # Example
2083    ///
2084    /// This shows a basic example of using this routine.
2085    ///
2086    /// ```
2087    /// use jiff::{fmt::temporal::SpanParser, ToSpan};
2088    ///
2089    /// static PARSER: SpanParser = SpanParser::new();
2090    ///
2091    /// let span = PARSER.parse_span(b"PT48m")?;
2092    /// assert_eq!(span, 48.minutes().fieldwise());
2093    ///
2094    /// # Ok::<(), Box<dyn std::error::Error>>(())
2095    /// ```
2096    ///
2097    /// Note that unless you need to parse a span from a byte string,
2098    /// at time of writing, there is no other advantage to using this
2099    /// parser directly. It is likely more convenient to just use the
2100    /// [`FromStr`](std::str::FromStr) trait implementation on [`Span`]:
2101    ///
2102    /// ```
2103    /// use jiff::{Span, ToSpan};
2104    ///
2105    /// let span = "PT48m".parse::<Span>()?;
2106    /// assert_eq!(span, 48.minutes().fieldwise());
2107    ///
2108    /// # Ok::<(), Box<dyn std::error::Error>>(())
2109    /// ```
2110    #[inline]
2111    pub fn parse_span<I: AsRef<[u8]>>(&self, input: I) -> Result<Span, Error> {
2112        self.p.parse_span(input)
2113    }
2114
2115    /// Parse an ISO 8601 duration string into a [`SignedDuration`] value.
2116    ///
2117    /// # Errors
2118    ///
2119    /// This returns an error if the span string given is invalid or if it is
2120    /// valid but can't be converted to a `SignedDuration`. This can occur
2121    /// when the parsed time exceeds the minimum and maximum `SignedDuration`
2122    /// values, or if there are any non-zero units greater than hours.
2123    ///
2124    /// # Example
2125    ///
2126    /// This shows a basic example of using this routine.
2127    ///
2128    /// ```
2129    /// use jiff::{fmt::temporal::SpanParser, SignedDuration};
2130    ///
2131    /// static PARSER: SpanParser = SpanParser::new();
2132    ///
2133    /// let duration = PARSER.parse_duration(b"PT48m")?;
2134    /// assert_eq!(duration, SignedDuration::from_mins(48));
2135    ///
2136    /// # Ok::<(), Box<dyn std::error::Error>>(())
2137    /// ```
2138    ///
2139    /// Note that unless you need to parse a span from a byte string,
2140    /// at time of writing, there is no other advantage to using this
2141    /// parser directly. It is likely more convenient to just use
2142    /// the [`FromStr`](std::str::FromStr) trait implementation on
2143    /// [`SignedDuration`]:
2144    ///
2145    /// ```
2146    /// use jiff::SignedDuration;
2147    ///
2148    /// let duration = "PT48m".parse::<SignedDuration>()?;
2149    /// assert_eq!(duration, SignedDuration::from_mins(48));
2150    ///
2151    /// # Ok::<(), Box<dyn std::error::Error>>(())
2152    /// ```
2153    #[inline]
2154    pub fn parse_duration<I: AsRef<[u8]>>(
2155        &self,
2156        input: I,
2157    ) -> Result<SignedDuration, Error> {
2158        self.p.parse_signed_duration(input)
2159    }
2160
2161    /// Parse an ISO 8601 duration string into a [`std::time::Duration`] value.
2162    ///
2163    /// # Errors
2164    ///
2165    /// This returns an error if the span string given is invalid or if it is
2166    /// valid but can't be converted to a `std::time::Duration`. This can occur
2167    /// when the parsed time exceeds the maximum `std::time::Duration` value,
2168    /// or if there are any non-zero units greater than hours.
2169    ///
2170    /// # Example
2171    ///
2172    /// This shows a basic example of using this routine.
2173    ///
2174    /// ```
2175    /// use std::time::Duration;
2176    ///
2177    /// use jiff::fmt::temporal::SpanParser;
2178    ///
2179    /// static PARSER: SpanParser = SpanParser::new();
2180    ///
2181    /// let duration = PARSER.parse_unsigned_duration(b"PT48m")?;
2182    /// assert_eq!(duration, Duration::from_secs(48 * 60));
2183    ///
2184    /// # Ok::<(), Box<dyn std::error::Error>>(())
2185    /// ```
2186    #[inline]
2187    pub fn parse_unsigned_duration<I: AsRef<[u8]>>(
2188        &self,
2189        input: I,
2190    ) -> Result<core::time::Duration, Error> {
2191        self.p.parse_unsigned_duration(input)
2192    }
2193}
2194
2195/// A printer for Temporal durations.
2196///
2197/// Note that in Jiff, a "Temporal duration" is called a "span."
2198///
2199/// This printer converts an in memory representation of a duration of time
2200/// to a machine (but also human) readable format. Using this printer,
2201/// one can convert a [`Span`] to a string. Note that a `Span` provides a
2202/// [`Display`](std::fmt::Display) trait implementation that utilize the
2203/// default configuration of this printer. However, this printer can print
2204/// directly to anything that implements the [`fmt::Write`](Write) trait.
2205///
2206/// See the [`fmt::temporal`](crate::fmt::temporal) module documentation for
2207/// more information on the specific format used.
2208///
2209/// # Example
2210///
2211/// This is a basic example showing how to print a [`Span`] directly to a
2212/// `Vec<u8>`.
2213///
2214/// ```
2215/// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
2216///
2217/// // A printer can be created in a const context.
2218/// const PRINTER: SpanPrinter = SpanPrinter::new();
2219///
2220/// let span = 48.minutes();
2221/// let mut buf = vec![];
2222/// // Printing to a `Vec<u8>` can never fail.
2223/// PRINTER.print_span(&span, &mut buf).unwrap();
2224/// assert_eq!(buf, "PT48M".as_bytes());
2225/// ```
2226///
2227/// # Example: using adapters with `std::io::Write` and `std::fmt::Write`
2228///
2229/// By using the [`StdIoWrite`](super::StdIoWrite) and
2230/// [`StdFmtWrite`](super::StdFmtWrite) adapters, one can print spans
2231/// directly to implementations of `std::io::Write` and `std::fmt::Write`,
2232/// respectively. The example below demonstrates writing to anything
2233/// that implements `std::io::Write`. Similar code can be written for
2234/// `std::fmt::Write`.
2235///
2236/// ```no_run
2237/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
2238///
2239/// use jiff::{fmt::{StdIoWrite, temporal::SpanPrinter}, ToSpan};
2240///
2241/// let span = 48.minutes();
2242///
2243/// let path = Path::new("/tmp/output");
2244/// let mut file = BufWriter::new(File::create(path)?);
2245/// SpanPrinter::new().print_span(&span, StdIoWrite(&mut file)).unwrap();
2246/// file.flush()?;
2247/// assert_eq!(std::fs::read_to_string(path)?, "PT48m");
2248///
2249/// # Ok::<(), Box<dyn std::error::Error>>(())
2250/// ```
2251#[derive(#[automatically_derived]impl ::core::fmt::Debug for SpanPrinter {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "SpanPrinter p",
            &&self.p)
    }
}Debug)]
2252pub struct SpanPrinter {
2253    p: printer::SpanPrinter,
2254}
2255
2256impl SpanPrinter {
2257    /// Create a new Temporal span printer with the default configuration.
2258    #[inline]
2259    pub const fn new() -> SpanPrinter {
2260        SpanPrinter { p: printer::SpanPrinter::new() }
2261    }
2262
2263    /// Use lowercase for unit designator labels.
2264    ///
2265    /// By default, unit designator labels are written in uppercase.
2266    ///
2267    /// # Example
2268    ///
2269    /// This shows the difference between the default (uppercase) and enabling
2270    /// lowercase. Lowercase unit designator labels tend to be easier to read
2271    /// (in this author's opinion), but they aren't as broadly supported since
2272    /// they are an extension to ISO 8601.
2273    ///
2274    /// ```
2275    /// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
2276    ///
2277    /// let span = 5.years().days(10).hours(1);
2278    /// let printer = SpanPrinter::new();
2279    /// assert_eq!(printer.span_to_string(&span), "P5Y10DT1H");
2280    /// assert_eq!(printer.lowercase(true).span_to_string(&span), "P5y10dT1h");
2281    /// ```
2282    #[inline]
2283    pub const fn lowercase(self, yes: bool) -> SpanPrinter {
2284        SpanPrinter { p: self.p.lowercase(yes) }
2285    }
2286
2287    /// Format a `Span` into a string.
2288    ///
2289    /// This is a convenience routine for [`SpanPrinter::print_span`] with
2290    /// a `String`.
2291    ///
2292    /// # Example
2293    ///
2294    /// ```
2295    /// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
2296    ///
2297    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2298    ///
2299    /// let span = 3.years().months(5);
2300    /// assert_eq!(PRINTER.span_to_string(&span), "P3Y5M");
2301    ///
2302    /// # Ok::<(), Box<dyn std::error::Error>>(())
2303    /// ```
2304    #[cfg(feature = "alloc")]
2305    pub fn span_to_string(&self, span: &Span) -> alloc::string::String {
2306        let mut buf = alloc::string::String::new();
2307        // OK because writing to `String` never fails.
2308        self.print_span(span, &mut buf).unwrap();
2309        buf
2310    }
2311
2312    /// Format a `SignedDuration` into a string.
2313    ///
2314    /// This balances the units of the duration up to at most hours
2315    /// automatically.
2316    ///
2317    /// This is a convenience routine for [`SpanPrinter::print_duration`] with
2318    /// a `String`.
2319    ///
2320    /// # Example
2321    ///
2322    /// ```
2323    /// use jiff::{fmt::temporal::SpanPrinter, SignedDuration};
2324    ///
2325    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2326    ///
2327    /// let dur = SignedDuration::new(86_525, 123_000_789);
2328    /// assert_eq!(PRINTER.duration_to_string(&dur), "PT24H2M5.123000789S");
2329    /// assert_eq!(PRINTER.duration_to_string(&-dur), "-PT24H2M5.123000789S");
2330    ///
2331    /// # Ok::<(), Box<dyn std::error::Error>>(())
2332    /// ```
2333    #[cfg(feature = "alloc")]
2334    pub fn duration_to_string(
2335        &self,
2336        duration: &SignedDuration,
2337    ) -> alloc::string::String {
2338        let mut buf = alloc::string::String::new();
2339        // OK because writing to `String` never fails.
2340        self.print_duration(duration, &mut buf).unwrap();
2341        buf
2342    }
2343
2344    /// Format a `std::time::Duration` into a string.
2345    ///
2346    /// This balances the units of the duration up to at most hours
2347    /// automatically.
2348    ///
2349    /// This is a convenience routine for
2350    /// [`SpanPrinter::print_unsigned_duration`] with a `String`.
2351    ///
2352    /// # Example
2353    ///
2354    /// ```
2355    /// use std::time::Duration;
2356    ///
2357    /// use jiff::fmt::temporal::SpanPrinter;
2358    ///
2359    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2360    ///
2361    /// let dur = Duration::new(86_525, 123_000_789);
2362    /// assert_eq!(
2363    ///     PRINTER.unsigned_duration_to_string(&dur),
2364    ///     "PT24H2M5.123000789S",
2365    /// );
2366    ///
2367    /// # Ok::<(), Box<dyn std::error::Error>>(())
2368    /// ```
2369    #[cfg(feature = "alloc")]
2370    pub fn unsigned_duration_to_string(
2371        &self,
2372        duration: &core::time::Duration,
2373    ) -> alloc::string::String {
2374        let mut buf = alloc::string::String::new();
2375        // OK because writing to `String` never fails.
2376        self.print_unsigned_duration(duration, &mut buf).unwrap();
2377        buf
2378    }
2379
2380    /// Print a `Span` to the given writer.
2381    ///
2382    /// # Errors
2383    ///
2384    /// This only returns an error when writing to the given [`Write`]
2385    /// implementation would fail. Some such implementations, like for `String`
2386    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
2387    /// cases, it would be appropriate to call `unwrap()` on the result.
2388    ///
2389    /// # Example
2390    ///
2391    /// ```
2392    /// use jiff::{fmt::temporal::SpanPrinter, ToSpan};
2393    ///
2394    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2395    ///
2396    /// let span = 3.years().months(5);
2397    ///
2398    /// let mut buf = String::new();
2399    /// // Printing to a `String` can never fail.
2400    /// PRINTER.print_span(&span, &mut buf).unwrap();
2401    /// assert_eq!(buf, "P3Y5M");
2402    ///
2403    /// # Ok::<(), Box<dyn std::error::Error>>(())
2404    /// ```
2405    pub fn print_span<W: Write>(
2406        &self,
2407        span: &Span,
2408        mut wtr: W,
2409    ) -> Result<(), Error> {
2410        self.p.print_span(span, &mut wtr)
2411    }
2412
2413    /// Print a `SignedDuration` to the given writer.
2414    ///
2415    /// This balances the units of the duration up to at most hours
2416    /// automatically.
2417    ///
2418    /// # Errors
2419    ///
2420    /// This only returns an error when writing to the given [`Write`]
2421    /// implementation would fail. Some such implementations, like for `String`
2422    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
2423    /// cases, it would be appropriate to call `unwrap()` on the result.
2424    ///
2425    /// # Example
2426    ///
2427    /// ```
2428    /// use jiff::{fmt::temporal::SpanPrinter, SignedDuration};
2429    ///
2430    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2431    ///
2432    /// let dur = SignedDuration::new(86_525, 123_000_789);
2433    ///
2434    /// let mut buf = String::new();
2435    /// // Printing to a `String` can never fail.
2436    /// PRINTER.print_duration(&dur, &mut buf).unwrap();
2437    /// assert_eq!(buf, "PT24H2M5.123000789S");
2438    ///
2439    /// // Negative durations are supported.
2440    /// buf.clear();
2441    /// PRINTER.print_duration(&-dur, &mut buf).unwrap();
2442    /// assert_eq!(buf, "-PT24H2M5.123000789S");
2443    ///
2444    /// # Ok::<(), Box<dyn std::error::Error>>(())
2445    /// ```
2446    pub fn print_duration<W: Write>(
2447        &self,
2448        duration: &SignedDuration,
2449        mut wtr: W,
2450    ) -> Result<(), Error> {
2451        self.p.print_signed_duration(duration, &mut wtr)
2452    }
2453
2454    /// Print a `std::time::Duration` to the given writer.
2455    ///
2456    /// This balances the units of the duration up to at most hours
2457    /// automatically.
2458    ///
2459    /// # Errors
2460    ///
2461    /// This only returns an error when writing to the given [`Write`]
2462    /// implementation would fail. Some such implementations, like for `String`
2463    /// and `Vec<u8>`, never fail (unless memory allocation fails). In such
2464    /// cases, it would be appropriate to call `unwrap()` on the result.
2465    ///
2466    /// # Example
2467    ///
2468    /// ```
2469    /// use std::time::Duration;
2470    /// use jiff::fmt::temporal::SpanPrinter;
2471    ///
2472    /// const PRINTER: SpanPrinter = SpanPrinter::new();
2473    ///
2474    /// let dur = Duration::new(86_525, 123_000_789);
2475    ///
2476    /// let mut buf = String::new();
2477    /// // Printing to a `String` can never fail.
2478    /// PRINTER.print_unsigned_duration(&dur, &mut buf).unwrap();
2479    /// assert_eq!(buf, "PT24H2M5.123000789S");
2480    ///
2481    /// # Ok::<(), Box<dyn std::error::Error>>(())
2482    /// ```
2483    pub fn print_unsigned_duration<W: Write>(
2484        &self,
2485        duration: &core::time::Duration,
2486        mut wtr: W,
2487    ) -> Result<(), Error> {
2488        self.p.print_unsigned_duration(duration, &mut wtr)
2489    }
2490}
2491
2492#[cfg(test)]
2493mod tests {
2494    use alloc::string::ToString;
2495
2496    use crate::Unit;
2497
2498    use super::*;
2499
2500    // This test ensures that strings like `2024-07-15+02` fail to parse.
2501    // Note though that `2024-07-15[America/New_York]` is okay!
2502    #[test]
2503    fn err_temporal_datetime_offset() {
2504        insta::assert_snapshot!(
2505            DateTimeParser::new().parse_date(b"2024-07-15+02").unwrap_err(),
2506            @r###"parsed value '2024-07-15', but unparsed input "+02" remains (expected no unparsed input)"###,
2507        );
2508        insta::assert_snapshot!(
2509            DateTimeParser::new().parse_date(b"2024-07-15-02").unwrap_err(),
2510            @r###"parsed value '2024-07-15', but unparsed input "-02" remains (expected no unparsed input)"###,
2511        );
2512    }
2513
2514    // Regression test for: https://github.com/BurntSushi/jiff/issues/539
2515    #[test]
2516    fn err_temporal_datetime_unparsed_input() {
2517        insta::assert_snapshot!(
2518            DateTimeParser::new()
2519                .parse_datetime(b"2026-04-17 19:43 AM")
2520                .unwrap_err(),
2521            @r###"parsed value '2026-04-17T19:43:00', but unparsed input " AM" remains (expected no unparsed input)"###,
2522        );
2523    }
2524
2525    #[test]
2526    fn year_zero() {
2527        insta::assert_snapshot!(
2528            DateTimeParser::new().parse_date("0000-01-01").unwrap(),
2529            @"0000-01-01",
2530        );
2531        insta::assert_snapshot!(
2532            DateTimeParser::new().parse_date("+000000-01-01").unwrap(),
2533            @"0000-01-01",
2534        );
2535        insta::assert_snapshot!(
2536            DateTimeParser::new().parse_date("-000000-01-01").unwrap_err(),
2537            @"year zero must be written without a sign or a positive sign, but not a negative sign",
2538        );
2539    }
2540
2541    // Regression test for: https://github.com/BurntSushi/jiff/issues/59
2542    #[test]
2543    fn fractional_duration_roundtrip() {
2544        let span1: Span = "Pt843517081,1H".parse().unwrap();
2545        let span2: Span = span1.to_string().parse().unwrap();
2546        assert_eq!(
2547            span1.total(Unit::Hour).unwrap(),
2548            span2.total(Unit::Hour).unwrap()
2549        );
2550    }
2551
2552    #[test]
2553    fn minimum_offset_roundtrip() {
2554        let zdt = civil::date(2025, 12, 25)
2555            .at(17, 0, 0, 0)
2556            .to_zoned_datetime(TimeZone::fixed(Offset::MIN))
2557            .unwrap();
2558        let string = zdt.to_string();
2559        assert_eq!(string, "2025-12-25T17:00:00-25:59[-25:59]");
2560
2561        let got: ZonedDateTime = string.parse().unwrap();
2562        // Since we started with a zoned datetime with a minimal offset
2563        // (to second precision) and RFC 9557 only supports minute precision
2564        // in time zone offsets, printing the zoned datetime rounds the offset.
2565        // But this would normally result in an offset beyond Jiff's limits,
2566        // so in this case, the offset truncates to the minimum supported
2567        // value by both Jiff and RFC 9557. That's what we test for here.
2568        let expected = civil::date(2025, 12, 25)
2569            .at(17, 0, 0, 0)
2570            .to_zoned_datetime(TimeZone::fixed(-Offset::hms(25, 59, 0)))
2571            .unwrap();
2572        assert_eq!(expected, got);
2573    }
2574
2575    #[test]
2576    fn maximum_offset_roundtrip() {
2577        let zdt = civil::date(2025, 12, 25)
2578            .at(17, 0, 0, 0)
2579            .to_zoned_datetime(TimeZone::fixed(Offset::MAX))
2580            .unwrap();
2581        let string = zdt.to_string();
2582        assert_eq!(string, "2025-12-25T17:00:00+25:59[+25:59]");
2583
2584        let got: ZonedDateTime = string.parse().unwrap();
2585        // Since we started with a zoned datetime with a maximal offset
2586        // (to second precision) and RFC 9557 only supports minute precision
2587        // in time zone offsets, printing the zoned datetime rounds the offset.
2588        // But this would normally result in an offset beyond Jiff's limits,
2589        // so in this case, the offset truncates to the maximum supported
2590        // value by both Jiff and RFC 9557. That's what we test for here.
2591        let expected = civil::date(2025, 12, 25)
2592            .at(17, 0, 0, 0)
2593            .to_zoned_datetime(TimeZone::fixed(Offset::hms(25, 59, 0)))
2594            .unwrap();
2595        assert_eq!(expected, got);
2596    }
2597}