Skip to main content

jiff/
zoned.rs

1use core::time::Duration as UnsignedDuration;
2
3use jcore::bounds::Sign;
4
5use crate::{
6    RoundMode, SignedDuration, Span, SpanRound, Timestamp, Unit,
7    civil::{
8        Date, DateTime, DateTimeRound, DateTimeWith, Era, ISOWeekDate, Time,
9        Weekday,
10    },
11    duration::{Duration, SDuration},
12    error::{Error, ErrorContext, zoned::Error as E},
13    fmt::{
14        self,
15        temporal::{self, DEFAULT_DATETIME_PARSER},
16    },
17    tz::{AmbiguousOffset, Disambiguation, Offset, OffsetConflict, TimeZone},
18    util::round::Increment,
19};
20
21/// A time zone aware instant in time.
22///
23/// A `ZonedDateTime` value can be thought of as the combination of following
24/// types, all rolled into one:
25///
26/// * A [`Timestamp`] for indicating the precise instant in time.
27/// * A [`DateTime`] for indicating the "civil" calendar date and clock time.
28/// * A [`TimeZone`] for indicating how to apply time zone transitions while
29/// performing arithmetic.
30///
31/// In particular, a `ZonedDateTime` is specifically designed for dealing with
32/// datetimes in a time zone aware manner. Here are some highlights:
33///
34/// * Arithmetic automatically adjusts for daylight saving time (DST), using
35/// the rules defined by [RFC 5545].
36/// * Creating new `ZonedDateTime` values from other `ZonedDateTime` values via
37/// [`ZonedDateTime::with`] by changing clock time (e.g., `02:30`) can do so
38/// without worrying that the time will be invalid due to DST transitions.
39/// * An approximate superset of the [`DateTime`] API is offered on
40/// `ZonedDateTime`, but where each of its operations take time zone into
41/// account when appropriate. For example, [`DateTime::start_of_day`] always
42/// returns a datetime set to midnight, but [`ZonedDateTime::start_of_day`]
43/// returns the first instant of a day, which might not be midnight if there is
44/// a time zone transition at midnight.
45/// * When using a `ZonedDateTime`, it is easy to switch between civil datetime
46/// (the day you see on the calendar and the time you see on the clock) and
47/// Unix time (a precise instant in time). Indeed, a `ZonedDateTime` can be
48/// losslessy converted to any other datetime type in this crate:
49/// [`Timestamp`], [`DateTime`], [`Date`] and [`Time`].
50/// * A `ZonedDateTime` value with an IANA time zone can be losslessly
51/// serialized and deserialized, via [serde], by adhering to [RFC 9557]. An
52/// example of a serialized zoned datetime is
53/// `2024-07-04T08:39:00-04:00[America/New_York]`.
54/// * Since a `ZonedDateTime` stores a [`TimeZone`] itself, multiple time zone
55/// aware operations can be chained together without repeatedly specifying the
56/// time zone.
57///
58/// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
59/// [RFC 9557]: https://www.rfc-editor.org/info/rfc9557/
60/// [serde]: https://serde.rs/
61///
62/// # Parsing and printing
63///
64/// The `ZonedDateTime` type provides convenient trait implementations of
65/// [`std::str::FromStr`] and [`std::fmt::Display`]:
66///
67/// ```
68/// use jiff::ZonedDateTime;
69///
70/// let zdt: ZonedDateTime = "2024-06-19 15:22[America/New_York]".parse()?;
71/// // Notice that the second component and the offset have both been added.
72/// assert_eq!(zdt.to_string(), "2024-06-19T15:22:00-04:00[America/New_York]");
73///
74/// // While in the above case the datetime is unambiguous, in some cases, it
75/// // can be ambiguous. In these cases, an offset is required to correctly
76/// // roundtrip a zoned datetime. For example, on 2024-11-03 in New York, the
77/// // 1 o'clock hour was repeated twice, corresponding to the end of daylight
78/// // saving time.
79/// //
80/// // So because of the ambiguity, this time could be in offset -04 (the first
81/// // time 1 o'clock is on the clock) or it could be -05 (the second time
82/// // 1 o'clock is on the clock, corresponding to the end of DST).
83/// //
84/// // By default, parsing uses a "compatible" strategy for resolving all cases
85/// // of ambiguity: in forward transitions (gaps), the later time is selected.
86/// // And in backward transitions (folds), the earlier time is selected.
87/// let zdt: ZonedDateTime = "2024-11-03 01:30[America/New_York]".parse()?;
88/// // As we can see, since this was a fold, the earlier time was selected
89/// // because the -04 offset is the first time 1 o'clock appears on the clock.
90/// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
91/// // But if we changed the offset and re-serialized, the only thing that
92/// // changes is, indeed, the offset. This demonstrates that the offset is
93/// // key to ensuring lossless serialization.
94/// let zdt = zdt.with().offset(jiff::tz::offset(-5)).build()?;
95/// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-05:00[America/New_York]");
96///
97/// # Ok::<(), Box<dyn std::error::Error>>(())
98/// ```
99///
100/// A `ZonedDateTime` can also be parsed from just a time zone aware date (but
101/// the time zone annotation is still required). In this case, the time is set
102/// to midnight:
103///
104/// ```
105/// use jiff::ZonedDateTime;
106///
107/// let zdt: ZonedDateTime = "2024-06-19[America/New_York]".parse()?;
108/// assert_eq!(zdt.to_string(), "2024-06-19T00:00:00-04:00[America/New_York]");
109/// // ... although it isn't always midnight, in the case of a time zone
110/// // transition at midnight!
111/// let zdt: ZonedDateTime = "2015-10-18[America/Sao_Paulo]".parse()?;
112/// assert_eq!(
113///     zdt.to_string(),
114///     "2015-10-18T01:00:00-02:00[America/Sao_Paulo]",
115/// );
116///
117/// # Ok::<(), Box<dyn std::error::Error>>(())
118/// ```
119///
120/// For more information on the specific format supported, see the
121/// [`fmt::temporal`](crate::fmt::temporal) module documentation.
122///
123/// # Default value
124///
125/// For convenience, this type implements the `Default` trait. Its default
126/// value corresponds to `1970-01-01T00:00:00.000000000` in the special UTC
127/// time zone. That is, it is the Unix epoch. One can also access this value
128/// via the [`ZonedDateTime::UNIX_EPOCH`] constant.
129///
130/// # Leap seconds
131///
132/// Jiff does not support leap seconds. Jiff behaves as if they don't exist.
133/// The only exception is that if one parses a datetime with a second component
134/// of `60`, then it is automatically constrained to `59`:
135///
136/// ```
137/// use jiff::{civil::date, ZonedDateTime};
138///
139/// let zdt: ZonedDateTime = "2016-12-31 23:59:60[Australia/Hobart]".parse()?;
140/// assert_eq!(zdt.datetime(), date(2016, 12, 31).at(23, 59, 59, 0));
141///
142/// # Ok::<(), Box<dyn std::error::Error>>(())
143/// ```
144///
145/// # Comparisons
146///
147/// The `ZonedDateTime` type provides both `Eq` and `Ord` trait implementations
148/// to facilitate easy comparisons. When a zoned datetime `zdt1` occurs before
149/// a zoned datetime `zdt2`, then `zdt1 < zdt2`. For example:
150///
151/// ```
152/// use jiff::civil::date;
153///
154/// let zdt1 = date(2024, 3, 11).at(1, 25, 15, 0).in_tz("America/New_York")?;
155/// let zdt2 = date(2025, 1, 31).at(0, 30, 0, 0).in_tz("America/New_York")?;
156/// assert!(zdt1 < zdt2);
157///
158/// # Ok::<(), Box<dyn std::error::Error>>(())
159/// ```
160///
161/// Note that `ZonedDateTime` comparisons only consider the precise instant in
162/// time. The civil datetime or even the time zone are completely ignored. So
163/// it's possible for a zoned datetime to be less than another even if it's
164/// civil datetime is bigger:
165///
166/// ```
167/// use jiff::civil::date;
168///
169/// let zdt1 = date(2024, 7, 4).at(12, 0, 0, 0).in_tz("America/New_York")?;
170/// let zdt2 = date(2024, 7, 4).at(11, 0, 0, 0).in_tz("America/Los_Angeles")?;
171/// assert!(zdt1 < zdt2);
172/// // But if we only compare civil datetime, the result is flipped:
173/// assert!(zdt1.datetime() > zdt2.datetime());
174///
175/// # Ok::<(), Box<dyn std::error::Error>>(())
176/// ```
177///
178/// The same applies for equality as well. Two `ZonedDateTime` values are
179/// equal, even if they have different time zones, when the instant in time is
180/// identical:
181///
182/// ```
183/// use jiff::civil::date;
184///
185/// let zdt1 = date(2024, 7, 4).at(12, 0, 0, 0).in_tz("America/New_York")?;
186/// let zdt2 = date(2024, 7, 4).at(9, 0, 0, 0).in_tz("America/Los_Angeles")?;
187/// assert_eq!(zdt1, zdt2);
188///
189/// # Ok::<(), Box<dyn std::error::Error>>(())
190/// ```
191///
192/// (Note that this is different from
193/// [Temporal's `ZonedDateTime.equals`][temporal-equals] comparison, which will
194/// take time zone into account for equality. This is because `Eq` and `Ord`
195/// trait implementations must be consistent in Rust. If you need Temporal's
196/// behavior, then use `zdt1 == zdt2 && zdt1.time_zone() == zdt2.time_zone()`.)
197///
198/// [temporal-equals]: https://tc39.es/proposal-temporal/docs/zoneddatetime.html#equals
199///
200/// # Arithmetic
201///
202/// This type provides routines for adding and subtracting spans of time, as
203/// well as computing the span of time between two `ZonedDateTime` values.
204/// These operations take time zones into account.
205///
206/// For adding or subtracting spans of time, one can use any of the following
207/// routines:
208///
209/// * [`ZonedDateTime::checked_add`] or [`ZonedDateTime::checked_sub`] for
210/// checked arithmetic.
211/// * [`ZonedDateTime::saturating_add`] or [`ZonedDateTime::saturating_sub`]
212/// for saturating arithmetic.
213///
214/// Additionally, checked arithmetic is available via the `Add` and `Sub`
215/// trait implementations. When the result overflows, a panic occurs.
216///
217/// ```
218/// use jiff::{civil::date, ToSpan};
219///
220/// let start = date(2024, 2, 25).at(15, 45, 0, 0).in_tz("America/New_York")?;
221/// // `ZonedDateTime` doesn't implement `Copy`, so you'll want to use `&start`
222/// // instead of `start` if you want to keep using it after arithmetic.
223/// let one_week_later = start + 1.weeks();
224/// assert_eq!(one_week_later.datetime(), date(2024, 3, 3).at(15, 45, 0, 0));
225///
226/// # Ok::<(), Box<dyn std::error::Error>>(())
227/// ```
228///
229/// One can compute the span of time between two zoned datetimes using either
230/// [`ZonedDateTime::until`] or [`ZonedDateTime::since`]. It's also possible to
231/// subtract two `ZonedDateTime` values directly via a `Sub` trait
232/// implementation:
233///
234/// ```
235/// use jiff::{civil::date, ToSpan};
236///
237/// let zdt1 = date(2024, 5, 3).at(23, 30, 0, 0).in_tz("America/New_York")?;
238/// let zdt2 = date(2024, 2, 25).at(7, 0, 0, 0).in_tz("America/New_York")?;
239/// assert_eq!(zdt1 - zdt2, 1647.hours().minutes(30).fieldwise());
240///
241/// # Ok::<(), Box<dyn std::error::Error>>(())
242/// ```
243///
244/// The `until` and `since` APIs are polymorphic and allow re-balancing and
245/// rounding the span returned. For example, the default largest unit is hours
246/// (as exemplified above), but we can ask for bigger units:
247///
248/// ```
249/// use jiff::{civil::date, ToSpan, Unit};
250///
251/// let zdt1 = date(2024, 5, 3).at(23, 30, 0, 0).in_tz("America/New_York")?;
252/// let zdt2 = date(2024, 2, 25).at(7, 0, 0, 0).in_tz("America/New_York")?;
253/// assert_eq!(
254///     zdt1.since((Unit::Year, &zdt2))?,
255///     2.months().days(7).hours(16).minutes(30).fieldwise(),
256/// );
257///
258/// # Ok::<(), Box<dyn std::error::Error>>(())
259/// ```
260///
261/// Or even round the span returned:
262///
263/// ```
264/// use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};
265///
266/// let zdt1 = date(2024, 5, 3).at(23, 30, 0, 0).in_tz("America/New_York")?;
267/// let zdt2 = date(2024, 2, 25).at(7, 0, 0, 0).in_tz("America/New_York")?;
268/// assert_eq!(
269///     zdt1.since(
270///         ZonedDateTimeDifference::new(&zdt2)
271///             .smallest(Unit::Day)
272///             .largest(Unit::Year),
273///     )?,
274///     2.months().days(7).fieldwise(),
275/// );
276/// // `ZonedDateTimeDifference` uses truncation as a rounding mode by default,
277/// // but you can set the rounding mode to break ties away from zero:
278/// assert_eq!(
279///     zdt1.since(
280///         ZonedDateTimeDifference::new(&zdt2)
281///             .smallest(Unit::Day)
282///             .largest(Unit::Year)
283///             .mode(RoundMode::HalfExpand),
284///     )?,
285///     // Rounds up to 8 days.
286///     2.months().days(8).fieldwise(),
287/// );
288///
289/// # Ok::<(), Box<dyn std::error::Error>>(())
290/// ```
291///
292/// # Rounding
293///
294/// A `ZonedDateTime` can be rounded based on a [`ZonedDateTimeRound`]
295/// configuration of smallest units, rounding increment and rounding mode.
296/// Here's an example showing how to round to the nearest third hour:
297///
298/// ```
299/// use jiff::{Unit, ZonedDateTimeRound, civil::date};
300///
301/// let zdt = date(2024, 6, 19)
302///     .at(16, 27, 29, 999_999_999)
303///     .in_tz("America/New_York")?;
304/// assert_eq!(
305///     zdt.round(
306///         ZonedDateTimeRound::new().smallest(Unit::Hour).increment(3)
307///     )?,
308///     date(2024, 6, 19).at(15, 0, 0, 0).in_tz("America/New_York")?,
309/// );
310/// // Or alternatively, make use of the `From<(Unit, i64)> for
311/// // ZonedDateTimeRound` trait implementation:
312/// assert_eq!(
313///     zdt.round((Unit::Hour, 3))?,
314///     date(2024, 6, 19).at(15, 0, 0, 0).in_tz("America/New_York")?,
315/// );
316///
317/// # Ok::<(), Box<dyn std::error::Error>>(())
318/// ```
319///
320/// See [`ZonedDateTime::round`] for more details.
321#[derive(#[automatically_derived]impl ::core::clone::Clone for ZonedDateTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ZonedDateTime { inner: ::core::clone::Clone::clone(&self.inner) }
    }
}Clone)]
322pub struct ZonedDateTime {
323    inner: ZonedDateTimeInner,
324}
325
326/// The representation of a `ZonedDateTime`.
327///
328/// This uses 4 different things: a timestamp, a datetime, an offset and a time
329/// zone. This in turn makes `ZonedDateTime` a bit beefy (40 bytes on x86-64),
330/// but I think this is probably the right trade off. (At time of writing,
331/// 2024-07-04.)
332///
333/// Technically speaking, the only essential fields here are timestamp and time
334/// zone. The datetime and offset can both be unambiguously _computed_ from the
335/// combination of a timestamp and a time zone. Indeed, just the timestamp and
336/// the time zone was my initial representation. But as I developed the API of
337/// this type, it became clearer that we should probably store the datetime and
338/// offset as well.
339///
340/// The main issue here is that in order to compute the datetime from a
341/// timestamp and a time zone, you need to do two things:
342///
343/// 1. First, compute the offset. This means doing a binary search on the TZif
344/// data for the transition (or closest transition) matching the timestamp.
345/// 2. Second, use the offset (from UTC) to convert the timestamp into a civil
346/// datetime. This involves a "Unix time to Unix epoch days" conversion that
347/// requires some heavy arithmetic.
348///
349/// So if we don't store the datetime or offset, then we need to compute them
350/// any time we need them. And the Temporal design really pushes heavily in
351/// favor of treating the "instant in time" and "civil datetime" as two sides
352/// to the same coin. That means users are very encouraged to just use whatever
353/// they need. So if we are always computing the offset and datetime whenever
354/// we need them, we're potentially punishing users for working with civil
355/// datetimes. It just doesn't feel like the right trade-off.
356///
357/// Instead, my idea here is that, ultimately, `ZonedDateTime` is meant to
358/// provide a one-stop shop for "doing the right thing." Presenting that
359/// unified abstraction comes with costs. And that if we want to expose cheaper
360/// ways of performing at least some of the operations on `ZonedDateTime` by
361/// making fewer assumptions, then we should probably endeavor to do that by
362/// exposing a lower level API. I'm not sure what that would look like, so I
363/// think it should be driven by use cases.
364///
365/// Some other things I considered:
366///
367/// * Use `ZonedDateTime(Arc<ZonedDateTimeInner>)` to make `ZonedDateTime`
368/// pointer-sized. But I didn't like this because it implies creating any new
369/// `ZonedDateTime` value requires an allocation. Since a `TimeZone` internally
370/// uses an `Arc`, all it requires today is a chunky memcpy and an atomic ref
371/// count increment.
372/// * Use `OnceLock` shenanigans for the datetime and offset fields. This would
373/// make `ZonedDateTime` even beefier and I wasn't totally clear how much this
374/// would save us. And it would impose some (probably small) cost on every
375/// datetime or offset access.
376/// * Use a radically different design that permits a `ZonedDateTime` to be
377/// `Copy`. I personally find it deeply annoying that `ZonedDateTime` is both
378/// the "main" datetime type in Jiff and also the only one that doesn't
379/// implement `Copy`. I explored some designs, but I couldn't figure out how to
380/// make it work in a satisfying way. The main issue here is `TimeZone`. A
381/// `TimeZone` is a huge chunk of data and the ergonomics of the
382/// `ZonedDateTime` API require being able to access a `TimeZone` without the
383/// caller providing it explicitly. So to me, the only real alternative here is
384/// to use some kind of integer handle into a global time zone database. But
385/// now you all of a sudden need to worry about synchronization for every time
386/// zone access and plausibly also garbage collection. And this also
387/// complicates matters for using custom time zone databases. So I ultimately
388/// came down on "ZonedDateTime is not Copy" as the least awful choice. *heavy
389/// sigh*
390#[derive(#[automatically_derived]impl ::core::clone::Clone for ZonedDateTimeInner {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ZonedDateTimeInner {
            timestamp: ::core::clone::Clone::clone(&self.timestamp),
            datetime: ::core::clone::Clone::clone(&self.datetime),
            offset: ::core::clone::Clone::clone(&self.offset),
            time_zone: ::core::clone::Clone::clone(&self.time_zone),
        }
    }
}Clone)]
391struct ZonedDateTimeInner {
392    timestamp: Timestamp,
393    datetime: DateTime,
394    offset: Offset,
395    time_zone: TimeZone,
396}
397
398impl ZonedDateTime {
399    /// The Unix epoch represented as a timestamp in the [`UTC`](TimeZone::UTC)
400    /// time zone.
401    ///
402    /// The Unix epoch corresponds to the instant at `1970-01-01T00:00:00Z`.
403    ///
404    /// This is equivalent to `ZonedDateTime::new(Timestamp::UNIX_EPOCH,
405    /// TimeZone::UTC)`. This is also equivalent to `ZonedDateTime::default()`,
406    /// but it can be used in a `const` context.
407    pub const UNIX_EPOCH: ZonedDateTime = ZonedDateTime::from_parts(
408        Timestamp::UNIX_EPOCH,
409        DateTime::constant(1970, 1, 1, 0, 0, 0, 0),
410        Offset::UTC,
411        TimeZone::UTC,
412    );
413
414    /// Returns the current system time in this system's time zone.
415    ///
416    /// If the system's time zone could not be found, then
417    /// [`TimeZone::unknown`] is used instead. When this happens, a `WARN`
418    /// level log message will be emitted. (To see it, one will need to install
419    /// a logger that is compatible with the `log` crate and enable Jiff's
420    /// `logging` Cargo feature.)
421    ///
422    /// To create a `ZonedDateTime` value for the current time in a particular
423    /// time zone other than the system default time zone, use
424    /// `Timestamp::now().to_zoned_datetime(time_zone)`. In particular, using
425    /// [`Timestamp::now`] avoids the work required to fetch the system time
426    /// zone if you did `ZonedDateTime::now().with_time_zone(time_zone)`.
427    ///
428    /// # Panics
429    ///
430    /// This panics if the system clock is set to a time value outside of the
431    /// range `-009999-01-01T00:00:00Z..=9999-12-31T11:59:59.999999999Z`. The
432    /// justification here is that it is reasonable to expect the system clock
433    /// to be set to a somewhat sane, if imprecise, value.
434    ///
435    /// If you want to get the current Unix time fallibly, use
436    /// [`ZonedDateTime::try_from`] with a `std::time::SystemTime` as input.
437    ///
438    /// This may also panic when `SystemTime::now()` itself panics. The most
439    /// common context in which this happens is on the `wasm32-unknown-unknown`
440    /// target. If you're using that target in the context of the web (for
441    /// example, via `wasm-pack`), and you're an application, then you should
442    /// enable Jiff's `js` feature. This will automatically instruct Jiff in
443    /// this very specific circumstance to execute JavaScript code to determine
444    /// the current time from the web browser.
445    ///
446    /// # Example
447    ///
448    /// ```
449    /// use jiff::{Timestamp, ZonedDateTime};
450    ///
451    /// assert!(ZonedDateTime::now().timestamp() > Timestamp::UNIX_EPOCH);
452    /// ```
453    #[cfg(feature = "std")]
454    #[inline]
455    pub fn now() -> ZonedDateTime {
456        ZonedDateTime::try_from(crate::now::system_time())
457            .expect("system time is valid")
458    }
459
460    /// Creates a new `ZonedDateTime` value from a specific instant in a
461    /// particular time zone. The time zone determines how to render the
462    /// instant in time into civil time. (Also known as "clock," "wall,"
463    /// "local" or "naive" time.)
464    ///
465    /// To create a new zoned datetime from another with a particular field
466    /// value, use the methods on [`ZonedDateTimeWith`] via
467    /// [`ZonedDateTime::with`].
468    ///
469    /// # Construction from civil time
470    ///
471    /// A `ZonedDateTime` value can also be created from a civil time via the
472    /// following methods:
473    ///
474    /// * [`DateTime::in_tz`] does a Time Zone Database lookup given a time
475    /// zone name string.
476    /// * [`DateTime::to_zoned_datetime`] accepts a `TimeZone`.
477    /// * [`Date::in_tz`] does a Time Zone Database lookup given a time zone
478    /// name string and attempts to use midnight as the clock time.
479    /// * [`Date::to_zoned_datetime`] accepts a `TimeZone` and attempts to use
480    /// midnight as the clock time.
481    ///
482    /// Whenever one is converting from civil time to a zoned
483    /// datetime, it is possible for the civil time to be ambiguous.
484    /// That is, it might be a clock reading that could refer to
485    /// multiple possible instants in time, or it might be a clock
486    /// reading that never exists. The above routines will use a
487    /// [`Disambiguation::Compatible`]
488    /// strategy to automatically resolve these corner cases.
489    ///
490    /// If one wants to control how ambiguity is resolved (including
491    /// by returning an error), use [`TimeZone::to_ambiguous_zoned_datetime`]
492    /// and select the desired strategy via a method on
493    /// [`AmbiguousZonedDateTime`](crate::tz::AmbiguousZonedDateTime).
494    ///
495    /// # Example: What was the civil time in Tasmania at the Unix epoch?
496    ///
497    /// ```
498    /// use jiff::{tz::TimeZone, Timestamp, ZonedDateTime};
499    ///
500    /// let tz = TimeZone::get("Australia/Hobart")?;
501    /// let zdt = ZonedDateTime::new(Timestamp::UNIX_EPOCH, tz);
502    /// assert_eq!(
503    ///     zdt.to_string(),
504    ///     "1970-01-01T11:00:00+11:00[Australia/Hobart]",
505    /// );
506    ///
507    /// # Ok::<(), Box<dyn std::error::Error>>(())
508    /// ```
509    ///
510    /// # Example: What was the civil time in New York when World War 1 ended?
511    ///
512    /// ```
513    /// use jiff::civil::date;
514    ///
515    /// let zdt1 = date(1918, 11, 11).at(11, 0, 0, 0).in_tz("Europe/Paris")?;
516    /// let zdt2 = zdt1.in_tz("America/New_York")?;
517    /// assert_eq!(
518    ///     zdt2.to_string(),
519    ///     "1918-11-11T06:00:00-05:00[America/New_York]",
520    /// );
521    ///
522    /// # Ok::<(), Box<dyn std::error::Error>>(())
523    /// ```
524    #[inline]
525    pub fn new(timestamp: Timestamp, time_zone: TimeZone) -> ZonedDateTime {
526        let offset = time_zone.to_offset(timestamp);
527        let datetime = offset.to_datetime(timestamp);
528        let inner =
529            ZonedDateTimeInner { timestamp, datetime, offset, time_zone };
530        ZonedDateTime { inner }
531    }
532
533    /// A crate internal constructor for building a `ZonedDateTime` from its
534    /// constituent parts.
535    ///
536    /// See `civil::DateTime::to_zoned_datetime` for a use case for this
537    /// routine. (Why do you think? Perf!)
538    ///
539    /// This should *probably* never be exposed, because it can be quite tricky
540    /// to get the parts correct. However, pretty much everything bows at the
541    /// alter of performance, so I'm open to exporting it given sufficient
542    /// motivation. We could add debug asserts that trip when `datetime`
543    /// and `offset` are incorrect.
544    #[inline]
545    pub(crate) const fn from_parts(
546        timestamp: Timestamp,
547        datetime: DateTime,
548        offset: Offset,
549        time_zone: TimeZone,
550    ) -> ZonedDateTime {
551        ZonedDateTime {
552            inner: ZonedDateTimeInner {
553                timestamp,
554                datetime,
555                offset,
556                time_zone,
557            },
558        }
559    }
560
561    /// Create a builder for constructing a new `ZonedDateTime` from the fields
562    /// of this zoned datetime.
563    ///
564    /// See the methods on [`ZonedDateTimeWith`] for the different ways one can
565    /// set the fields of a new `ZonedDateTime`.
566    ///
567    /// Note that this doesn't support changing the time zone. If you want a
568    /// `ZonedDateTime` value of the same instant but in a different time zone,
569    /// use [`ZonedDateTime::in_tz`] or [`ZonedDateTime::with_time_zone`]. If
570    /// you want a `ZonedDateTime` value of the same civil datetime (assuming
571    /// it isn't ambiguous) but in a different time zone, then use
572    /// [`ZonedDateTime::datetime`] followed by [`DateTime::in_tz`] or
573    /// [`DateTime::to_zoned_datetime`].
574    ///
575    /// # Example
576    ///
577    /// The builder ensures one can chain together the individual components
578    /// of a zoned datetime without it failing at an intermediate step. For
579    /// example, if you had a date of `2024-10-31T00:00:00[America/New_York]`
580    /// and wanted to change both the day and the month, and each setting was
581    /// validated independent of the other, you would need to be careful to set
582    /// the day first and then the month. In some cases, you would need to set
583    /// the month first and then the day!
584    ///
585    /// But with the builder, you can set values in any order:
586    ///
587    /// ```
588    /// use jiff::civil::date;
589    ///
590    /// let zdt1 = date(2024, 10, 31)
591    ///     .at(0, 0, 0, 0)
592    ///     .in_tz("America/New_York")?;
593    /// let zdt2 = zdt1.with().month(11).day(30).build()?;
594    /// assert_eq!(
595    ///     zdt2,
596    ///     date(2024, 11, 30).at(0, 0, 0, 0).in_tz("America/New_York")?,
597    /// );
598    ///
599    /// let zdt1 = date(2024, 4, 30).at(0, 0, 0, 0).in_tz("America/New_York")?;
600    /// let zdt2 = zdt1.with().day(31).month(7).build()?;
601    /// assert_eq!(
602    ///     zdt2,
603    ///     date(2024, 7, 31).at(0, 0, 0, 0).in_tz("America/New_York")?,
604    /// );
605    ///
606    /// # Ok::<(), Box<dyn std::error::Error>>(())
607    /// ```
608    #[inline]
609    pub fn with(&self) -> ZonedDateTimeWith {
610        ZonedDateTimeWith::new(self.clone())
611    }
612
613    /// Return a new zoned datetime with precisely the same instant in a
614    /// different time zone.
615    ///
616    /// The zoned datetime returned is guaranteed to have an equivalent
617    /// [`Timestamp`]. However, its civil [`DateTime`] may be different.
618    ///
619    /// # Example: What was the civil time in New York when World War 1 ended?
620    ///
621    /// ```
622    /// use jiff::{civil::date, tz::TimeZone};
623    ///
624    /// let from = TimeZone::get("Europe/Paris")?;
625    /// let to = TimeZone::get("America/New_York")?;
626    /// let zdt1 =
627    ///     date(1918, 11, 11).at(11, 0, 0, 0).to_zoned_datetime(from)?;
628    /// // Switch zdt1 to a different time zone, but keeping the same instant
629    /// // in time. The civil time changes, but not the instant!
630    /// let zdt2 = zdt1.with_time_zone(to);
631    /// assert_eq!(
632    ///     zdt2.to_string(),
633    ///     "1918-11-11T06:00:00-05:00[America/New_York]",
634    /// );
635    ///
636    /// # Ok::<(), Box<dyn std::error::Error>>(())
637    /// ```
638    #[inline]
639    pub fn with_time_zone(&self, time_zone: TimeZone) -> ZonedDateTime {
640        ZonedDateTime::new(self.timestamp(), time_zone)
641    }
642
643    /// Return a new zoned datetime with precisely the same instant in a
644    /// different time zone.
645    ///
646    /// The zoned datetime returned is guaranteed to have an equivalent
647    /// [`Timestamp`]. However, its civil [`DateTime`] may be different.
648    ///
649    /// The name given is resolved to a [`TimeZone`] by using the default
650    /// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase) created by
651    /// [`tz::db`](crate::tz::db). Indeed, this is a convenience function for
652    /// [`DateTime::to_zoned_datetime`] where the time zone database lookup is
653    /// done automatically.
654    ///
655    /// # Errors
656    ///
657    /// This returns an error when the given time zone name could not be found
658    /// in the default time zone database.
659    ///
660    /// # Example: What was the civil time in New York when World War 1 ended?
661    ///
662    /// ```
663    /// use jiff::civil::date;
664    ///
665    /// let zdt1 = date(1918, 11, 11).at(11, 0, 0, 0).in_tz("Europe/Paris")?;
666    /// // Switch zdt1 to a different time zone, but keeping the same instant
667    /// // in time. The civil time changes, but not the instant!
668    /// let zdt2 = zdt1.in_tz("America/New_York")?;
669    /// assert_eq!(
670    ///     zdt2.to_string(),
671    ///     "1918-11-11T06:00:00-05:00[America/New_York]",
672    /// );
673    ///
674    /// # Ok::<(), Box<dyn std::error::Error>>(())
675    /// ```
676    #[inline]
677    pub fn in_tz(&self, name: &str) -> Result<ZonedDateTime, Error> {
678        let tz = crate::tz::db().get(name)?;
679        Ok(self.with_time_zone(tz))
680    }
681
682    /// Returns the time zone attached to this [`ZonedDateTime`] value.
683    ///
684    /// A time zone is more than just an offset. A time zone is a series of
685    /// rules for determining the civil time for a corresponding instant.
686    /// Indeed, a zoned datetime uses its time zone to perform zone-aware
687    /// arithmetic, rounding and serialization.
688    ///
689    /// # Example
690    ///
691    /// ```
692    /// use jiff::ZonedDateTime;
693    ///
694    /// let zdt: ZonedDateTime = "2024-07-03 14:31[america/new_york]".parse()?;
695    /// assert_eq!(zdt.time_zone().iana_name(), Some("America/New_York"));
696    ///
697    /// # Ok::<(), Box<dyn std::error::Error>>(())
698    /// ```
699    #[inline]
700    pub fn time_zone(&self) -> &TimeZone {
701        &self.inner.time_zone
702    }
703
704    /// Returns the year for this zoned datetime.
705    ///
706    /// The value returned is guaranteed to be in the range `-9999..=9999`.
707    ///
708    /// # Example
709    ///
710    /// ```
711    /// use jiff::civil::date;
712    ///
713    /// let zdt1 = date(2024, 3, 9).at(7, 30, 0, 0).in_tz("America/New_York")?;
714    /// assert_eq!(zdt1.year(), 2024);
715    ///
716    /// let zdt2 = date(-2024, 3, 9)
717    ///     .at(7, 30, 0, 0)
718    ///     .in_tz("America/New_York")?;
719    /// assert_eq!(zdt2.year(), -2024);
720    ///
721    /// let zdt3 = date(0, 3, 9).at(7, 30, 0, 0).in_tz("America/New_York")?;
722    /// assert_eq!(zdt3.year(), 0);
723    ///
724    /// # Ok::<(), Box<dyn std::error::Error>>(())
725    /// ```
726    #[inline]
727    pub fn year(&self) -> i16 {
728        self.date().year()
729    }
730
731    /// Returns the year and its era.
732    ///
733    /// This crate specifically allows years to be negative or `0`, where as
734    /// years written for the Gregorian calendar are always positive and
735    /// greater than `0`. In the Gregorian calendar, the era labels `BCE` and
736    /// `CE` are used to disambiguate between years less than or equal to `0`
737    /// and years greater than `0`, respectively.
738    ///
739    /// The crate is designed this way so that years in the latest era (that
740    /// is, `CE`) are aligned with years in this crate.
741    ///
742    /// The year returned is guaranteed to be in the range `1..=10000`.
743    ///
744    /// # Example
745    ///
746    /// ```
747    /// use jiff::civil::{Era, date};
748    ///
749    /// let zdt = date(2024, 10, 3).at(7, 30, 0, 0).in_tz("America/New_York")?;
750    /// assert_eq!(zdt.era_year(), (2024, Era::CE));
751    ///
752    /// let zdt = date(1, 10, 3).at(7, 30, 0, 0).in_tz("America/New_York")?;
753    /// assert_eq!(zdt.era_year(), (1, Era::CE));
754    ///
755    /// let zdt = date(0, 10, 3).at(7, 30, 0, 0).in_tz("America/New_York")?;
756    /// assert_eq!(zdt.era_year(), (1, Era::BCE));
757    ///
758    /// let zdt = date(-1, 10, 3).at(7, 30, 0, 0).in_tz("America/New_York")?;
759    /// assert_eq!(zdt.era_year(), (2, Era::BCE));
760    ///
761    /// let zdt = date(-10, 10, 3).at(7, 30, 0, 0).in_tz("America/New_York")?;
762    /// assert_eq!(zdt.era_year(), (11, Era::BCE));
763    ///
764    /// let zdt = date(-9_999, 10, 3)
765    ///     .at(7, 30, 0, 0)
766    ///     .in_tz("America/New_York")?;
767    /// assert_eq!(zdt.era_year(), (10_000, Era::BCE));
768    ///
769    /// # Ok::<(), Box<dyn std::error::Error>>(())
770    /// ```
771    #[inline]
772    pub fn era_year(&self) -> (i16, Era) {
773        self.date().era_year()
774    }
775
776    /// Returns the month for this zoned datetime.
777    ///
778    /// The value returned is guaranteed to be in the range `1..=12`.
779    ///
780    /// # Example
781    ///
782    /// ```
783    /// use jiff::civil::date;
784    ///
785    /// let zdt = date(2024, 3, 9).at(7, 30, 0, 0).in_tz("America/New_York")?;
786    /// assert_eq!(zdt.month(), 3);
787    ///
788    /// # Ok::<(), Box<dyn std::error::Error>>(())
789    /// ```
790    #[inline]
791    pub fn month(&self) -> i8 {
792        self.date().month()
793    }
794
795    /// Returns the day for this zoned datetime.
796    ///
797    /// The value returned is guaranteed to be in the range `1..=31`.
798    ///
799    /// # Example
800    ///
801    /// ```
802    /// use jiff::civil::date;
803    ///
804    /// let zdt = date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?;
805    /// assert_eq!(zdt.day(), 29);
806    ///
807    /// # Ok::<(), Box<dyn std::error::Error>>(())
808    /// ```
809    #[inline]
810    pub fn day(&self) -> i8 {
811        self.date().day()
812    }
813
814    /// Returns the "hour" component of this zoned datetime.
815    ///
816    /// The value returned is guaranteed to be in the range `0..=23`.
817    ///
818    /// # Example
819    ///
820    /// ```
821    /// use jiff::civil::date;
822    ///
823    /// let zdt = date(2000, 1, 2)
824    ///     .at(3, 4, 5, 123_456_789)
825    ///     .in_tz("America/New_York")?;
826    /// assert_eq!(zdt.hour(), 3);
827    ///
828    /// # Ok::<(), Box<dyn std::error::Error>>(())
829    /// ```
830    #[inline]
831    pub fn hour(&self) -> i8 {
832        self.time().hour()
833    }
834
835    /// Returns the "minute" component of this zoned datetime.
836    ///
837    /// The value returned is guaranteed to be in the range `0..=59`.
838    ///
839    /// # Example
840    ///
841    /// ```
842    /// use jiff::civil::date;
843    ///
844    /// let zdt = date(2000, 1, 2)
845    ///     .at(3, 4, 5, 123_456_789)
846    ///     .in_tz("America/New_York")?;
847    /// assert_eq!(zdt.minute(), 4);
848    ///
849    /// # Ok::<(), Box<dyn std::error::Error>>(())
850    /// ```
851    #[inline]
852    pub fn minute(&self) -> i8 {
853        self.time().minute()
854    }
855
856    /// Returns the "second" component of this zoned datetime.
857    ///
858    /// The value returned is guaranteed to be in the range `0..=59`.
859    ///
860    /// # Example
861    ///
862    /// ```
863    /// use jiff::civil::date;
864    ///
865    /// let zdt = date(2000, 1, 2)
866    ///     .at(3, 4, 5, 123_456_789)
867    ///     .in_tz("America/New_York")?;
868    /// assert_eq!(zdt.second(), 5);
869    ///
870    /// # Ok::<(), Box<dyn std::error::Error>>(())
871    /// ```
872    #[inline]
873    pub fn second(&self) -> i8 {
874        self.time().second()
875    }
876
877    /// Returns the "millisecond" component of this zoned datetime.
878    ///
879    /// The value returned is guaranteed to be in the range `0..=999`.
880    ///
881    /// # Example
882    ///
883    /// ```
884    /// use jiff::civil::date;
885    ///
886    /// let zdt = date(2000, 1, 2)
887    ///     .at(3, 4, 5, 123_456_789)
888    ///     .in_tz("America/New_York")?;
889    /// assert_eq!(zdt.millisecond(), 123);
890    ///
891    /// # Ok::<(), Box<dyn std::error::Error>>(())
892    /// ```
893    #[inline]
894    pub fn millisecond(&self) -> i16 {
895        self.time().millisecond()
896    }
897
898    /// Returns the "microsecond" component of this zoned datetime.
899    ///
900    /// The value returned is guaranteed to be in the range `0..=999`.
901    ///
902    /// # Example
903    ///
904    /// ```
905    /// use jiff::civil::date;
906    ///
907    /// let zdt = date(2000, 1, 2)
908    ///     .at(3, 4, 5, 123_456_789)
909    ///     .in_tz("America/New_York")?;
910    /// assert_eq!(zdt.microsecond(), 456);
911    ///
912    /// # Ok::<(), Box<dyn std::error::Error>>(())
913    /// ```
914    #[inline]
915    pub fn microsecond(&self) -> i16 {
916        self.time().microsecond()
917    }
918
919    /// Returns the "nanosecond" component of this zoned datetime.
920    ///
921    /// The value returned is guaranteed to be in the range `0..=999`.
922    ///
923    /// # Example
924    ///
925    /// ```
926    /// use jiff::civil::date;
927    ///
928    /// let zdt = date(2000, 1, 2)
929    ///     .at(3, 4, 5, 123_456_789)
930    ///     .in_tz("America/New_York")?;
931    /// assert_eq!(zdt.nanosecond(), 789);
932    ///
933    /// # Ok::<(), Box<dyn std::error::Error>>(())
934    /// ```
935    #[inline]
936    pub fn nanosecond(&self) -> i16 {
937        self.time().nanosecond()
938    }
939
940    /// Returns the fractional nanosecond for this `ZonedDateTime` value.
941    ///
942    /// If you want to set this value on `ZonedDateTime`, then use
943    /// [`ZonedDateTimeWith::subsec_nanosecond`] via [`ZonedDateTime::with`].
944    ///
945    /// The value returned is guaranteed to be in the range `0..=999_999_999`.
946    ///
947    /// Note that this returns the fractional second associated with the civil
948    /// time on this `ZonedDateTime` value. This is distinct from the
949    /// fractional second on the underlying timestamp. A timestamp, for
950    /// example, may be negative to indicate time before the Unix epoch. But a
951    /// civil datetime can only have a negative year, while the remaining
952    /// values are all semantically positive. See the examples below for how
953    /// this can manifest in practice.
954    ///
955    /// # Example
956    ///
957    /// This shows the relationship between constructing a `ZonedDateTime`
958    /// value with routines like `with().millisecond()` and accessing the
959    /// entire fractional part as a nanosecond:
960    ///
961    /// ```
962    /// use jiff::civil::date;
963    ///
964    /// let zdt1 = date(2000, 1, 2)
965    ///     .at(3, 4, 5, 123_456_789)
966    ///     .in_tz("America/New_York")?;
967    /// assert_eq!(zdt1.subsec_nanosecond(), 123_456_789);
968    ///
969    /// let zdt2 = zdt1.with().millisecond(333).build()?;
970    /// assert_eq!(zdt2.subsec_nanosecond(), 333_456_789);
971    ///
972    /// # Ok::<(), Box<dyn std::error::Error>>(())
973    /// ```
974    ///
975    /// # Example: nanoseconds from a timestamp
976    ///
977    /// This shows how the fractional nanosecond part of a `ZonedDateTime`
978    /// value manifests from a specific timestamp.
979    ///
980    /// ```
981    /// use jiff::Timestamp;
982    ///
983    /// // 1,234 nanoseconds after the Unix epoch.
984    /// let zdt = Timestamp::new(0, 1_234)?.in_tz("UTC")?;
985    /// assert_eq!(zdt.subsec_nanosecond(), 1_234);
986    /// // N.B. The timestamp's fractional second and the civil datetime's
987    /// // fractional second happen to be equal here:
988    /// assert_eq!(zdt.timestamp().subsec_nanosecond(), 1_234);
989    ///
990    /// # Ok::<(), Box<dyn std::error::Error>>(())
991    /// ```
992    ///
993    /// # Example: fractional seconds in timestamps and civil time
994    ///
995    /// This shows how a timestamp can have a different fractional second value
996    /// than its corresponding `ZonedDateTime` value because of how the sign is
997    /// handled:
998    ///
999    /// ```
1000    /// use jiff::{civil, Timestamp};
1001    ///
1002    /// // 1,234 nanoseconds before the Unix epoch.
1003    /// let zdt = Timestamp::new(0, -1_234)?.in_tz("UTC")?;
1004    /// // The timestamp's fractional second is what was given:
1005    /// assert_eq!(zdt.timestamp().subsec_nanosecond(), -1_234);
1006    /// // But the civil datetime's fractional second is equal to
1007    /// // `1_000_000_000 - 1_234`. This is because civil datetimes
1008    /// // represent times in strictly positive values, like it
1009    /// // would read on a clock.
1010    /// assert_eq!(zdt.subsec_nanosecond(), 999998766);
1011    /// // Looking at the other components of the time value might help.
1012    /// assert_eq!(zdt.hour(), 23);
1013    /// assert_eq!(zdt.minute(), 59);
1014    /// assert_eq!(zdt.second(), 59);
1015    ///
1016    /// # Ok::<(), Box<dyn std::error::Error>>(())
1017    /// ```
1018    #[inline]
1019    pub fn subsec_nanosecond(&self) -> i32 {
1020        self.time().subsec_nanosecond()
1021    }
1022
1023    /// Returns the weekday corresponding to this zoned datetime.
1024    ///
1025    /// # Example
1026    ///
1027    /// ```
1028    /// use jiff::civil::{Weekday, date};
1029    ///
1030    /// // The Unix epoch was on a Thursday.
1031    /// let zdt = date(1970, 1, 1).at(7, 30, 0, 0).in_tz("America/New_York")?;
1032    /// assert_eq!(zdt.weekday(), Weekday::Thursday);
1033    /// // One can also get the weekday as an offset in a variety of schemes.
1034    /// assert_eq!(zdt.weekday().to_monday_zero_offset(), 3);
1035    /// assert_eq!(zdt.weekday().to_monday_one_offset(), 4);
1036    /// assert_eq!(zdt.weekday().to_sunday_zero_offset(), 4);
1037    /// assert_eq!(zdt.weekday().to_sunday_one_offset(), 5);
1038    ///
1039    /// # Ok::<(), Box<dyn std::error::Error>>(())
1040    /// ```
1041    #[inline]
1042    pub fn weekday(&self) -> Weekday {
1043        self.date().weekday()
1044    }
1045
1046    /// Returns the ordinal day of the year that this zoned datetime resides
1047    /// in.
1048    ///
1049    /// For leap years, this always returns a value in the range `1..=366`.
1050    /// Otherwise, the value is in the range `1..=365`.
1051    ///
1052    /// # Example
1053    ///
1054    /// ```
1055    /// use jiff::civil::date;
1056    ///
1057    /// let zdt = date(2006, 8, 24)
1058    ///     .at(7, 30, 0, 0)
1059    ///     .in_tz("America/New_York")?;
1060    /// assert_eq!(zdt.day_of_year(), 236);
1061    ///
1062    /// let zdt = date(2023, 12, 31)
1063    ///     .at(7, 30, 0, 0)
1064    ///     .in_tz("America/New_York")?;
1065    /// assert_eq!(zdt.day_of_year(), 365);
1066    ///
1067    /// let zdt = date(2024, 12, 31)
1068    ///     .at(7, 30, 0, 0)
1069    ///     .in_tz("America/New_York")?;
1070    /// assert_eq!(zdt.day_of_year(), 366);
1071    ///
1072    /// # Ok::<(), Box<dyn std::error::Error>>(())
1073    /// ```
1074    #[inline]
1075    pub fn day_of_year(&self) -> i16 {
1076        self.date().day_of_year()
1077    }
1078
1079    /// Returns the ordinal day of the year that this zoned datetime resides
1080    /// in, but ignores leap years.
1081    ///
1082    /// That is, the range of possible values returned by this routine is
1083    /// `1..=365`, even if this date resides in a leap year. If this date is
1084    /// February 29, then this routine returns `None`.
1085    ///
1086    /// The value `365` always corresponds to the last day in the year,
1087    /// December 31, even for leap years.
1088    ///
1089    /// # Example
1090    ///
1091    /// ```
1092    /// use jiff::civil::date;
1093    ///
1094    /// let zdt = date(2006, 8, 24).at(7, 30, 0, 0).in_tz("America/New_York")?;
1095    /// assert_eq!(zdt.day_of_year_no_leap(), Some(236));
1096    ///
1097    /// let zdt = date(2023, 12, 31)
1098    ///     .at(7, 30, 0, 0)
1099    ///     .in_tz("America/New_York")?;
1100    /// assert_eq!(zdt.day_of_year_no_leap(), Some(365));
1101    ///
1102    /// let zdt = date(2024, 12, 31)
1103    ///     .at(7, 30, 0, 0)
1104    ///     .in_tz("America/New_York")?;
1105    /// assert_eq!(zdt.day_of_year_no_leap(), Some(365));
1106    ///
1107    /// let zdt = date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?;
1108    /// assert_eq!(zdt.day_of_year_no_leap(), None);
1109    ///
1110    /// # Ok::<(), Box<dyn std::error::Error>>(())
1111    /// ```
1112    #[inline]
1113    pub fn day_of_year_no_leap(&self) -> Option<i16> {
1114        self.date().day_of_year_no_leap()
1115    }
1116
1117    /// Returns the beginning of the day, corresponding to `00:00:00` civil
1118    /// time, that this datetime resides in.
1119    ///
1120    /// While in nearly all cases the time returned will be `00:00:00`, it is
1121    /// possible for the time to be different from midnight if there is a time
1122    /// zone transition at midnight.
1123    ///
1124    /// # Example
1125    ///
1126    /// ```
1127    /// use jiff::{civil::date, ZonedDateTime};
1128    ///
1129    /// let zdt = date(2015, 10, 18)
1130    ///     .at(12, 0, 0, 0)
1131    ///     .in_tz("America/New_York")?;
1132    /// assert_eq!(
1133    ///     zdt.start_of_day()?.to_string(),
1134    ///     "2015-10-18T00:00:00-04:00[America/New_York]",
1135    /// );
1136    ///
1137    /// # Ok::<(), Box<dyn std::error::Error>>(())
1138    /// ```
1139    ///
1140    /// # Example: start of day may not be midnight
1141    ///
1142    /// In some time zones, gap transitions may begin at midnight. This implies
1143    /// that `00:xx:yy` does not exist on a clock in that time zone for that
1144    /// day.
1145    ///
1146    /// ```
1147    /// use jiff::{civil::date, ZonedDateTime};
1148    ///
1149    /// let zdt = date(2015, 10, 18)
1150    ///     .at(12, 0, 0, 0)
1151    ///     .in_tz("America/Sao_Paulo")?;
1152    /// assert_eq!(
1153    ///     zdt.start_of_day()?.to_string(),
1154    ///     // not midnight!
1155    ///     "2015-10-18T01:00:00-02:00[America/Sao_Paulo]",
1156    /// );
1157    ///
1158    /// # Ok::<(), Box<dyn std::error::Error>>(())
1159    /// ```
1160    ///
1161    /// # Example: error because of overflow
1162    ///
1163    /// In some cases, it's possible for `ZonedDateTime` value to be able to
1164    /// represent an instant in time later in the day for a particular time
1165    /// zone, but not earlier in the day. This can only occur near the minimum
1166    /// datetime value supported by Jiff.
1167    ///
1168    /// ```
1169    /// use jiff::{
1170    ///     ZonedDateTime,
1171    ///     civil::date,
1172    ///     tz::{Offset, TimeZone},
1173    /// };
1174    ///
1175    /// // While -9999-01-03T04:00:00+25:59:59 is representable as a
1176    /// // ZonedDateTime value, the start of the corresponding day is not!
1177    /// let tz = TimeZone::fixed(Offset::MAX);
1178    /// let zdt =
1179    ///     date(-9999, 1, 3).at(4, 0, 0, 0).to_zoned_datetime(tz.clone())?;
1180    /// assert!(zdt.start_of_day().is_err());
1181    /// // The next day works fine since -9999-01-04T00:00:00+25:59:59 is
1182    /// // representable.
1183    /// let zdt = date(-9999, 1, 4).at(15, 0, 0, 0).to_zoned_datetime(tz)?;
1184    /// assert_eq!(
1185    ///     zdt.start_of_day()?.datetime(),
1186    ///     date(-9999, 1, 4).at(0, 0, 0, 0),
1187    /// );
1188    ///
1189    /// # Ok::<(), Box<dyn std::error::Error>>(())
1190    /// ```
1191    #[inline]
1192    pub fn start_of_day(&self) -> Result<ZonedDateTime, Error> {
1193        self.datetime()
1194            .start_of_day()
1195            .to_zoned_datetime(self.time_zone().clone())
1196    }
1197
1198    /// Returns the end of the day, corresponding to `23:59:59.999999999` civil
1199    /// time, that this datetime resides in.
1200    ///
1201    /// While in nearly all cases the time returned will be
1202    /// `23:59:59.999999999`, it is possible for the time to be different if
1203    /// there is a time zone transition covering that time.
1204    ///
1205    /// # Example
1206    ///
1207    /// ```
1208    /// use jiff::civil::date;
1209    ///
1210    /// let zdt = date(2024, 7, 3)
1211    ///     .at(7, 30, 10, 123_456_789)
1212    ///     .in_tz("America/New_York")?;
1213    /// assert_eq!(
1214    ///     zdt.end_of_day()?,
1215    ///     date(2024, 7, 3)
1216    ///         .at(23, 59, 59, 999_999_999)
1217    ///         .in_tz("America/New_York")?,
1218    /// );
1219    ///
1220    /// # Ok::<(), Box<dyn std::error::Error>>(())
1221    /// ```
1222    ///
1223    /// # Example: error because of overflow
1224    ///
1225    /// In some cases, it's possible for `ZonedDateTime` value to be able to
1226    /// represent an instant in time earlier in the day for a particular time
1227    /// zone, but not later in the day. This can only occur near the maximum
1228    /// datetime value supported by Jiff.
1229    ///
1230    /// ```
1231    /// use jiff::{
1232    ///     ZonedDateTime,
1233    ///     civil::date,
1234    ///     tz::{Offset, TimeZone},
1235    /// };
1236    ///
1237    /// // While 9999-12-30T01:30-04 is representable as a ZonedDateTime
1238    /// // value, the start of the corresponding day is not!
1239    /// let tz = TimeZone::get("America/New_York")?;
1240    /// let zdt = date(9999, 12, 30)
1241    ///     .at(1, 30, 0, 0)
1242    ///     .to_zoned_datetime(tz.clone())?;
1243    /// assert!(zdt.end_of_day().is_err());
1244    /// // The previous day works fine since 9999-12-29T23:59:59.999999999-04
1245    /// // is representable.
1246    /// let zdt = date(9999, 12, 29)
1247    ///     .at(1, 30, 0, 0)
1248    ///     .to_zoned_datetime(tz.clone())?;
1249    /// assert_eq!(
1250    ///     zdt.end_of_day()?,
1251    ///     date(9999, 12, 29)
1252    ///         .at(23, 59, 59, 999_999_999)
1253    ///         .in_tz("America/New_York")?,
1254    /// );
1255    ///
1256    /// # Ok::<(), Box<dyn std::error::Error>>(())
1257    /// ```
1258    #[inline]
1259    pub fn end_of_day(&self) -> Result<ZonedDateTime, Error> {
1260        let end_of_civil_day = self.datetime().end_of_day();
1261        let ambts = self.time_zone().to_ambiguous_timestamp(end_of_civil_day);
1262        // I'm not sure if there are any real world cases where this matters,
1263        // but this is basically the reverse of `compatible`, so we write
1264        // it out ourselves. Basically, if the last civil datetime is in a
1265        // gap, then we want the earlier instant since the later instant must
1266        // necessarily be in the next day. And if the last civil datetime is
1267        // in a fold, then we want the later instant since both the earlier
1268        // and later instants are in the same calendar day and the later one
1269        // must be, well, later. In contrast, compatible mode takes the later
1270        // instant in a gap and the earlier instant in a fold. So we flip that
1271        // here.
1272        let offset = match ambts.offset() {
1273            AmbiguousOffset::Unambiguous { offset } => offset,
1274            AmbiguousOffset::Gap { after, .. } => after,
1275            AmbiguousOffset::Fold { after, .. } => after,
1276        };
1277        offset
1278            .to_timestamp(end_of_civil_day)
1279            .map(|ts| ts.to_zoned_datetime(self.time_zone().clone()))
1280    }
1281
1282    /// Returns the first date of the month that this zoned datetime resides
1283    /// in.
1284    ///
1285    /// In most cases, the time in the zoned datetime returned remains
1286    /// unchanged. In some cases, the time may change if the time on the
1287    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1288    /// a precise instant in time) and the same clock time on the returned
1289    /// zoned datetime is ambiguous. In this case, the
1290    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1291    /// precise instant. If you want to use a different disambiguation
1292    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1293    /// datetime, then use [`DateTime::first_of_month`], then use
1294    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1295    /// disambiguation strategy.
1296    ///
1297    /// # Example
1298    ///
1299    /// ```
1300    /// use jiff::civil::date;
1301    ///
1302    /// let zdt = date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?;
1303    /// assert_eq!(
1304    ///     zdt.first_of_month()?,
1305    ///     date(2024, 2, 1).at(7, 30, 0, 0).in_tz("America/New_York")?,
1306    /// );
1307    ///
1308    /// # Ok::<(), Box<dyn std::error::Error>>(())
1309    /// ```
1310    #[inline]
1311    pub fn first_of_month(&self) -> Result<ZonedDateTime, Error> {
1312        self.datetime()
1313            .first_of_month()
1314            .to_zoned_datetime(self.time_zone().clone())
1315    }
1316
1317    /// Returns the last date of the month that this zoned datetime resides in.
1318    ///
1319    /// In most cases, the time in the zoned datetime returned remains
1320    /// unchanged. In some cases, the time may change if the time on the
1321    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1322    /// a precise instant in time) and the same clock time on the returned
1323    /// zoned datetime is ambiguous. In this case, the
1324    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1325    /// precise instant. If you want to use a different disambiguation
1326    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1327    /// datetime, then use [`DateTime::last_of_month`], then use
1328    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1329    /// disambiguation strategy.
1330    ///
1331    /// # Example
1332    ///
1333    /// ```
1334    /// use jiff::civil::date;
1335    ///
1336    /// let zdt = date(2024, 2, 5).at(7, 30, 0, 0).in_tz("America/New_York")?;
1337    /// assert_eq!(
1338    ///     zdt.last_of_month()?,
1339    ///     date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?,
1340    /// );
1341    ///
1342    /// # Ok::<(), Box<dyn std::error::Error>>(())
1343    /// ```
1344    #[inline]
1345    pub fn last_of_month(&self) -> Result<ZonedDateTime, Error> {
1346        self.datetime()
1347            .last_of_month()
1348            .to_zoned_datetime(self.time_zone().clone())
1349    }
1350
1351    /// Returns the ordinal number of the last day in the month in which this
1352    /// zoned datetime resides.
1353    ///
1354    /// This is phrased as "the ordinal number of the last day" instead of "the
1355    /// number of days" because some months may be missing days due to time
1356    /// zone transitions. However, this is extraordinarily rare.
1357    ///
1358    /// This is guaranteed to always return one of the following values,
1359    /// depending on the year and the month: 28, 29, 30 or 31.
1360    ///
1361    /// # Example
1362    ///
1363    /// ```
1364    /// use jiff::civil::date;
1365    ///
1366    /// let zdt = date(2024, 2, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1367    /// assert_eq!(zdt.days_in_month(), 29);
1368    ///
1369    /// let zdt = date(2023, 2, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1370    /// assert_eq!(zdt.days_in_month(), 28);
1371    ///
1372    /// let zdt = date(2024, 8, 15).at(7, 30, 0, 0).in_tz("America/New_York")?;
1373    /// assert_eq!(zdt.days_in_month(), 31);
1374    ///
1375    /// # Ok::<(), Box<dyn std::error::Error>>(())
1376    /// ```
1377    ///
1378    /// # Example: count of days in month
1379    ///
1380    /// In `Pacific/Apia`, December 2011 did not have a December 30. Instead,
1381    /// the calendar [skipped from December 29 right to December 31][samoa].
1382    ///
1383    /// If you really do need the count of days in a month in a time zone
1384    /// aware fashion, then it's possible to achieve through arithmetic:
1385    ///
1386    /// ```
1387    /// use jiff::{
1388    ///     RoundMode, ToSpan, Unit, ZonedDateTimeDifference, civil::date,
1389    /// };
1390    ///
1391    /// let first_of_month = date(2011, 12, 1).in_tz("Pacific/Apia")?;
1392    /// assert_eq!(first_of_month.days_in_month(), 31);
1393    /// let one_month_later = first_of_month.checked_add(1.month())?;
1394    ///
1395    /// let options = ZonedDateTimeDifference::new(&one_month_later)
1396    ///     .largest(Unit::Hour)
1397    ///     .smallest(Unit::Hour)
1398    ///     .mode(RoundMode::HalfExpand);
1399    /// let span = first_of_month.until(options)?;
1400    /// let days = ((span.get_hours() as f64) / 24.0).round() as i64;
1401    /// // Try the above in a different time zone, like America/New_York, and
1402    /// // you'll get 31 here.
1403    /// assert_eq!(days, 30);
1404    ///
1405    /// # Ok::<(), Box<dyn std::error::Error>>(())
1406    /// ```
1407    ///
1408    /// [samoa]: https://en.wikipedia.org/wiki/Time_in_Samoa#2011_time_zone_change
1409    #[inline]
1410    pub fn days_in_month(&self) -> i8 {
1411        self.date().days_in_month()
1412    }
1413
1414    /// Returns the first date of the year that this zoned datetime resides in.
1415    ///
1416    /// In most cases, the time in the zoned datetime returned remains
1417    /// unchanged. In some cases, the time may change if the time on the
1418    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1419    /// a precise instant in time) and the same clock time on the returned
1420    /// zoned datetime is ambiguous. In this case, the
1421    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1422    /// precise instant. If you want to use a different disambiguation
1423    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1424    /// datetime, then use [`DateTime::first_of_year`], then use
1425    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1426    /// disambiguation strategy.
1427    ///
1428    /// # Example
1429    ///
1430    /// ```
1431    /// use jiff::civil::date;
1432    ///
1433    /// let zdt = date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?;
1434    /// assert_eq!(
1435    ///     zdt.first_of_year()?,
1436    ///     date(2024, 1, 1).at(7, 30, 0, 0).in_tz("America/New_York")?,
1437    /// );
1438    ///
1439    /// # Ok::<(), Box<dyn std::error::Error>>(())
1440    /// ```
1441    #[inline]
1442    pub fn first_of_year(&self) -> Result<ZonedDateTime, Error> {
1443        self.datetime()
1444            .first_of_year()
1445            .to_zoned_datetime(self.time_zone().clone())
1446    }
1447
1448    /// Returns the last date of the year that this zoned datetime resides in.
1449    ///
1450    /// In most cases, the time in the zoned datetime returned remains
1451    /// unchanged. In some cases, the time may change if the time on the
1452    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1453    /// a precise instant in time) and the same clock time on the returned
1454    /// zoned datetime is ambiguous. In this case, the
1455    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1456    /// precise instant. If you want to use a different disambiguation
1457    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1458    /// datetime, then use [`DateTime::last_of_year`], then use
1459    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1460    /// disambiguation strategy.
1461    ///
1462    /// # Example
1463    ///
1464    /// ```
1465    /// use jiff::civil::date;
1466    ///
1467    /// let zdt = date(2024, 2, 5).at(7, 30, 0, 0).in_tz("America/New_York")?;
1468    /// assert_eq!(
1469    ///     zdt.last_of_year()?,
1470    ///     date(2024, 12, 31).at(7, 30, 0, 0).in_tz("America/New_York")?,
1471    /// );
1472    ///
1473    /// # Ok::<(), Box<dyn std::error::Error>>(())
1474    /// ```
1475    #[inline]
1476    pub fn last_of_year(&self) -> Result<ZonedDateTime, Error> {
1477        self.datetime()
1478            .last_of_year()
1479            .to_zoned_datetime(self.time_zone().clone())
1480    }
1481
1482    /// Returns the ordinal number of the last day in the year in which this
1483    /// zoned datetime resides.
1484    ///
1485    /// This is phrased as "the ordinal number of the last day" instead of "the
1486    /// number of days" because some years may be missing days due to time
1487    /// zone transitions. However, this is extraordinarily rare.
1488    ///
1489    /// This is guaranteed to always return either `365` or `366`.
1490    ///
1491    /// # Example
1492    ///
1493    /// ```
1494    /// use jiff::civil::date;
1495    ///
1496    /// let zdt = date(2024, 7, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1497    /// assert_eq!(zdt.days_in_year(), 366);
1498    ///
1499    /// let zdt = date(2023, 7, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1500    /// assert_eq!(zdt.days_in_year(), 365);
1501    ///
1502    /// # Ok::<(), Box<dyn std::error::Error>>(())
1503    /// ```
1504    #[inline]
1505    pub fn days_in_year(&self) -> i16 {
1506        self.date().days_in_year()
1507    }
1508
1509    /// Returns true if and only if the year in which this zoned datetime
1510    /// resides is a leap year.
1511    ///
1512    /// # Example
1513    ///
1514    /// ```
1515    /// use jiff::civil::date;
1516    ///
1517    /// let zdt = date(2024, 1, 1).at(7, 30, 0, 0).in_tz("America/New_York")?;
1518    /// assert!(zdt.in_leap_year());
1519    ///
1520    /// let zdt = date(2023, 12, 31)
1521    ///     .at(7, 30, 0, 0)
1522    ///     .in_tz("America/New_York")?;
1523    /// assert!(!zdt.in_leap_year());
1524    ///
1525    /// # Ok::<(), Box<dyn std::error::Error>>(())
1526    /// ```
1527    #[inline]
1528    pub fn in_leap_year(&self) -> bool {
1529        self.date().in_leap_year()
1530    }
1531
1532    /// Returns the zoned datetime with a date immediately following this one.
1533    ///
1534    /// In most cases, the time in the zoned datetime returned remains
1535    /// unchanged. In some cases, the time may change if the time on the
1536    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1537    /// a precise instant in time) and the same clock time on the returned
1538    /// zoned datetime is ambiguous. In this case, the
1539    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1540    /// precise instant. If you want to use a different disambiguation
1541    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1542    /// datetime, then use [`DateTime::tomorrow`], then use
1543    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1544    /// disambiguation strategy.
1545    ///
1546    /// # Errors
1547    ///
1548    /// This returns an error when one day following this zoned datetime would
1549    /// exceed the maximum `ZonedDateTime` value.
1550    ///
1551    /// # Example
1552    ///
1553    /// ```
1554    /// use jiff::{civil::date, Timestamp};
1555    ///
1556    /// let zdt = date(2024, 2, 28).at(7, 30, 0, 0).in_tz("America/New_York")?;
1557    /// assert_eq!(
1558    ///     zdt.tomorrow()?,
1559    ///     date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?,
1560    /// );
1561    ///
1562    /// // The max doesn't have a tomorrow.
1563    /// assert!(Timestamp::MAX.in_tz("America/New_York")?.tomorrow().is_err());
1564    ///
1565    /// # Ok::<(), Box<dyn std::error::Error>>(())
1566    /// ```
1567    ///
1568    /// # Example: ambiguous datetimes are automatically resolved
1569    ///
1570    /// ```
1571    /// use jiff::{civil::date, Timestamp};
1572    ///
1573    /// let zdt = date(2024, 3, 9).at(2, 30, 0, 0).in_tz("America/New_York")?;
1574    /// assert_eq!(
1575    ///     zdt.tomorrow()?,
1576    ///     date(2024, 3, 10).at(3, 30, 0, 0).in_tz("America/New_York")?,
1577    /// );
1578    ///
1579    /// # Ok::<(), Box<dyn std::error::Error>>(())
1580    /// ```
1581    #[inline]
1582    pub fn tomorrow(&self) -> Result<ZonedDateTime, Error> {
1583        self.datetime().tomorrow()?.to_zoned_datetime(self.time_zone().clone())
1584    }
1585
1586    /// Returns the zoned datetime with a date immediately preceding this one.
1587    ///
1588    /// In most cases, the time in the zoned datetime returned remains
1589    /// unchanged. In some cases, the time may change if the time on the
1590    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1591    /// a precise instant in time) and the same clock time on the returned
1592    /// zoned datetime is ambiguous. In this case, the
1593    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1594    /// precise instant. If you want to use a different disambiguation
1595    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1596    /// datetime, then use [`DateTime::yesterday`], then use
1597    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1598    /// disambiguation strategy.
1599    ///
1600    /// # Errors
1601    ///
1602    /// This returns an error when one day preceding this zoned datetime would
1603    /// be less than the minimum `ZonedDateTime` value.
1604    ///
1605    /// # Example
1606    ///
1607    /// ```
1608    /// use jiff::{civil::date, Timestamp};
1609    ///
1610    /// let zdt = date(2024, 3, 1).at(7, 30, 0, 0).in_tz("America/New_York")?;
1611    /// assert_eq!(
1612    ///     zdt.yesterday()?,
1613    ///     date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?,
1614    /// );
1615    ///
1616    /// // The min doesn't have a yesterday.
1617    /// assert!(
1618    ///     Timestamp::MIN
1619    ///         .in_tz("America/New_York")?
1620    ///         .yesterday()
1621    ///         .is_err()
1622    /// );
1623    ///
1624    /// # Ok::<(), Box<dyn std::error::Error>>(())
1625    /// ```
1626    ///
1627    /// # Example: ambiguous datetimes are automatically resolved
1628    ///
1629    /// ```
1630    /// use jiff::{civil::date, Timestamp};
1631    ///
1632    /// let zdt = date(2024, 11, 4).at(1, 30, 0, 0).in_tz("America/New_York")?;
1633    /// assert_eq!(
1634    ///     zdt.yesterday()?.to_string(),
1635    ///     // Consistent with the "compatible" disambiguation strategy, the
1636    ///     // "first" 1 o'clock hour is selected. You can tell this because
1637    ///     // the offset is -04, which corresponds to DST time in New York.
1638    ///     // The second 1 o'clock hour would have offset -05.
1639    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
1640    /// );
1641    ///
1642    /// # Ok::<(), Box<dyn std::error::Error>>(())
1643    /// ```
1644    #[inline]
1645    pub fn yesterday(&self) -> Result<ZonedDateTime, Error> {
1646        self.datetime()
1647            .yesterday()?
1648            .to_zoned_datetime(self.time_zone().clone())
1649    }
1650
1651    /// Returns the "nth" weekday from the beginning or end of the month in
1652    /// which this zoned datetime resides.
1653    ///
1654    /// The `nth` parameter can be positive or negative. A positive value
1655    /// computes the "nth" weekday from the beginning of the month. A negative
1656    /// value computes the "nth" weekday from the end of the month. So for
1657    /// example, use `-1` to "find the last weekday" in this date's month.
1658    ///
1659    /// In most cases, the time in the zoned datetime returned remains
1660    /// unchanged. In some cases, the time may change if the time on the
1661    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1662    /// a precise instant in time) and the same clock time on the returned
1663    /// zoned datetime is ambiguous. In this case, the
1664    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1665    /// precise instant. If you want to use a different disambiguation
1666    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1667    /// datetime, then use [`DateTime::nth_weekday_of_month`], then use
1668    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1669    /// disambiguation strategy.
1670    ///
1671    /// # Errors
1672    ///
1673    /// This returns an error when `nth` is `0`, or if it is `5` or `-5` and
1674    /// there is no 5th weekday from the beginning or end of the month. This
1675    /// could also return an error if the corresponding datetime could not be
1676    /// represented as an instant for this `ZonedDateTime`'s time zone. (This
1677    /// can only happen close the boundaries of an [`Timestamp`].)
1678    ///
1679    /// # Example
1680    ///
1681    /// This shows how to get the nth weekday in a month, starting from the
1682    /// beginning of the month:
1683    ///
1684    /// ```
1685    /// use jiff::civil::{Weekday, date};
1686    ///
1687    /// let zdt = date(2017, 3, 1).at(7, 30, 0, 0).in_tz("America/New_York")?;
1688    /// let second_friday = zdt.nth_weekday_of_month(2, Weekday::Friday)?;
1689    /// assert_eq!(
1690    ///     second_friday,
1691    ///     date(2017, 3, 10).at(7, 30, 0, 0).in_tz("America/New_York")?,
1692    /// );
1693    ///
1694    /// # Ok::<(), Box<dyn std::error::Error>>(())
1695    /// ```
1696    ///
1697    /// This shows how to do the reverse of the above. That is, the nth _last_
1698    /// weekday in a month:
1699    ///
1700    /// ```
1701    /// use jiff::civil::{Weekday, date};
1702    ///
1703    /// let zdt = date(2024, 3, 1).at(7, 30, 0, 0).in_tz("America/New_York")?;
1704    /// let last_thursday = zdt.nth_weekday_of_month(-1, Weekday::Thursday)?;
1705    /// assert_eq!(
1706    ///     last_thursday,
1707    ///     date(2024, 3, 28).at(7, 30, 0, 0).in_tz("America/New_York")?,
1708    /// );
1709    ///
1710    /// let second_last_thursday = zdt.nth_weekday_of_month(
1711    ///     -2,
1712    ///     Weekday::Thursday,
1713    /// )?;
1714    /// assert_eq!(
1715    ///     second_last_thursday,
1716    ///     date(2024, 3, 21).at(7, 30, 0, 0).in_tz("America/New_York")?,
1717    /// );
1718    ///
1719    /// # Ok::<(), Box<dyn std::error::Error>>(())
1720    /// ```
1721    ///
1722    /// This routine can return an error if there isn't an `nth` weekday
1723    /// for this month. For example, March 2024 only has 4 Mondays:
1724    ///
1725    /// ```
1726    /// use jiff::civil::{Weekday, date};
1727    ///
1728    /// let zdt = date(2024, 3, 25).at(7, 30, 0, 0).in_tz("America/New_York")?;
1729    /// let fourth_monday = zdt.nth_weekday_of_month(4, Weekday::Monday)?;
1730    /// assert_eq!(
1731    ///     fourth_monday,
1732    ///     date(2024, 3, 25).at(7, 30, 0, 0).in_tz("America/New_York")?,
1733    /// );
1734    /// // There is no 5th Monday.
1735    /// assert!(zdt.nth_weekday_of_month(5, Weekday::Monday).is_err());
1736    /// // Same goes for counting backwards.
1737    /// assert!(zdt.nth_weekday_of_month(-5, Weekday::Monday).is_err());
1738    ///
1739    /// # Ok::<(), Box<dyn std::error::Error>>(())
1740    /// ```
1741    #[inline]
1742    pub fn nth_weekday_of_month(
1743        &self,
1744        nth: i8,
1745        weekday: Weekday,
1746    ) -> Result<ZonedDateTime, Error> {
1747        self.datetime()
1748            .nth_weekday_of_month(nth, weekday)?
1749            .to_zoned_datetime(self.time_zone().clone())
1750    }
1751
1752    /// Returns the "nth" weekday from this zoned datetime, not including
1753    /// itself.
1754    ///
1755    /// The `nth` parameter can be positive or negative. A positive value
1756    /// computes the "nth" weekday starting at the day after this date and
1757    /// going forwards in time. A negative value computes the "nth" weekday
1758    /// starting at the day before this date and going backwards in time.
1759    ///
1760    /// For example, if this zoned datetime's weekday is a Sunday and the first
1761    /// Sunday is asked for (that is, `zdt.nth_weekday(1, Weekday::Sunday)`),
1762    /// then the result is a week from this zoned datetime corresponding to the
1763    /// following Sunday.
1764    ///
1765    /// In most cases, the time in the zoned datetime returned remains
1766    /// unchanged. In some cases, the time may change if the time on the
1767    /// previous date was unambiguous (always true, since a `ZonedDateTime` is
1768    /// a precise instant in time) and the same clock time on the returned
1769    /// zoned datetime is ambiguous. In this case, the
1770    /// [`Disambiguation::Compatible`] strategy will be used to turn it into a
1771    /// precise instant. If you want to use a different disambiguation
1772    /// strategy, then use [`ZonedDateTime::datetime`] to get the civil
1773    /// datetime, then use [`DateTime::nth_weekday`], then use
1774    /// [`TimeZone::to_ambiguous_zoned_datetime`] and apply your preferred
1775    /// disambiguation strategy.
1776    ///
1777    /// # Errors
1778    ///
1779    /// This returns an error when `nth` is `0`, or if it would otherwise
1780    /// result in a date that overflows the minimum/maximum values of
1781    /// `ZonedDateTime`.
1782    ///
1783    /// # Example
1784    ///
1785    /// This example shows how to find the "nth" weekday going forwards in
1786    /// time:
1787    ///
1788    /// ```
1789    /// use jiff::civil::{Weekday, date};
1790    ///
1791    /// // Use a Sunday in March as our start date.
1792    /// let zdt = date(2024, 3, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1793    /// assert_eq!(zdt.weekday(), Weekday::Sunday);
1794    ///
1795    /// // The first next Monday is tomorrow!
1796    /// let next_monday = zdt.nth_weekday(1, Weekday::Monday)?;
1797    /// assert_eq!(
1798    ///     next_monday,
1799    ///     date(2024, 3, 11).at(7, 30, 0, 0).in_tz("America/New_York")?,
1800    /// );
1801    ///
1802    /// // But the next Sunday is a week away, because this doesn't
1803    /// // include the current weekday.
1804    /// let next_sunday = zdt.nth_weekday(1, Weekday::Sunday)?;
1805    /// assert_eq!(
1806    ///     next_sunday,
1807    ///     date(2024, 3, 17).at(7, 30, 0, 0).in_tz("America/New_York")?,
1808    /// );
1809    ///
1810    /// // "not this Thursday, but next Thursday"
1811    /// let next_next_thursday = zdt.nth_weekday(2, Weekday::Thursday)?;
1812    /// assert_eq!(
1813    ///     next_next_thursday,
1814    ///     date(2024, 3, 21).at(7, 30, 0, 0).in_tz("America/New_York")?,
1815    /// );
1816    ///
1817    /// # Ok::<(), Box<dyn std::error::Error>>(())
1818    /// ```
1819    ///
1820    /// This example shows how to find the "nth" weekday going backwards in
1821    /// time:
1822    ///
1823    /// ```
1824    /// use jiff::civil::{Weekday, date};
1825    ///
1826    /// // Use a Sunday in March as our start date.
1827    /// let zdt = date(2024, 3, 10).at(7, 30, 0, 0).in_tz("America/New_York")?;
1828    /// assert_eq!(zdt.weekday(), Weekday::Sunday);
1829    ///
1830    /// // "last Saturday" was yesterday!
1831    /// let last_saturday = zdt.nth_weekday(-1, Weekday::Saturday)?;
1832    /// assert_eq!(
1833    ///     last_saturday,
1834    ///     date(2024, 3, 9).at(7, 30, 0, 0).in_tz("America/New_York")?,
1835    /// );
1836    ///
1837    /// // "last Sunday" was a week ago.
1838    /// let last_sunday = zdt.nth_weekday(-1, Weekday::Sunday)?;
1839    /// assert_eq!(
1840    ///     last_sunday,
1841    ///     date(2024, 3, 3).at(7, 30, 0, 0).in_tz("America/New_York")?,
1842    /// );
1843    ///
1844    /// // "not last Thursday, but the one before"
1845    /// let prev_prev_thursday = zdt.nth_weekday(-2, Weekday::Thursday)?;
1846    /// assert_eq!(
1847    ///     prev_prev_thursday,
1848    ///     date(2024, 2, 29).at(7, 30, 0, 0).in_tz("America/New_York")?,
1849    /// );
1850    ///
1851    /// # Ok::<(), Box<dyn std::error::Error>>(())
1852    /// ```
1853    ///
1854    /// This example shows that overflow results in an error in either
1855    /// direction:
1856    ///
1857    /// ```
1858    /// use jiff::{civil::Weekday, Timestamp};
1859    ///
1860    /// let zdt = Timestamp::MAX.in_tz("America/New_York")?;
1861    /// assert_eq!(zdt.weekday(), Weekday::Thursday);
1862    /// assert!(zdt.nth_weekday(1, Weekday::Saturday).is_err());
1863    ///
1864    /// let zdt = Timestamp::MIN.in_tz("America/New_York")?;
1865    /// assert_eq!(zdt.weekday(), Weekday::Monday);
1866    /// assert!(zdt.nth_weekday(-1, Weekday::Sunday).is_err());
1867    ///
1868    /// # Ok::<(), Box<dyn std::error::Error>>(())
1869    /// ```
1870    ///
1871    /// # Example: getting the start of the week
1872    ///
1873    /// Given a date, one can use `nth_weekday` to determine the start of the
1874    /// week in which the date resides in. This might vary based on whether
1875    /// the weeks start on Sunday or Monday. This example shows how to handle
1876    /// both.
1877    ///
1878    /// ```
1879    /// use jiff::civil::{Weekday, date};
1880    ///
1881    /// let zdt = date(2024, 3, 15).at(7, 30, 0, 0).in_tz("America/New_York")?;
1882    /// // For weeks starting with Sunday.
1883    /// let start_of_week = zdt.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
1884    /// assert_eq!(
1885    ///     start_of_week,
1886    ///     date(2024, 3, 10).at(7, 30, 0, 0).in_tz("America/New_York")?,
1887    /// );
1888    /// // For weeks starting with Monday.
1889    /// let start_of_week = zdt.tomorrow()?.nth_weekday(-1, Weekday::Monday)?;
1890    /// assert_eq!(
1891    ///     start_of_week,
1892    ///     date(2024, 3, 11).at(7, 30, 0, 0).in_tz("America/New_York")?,
1893    /// );
1894    ///
1895    /// # Ok::<(), Box<dyn std::error::Error>>(())
1896    /// ```
1897    ///
1898    /// In the above example, we first get the date after the current one
1899    /// because `nth_weekday` does not consider itself when counting. This
1900    /// works as expected even at the boundaries of a week:
1901    ///
1902    /// ```
1903    /// use jiff::civil::{Time, Weekday, date};
1904    ///
1905    /// // The start of the week.
1906    /// let zdt = date(2024, 3, 10).at(0, 0, 0, 0).in_tz("America/New_York")?;
1907    /// let start_of_week = zdt.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
1908    /// assert_eq!(
1909    ///     start_of_week,
1910    ///     date(2024, 3, 10).at(0, 0, 0, 0).in_tz("America/New_York")?,
1911    /// );
1912    /// // The end of the week.
1913    /// let zdt = date(2024, 3, 16)
1914    ///     .at(23, 59, 59, 999_999_999)
1915    ///     .in_tz("America/New_York")?;
1916    /// let start_of_week = zdt
1917    ///     .tomorrow()?
1918    ///     .nth_weekday(-1, Weekday::Sunday)?
1919    ///     .with().time(Time::midnight()).build()?;
1920    /// assert_eq!(
1921    ///     start_of_week,
1922    ///     date(2024, 3, 10).at(0, 0, 0, 0).in_tz("America/New_York")?,
1923    /// );
1924    ///
1925    /// # Ok::<(), Box<dyn std::error::Error>>(())
1926    /// ```
1927    #[inline]
1928    pub fn nth_weekday(
1929        &self,
1930        nth: i32,
1931        weekday: Weekday,
1932    ) -> Result<ZonedDateTime, Error> {
1933        self.datetime()
1934            .nth_weekday(nth, weekday)?
1935            .to_zoned_datetime(self.time_zone().clone())
1936    }
1937
1938    /// Returns the precise instant in time referred to by this zoned datetime.
1939    ///
1940    /// # Example
1941    ///
1942    /// ```
1943    /// use jiff::civil::date;
1944    ///
1945    /// let zdt = date(2024, 3, 14)
1946    ///     .at(18, 45, 0, 0)
1947    ///     .in_tz("America/New_York")?;
1948    /// assert_eq!(zdt.timestamp().as_second(), 1_710_456_300);
1949    ///
1950    /// # Ok::<(), Box<dyn std::error::Error>>(())
1951    /// ```
1952    #[inline]
1953    pub fn timestamp(&self) -> Timestamp {
1954        self.inner.timestamp
1955    }
1956
1957    /// Returns the civil datetime component of this zoned datetime.
1958    ///
1959    /// # Example
1960    ///
1961    /// ```
1962    /// use jiff::civil::date;
1963    ///
1964    /// let zdt = date(2024, 3, 14)
1965    ///     .at(18, 45, 0, 0)
1966    ///     .in_tz("America/New_York")?;
1967    /// assert_eq!(zdt.datetime(), date(2024, 3, 14).at(18, 45, 0, 0));
1968    ///
1969    /// # Ok::<(), Box<dyn std::error::Error>>(())
1970    /// ```
1971    #[inline]
1972    pub fn datetime(&self) -> DateTime {
1973        self.inner.datetime
1974    }
1975
1976    /// Returns the civil date component of this zoned datetime.
1977    ///
1978    /// # Example
1979    ///
1980    /// ```
1981    /// use jiff::civil::date;
1982    ///
1983    /// let zdt = date(2024, 3, 14)
1984    ///     .at(18, 45, 0, 0)
1985    ///     .in_tz("America/New_York")?;
1986    /// assert_eq!(zdt.date(), date(2024, 3, 14));
1987    ///
1988    /// # Ok::<(), Box<dyn std::error::Error>>(())
1989    /// ```
1990    #[inline]
1991    pub fn date(&self) -> Date {
1992        self.datetime().date()
1993    }
1994
1995    /// Returns the civil time component of this zoned datetime.
1996    ///
1997    /// # Example
1998    ///
1999    /// ```
2000    /// use jiff::civil::{date, time};
2001    ///
2002    /// let zdt = date(2024, 3, 14)
2003    ///     .at(18, 45, 0, 0)
2004    ///     .in_tz("America/New_York")?;
2005    /// assert_eq!(zdt.time(), time(18, 45, 0, 0));
2006    ///
2007    /// # Ok::<(), Box<dyn std::error::Error>>(())
2008    /// ```
2009    #[inline]
2010    pub fn time(&self) -> Time {
2011        self.datetime().time()
2012    }
2013
2014    /// Construct a civil [ISO 8601 week date] from this zoned datetime.
2015    ///
2016    /// The [`ISOWeekDate`] type describes itself in more detail, but in
2017    /// brief, the ISO week date calendar system eschews months in favor of
2018    /// weeks.
2019    ///
2020    /// This routine is equivalent to
2021    /// [`ISOWeekDate::from_date(zdt.date())`](ISOWeekDate::from_date).
2022    ///
2023    /// [ISO 8601 week date]: https://en.wikipedia.org/wiki/ISO_week_date
2024    ///
2025    /// # Example
2026    ///
2027    /// This shows a number of examples demonstrating the conversion from a
2028    /// Gregorian date to an ISO 8601 week date:
2029    ///
2030    /// ```
2031    /// use jiff::civil::{Date, Time, Weekday, date};
2032    ///
2033    /// let zdt = date(1995, 1, 1).at(18, 45, 0, 0).in_tz("America/New_York")?;
2034    /// let weekdate = zdt.iso_week_date();
2035    /// assert_eq!(weekdate.year(), 1994);
2036    /// assert_eq!(weekdate.week(), 52);
2037    /// assert_eq!(weekdate.weekday(), Weekday::Sunday);
2038    ///
2039    /// let zdt = date(1996, 12, 31)
2040    ///     .at(18, 45, 0, 0)
2041    ///     .in_tz("America/New_York")?;
2042    /// let weekdate = zdt.iso_week_date();
2043    /// assert_eq!(weekdate.year(), 1997);
2044    /// assert_eq!(weekdate.week(), 1);
2045    /// assert_eq!(weekdate.weekday(), Weekday::Tuesday);
2046    ///
2047    /// let zdt = date(2019, 12, 30)
2048    ///     .at(18, 45, 0, 0)
2049    ///     .in_tz("America/New_York")?;
2050    /// let weekdate = zdt.iso_week_date();
2051    /// assert_eq!(weekdate.year(), 2020);
2052    /// assert_eq!(weekdate.week(), 1);
2053    /// assert_eq!(weekdate.weekday(), Weekday::Monday);
2054    ///
2055    /// let zdt = date(2024, 3, 9).at(18, 45, 0, 0).in_tz("America/New_York")?;
2056    /// let weekdate = zdt.iso_week_date();
2057    /// assert_eq!(weekdate.year(), 2024);
2058    /// assert_eq!(weekdate.week(), 10);
2059    /// assert_eq!(weekdate.weekday(), Weekday::Saturday);
2060    ///
2061    /// # Ok::<(), Box<dyn std::error::Error>>(())
2062    /// ```
2063    #[inline]
2064    pub fn iso_week_date(&self) -> ISOWeekDate {
2065        self.date().iso_week_date()
2066    }
2067
2068    /// Returns the time zone offset of this zoned datetime.
2069    ///
2070    /// # Example
2071    ///
2072    /// ```
2073    /// use jiff::civil::date;
2074    ///
2075    /// let zdt = date(2024, 2, 14)
2076    ///     .at(18, 45, 0, 0)
2077    ///     .in_tz("America/New_York")?;
2078    /// // -05 because New York is in "standard" time at this point.
2079    /// assert_eq!(zdt.offset(), jiff::tz::offset(-5));
2080    ///
2081    /// let zdt = date(2024, 7, 14)
2082    ///     .at(18, 45, 0, 0)
2083    ///     .in_tz("America/New_York")?;
2084    /// // But we get -04 once "summer" or "daylight saving time" starts.
2085    /// assert_eq!(zdt.offset(), jiff::tz::offset(-4));
2086    ///
2087    /// # Ok::<(), Box<dyn std::error::Error>>(())
2088    /// ```
2089    #[inline]
2090    pub fn offset(&self) -> Offset {
2091        self.inner.offset
2092    }
2093
2094    /// Add the given span of time to this zoned datetime. If the sum would
2095    /// overflow the minimum or maximum zoned datetime values, then an error is
2096    /// returned.
2097    ///
2098    /// This operation accepts three different duration types: [`Span`],
2099    /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
2100    /// `From` trait implementations for the [`ZonedDateTimeArithmetic`] type.
2101    ///
2102    /// # Properties
2103    ///
2104    /// This routine is _not_ reversible because some additions may
2105    /// be ambiguous. For example, adding `1 month` to the zoned
2106    /// datetime `2024-03-31T00:00:00[America/New_York]` will produce
2107    /// `2024-04-30T00:00:00[America/New_York]` since April has
2108    /// only 30 days in a month. Moreover, subtracting `1 month`
2109    /// from `2024-04-30T00:00:00[America/New_York]` will produce
2110    /// `2024-03-30T00:00:00[America/New_York]`, which is not the date we
2111    /// started with.
2112    ///
2113    /// A similar argument applies for days, since with zoned datetimes,
2114    /// different days can be different lengths.
2115    ///
2116    /// If spans of time are limited to units of hours (or less), then this
2117    /// routine _is_ reversible. This also implies that all operations with a
2118    /// [`SignedDuration`] or a [`std::time::Duration`] are reversible.
2119    ///
2120    /// # Errors
2121    ///
2122    /// If the span added to this zoned datetime would result in a zoned
2123    /// datetime that exceeds the range of a `ZonedDateTime`, then this will
2124    /// return an error.
2125    ///
2126    /// # Example
2127    ///
2128    /// This shows a few examples of adding spans of time to various zoned
2129    /// datetimes. We make use of the [`ToSpan`](crate::ToSpan) trait for
2130    /// convenient creation of spans.
2131    ///
2132    /// ```
2133    /// use jiff::{civil::date, ToSpan};
2134    ///
2135    /// let zdt = date(1995, 12, 7)
2136    ///     .at(3, 24, 30, 3_500)
2137    ///     .in_tz("America/New_York")?;
2138    /// let got = zdt.checked_add(20.years().months(4).nanoseconds(500))?;
2139    /// assert_eq!(
2140    ///     got,
2141    ///     date(2016, 4, 7).at(3, 24, 30, 4_000).in_tz("America/New_York")?,
2142    /// );
2143    ///
2144    /// let zdt = date(2019, 1, 31)
2145    ///     .at(15, 30, 0, 0)
2146    ///     .in_tz("America/New_York")?;
2147    /// let got = zdt.checked_add(1.months())?;
2148    /// assert_eq!(
2149    ///     got,
2150    ///     date(2019, 2, 28).at(15, 30, 0, 0).in_tz("America/New_York")?,
2151    /// );
2152    ///
2153    /// # Ok::<(), Box<dyn std::error::Error>>(())
2154    /// ```
2155    ///
2156    /// # Example: available via addition operator
2157    ///
2158    /// This routine can be used via the `+` operator. Note though that if it
2159    /// fails, it will result in a panic. Note that we use `&zdt + ...` instead
2160    /// of `zdt + ...` since `Add` is implemented for `&ZonedDateTime` and not
2161    /// `ZonedDateTime`. This is because `ZonedDateTime` is not `Copy`.
2162    ///
2163    /// ```
2164    /// use jiff::{civil::date, ToSpan};
2165    ///
2166    /// let zdt = date(1995, 12, 7)
2167    ///     .at(3, 24, 30, 3_500)
2168    ///     .in_tz("America/New_York")?;
2169    /// let got = &zdt + 20.years().months(4).nanoseconds(500);
2170    /// assert_eq!(
2171    ///     got,
2172    ///     date(2016, 4, 7).at(3, 24, 30, 4_000).in_tz("America/New_York")?,
2173    /// );
2174    ///
2175    /// # Ok::<(), Box<dyn std::error::Error>>(())
2176    /// ```
2177    ///
2178    /// # Example: zone aware arithmetic
2179    ///
2180    /// This example demonstrates the difference between "add 1 day" and
2181    /// "add 24 hours." In the former case, 1 day might not correspond to 24
2182    /// hours if there is a time zone transition in the intervening period.
2183    /// However, adding 24 hours always means adding exactly 24 hours.
2184    ///
2185    /// ```
2186    /// use jiff::{civil::date, ToSpan};
2187    ///
2188    /// let zdt = date(2024, 3, 10).at(0, 0, 0, 0).in_tz("America/New_York")?;
2189    ///
2190    /// let one_day_later = zdt.checked_add(1.day())?;
2191    /// assert_eq!(
2192    ///     one_day_later.to_string(),
2193    ///     "2024-03-11T00:00:00-04:00[America/New_York]",
2194    /// );
2195    ///
2196    /// let twenty_four_hours_later = zdt.checked_add(24.hours())?;
2197    /// assert_eq!(
2198    ///     twenty_four_hours_later.to_string(),
2199    ///     "2024-03-11T01:00:00-04:00[America/New_York]",
2200    /// );
2201    ///
2202    /// # Ok::<(), Box<dyn std::error::Error>>(())
2203    /// ```
2204    ///
2205    /// # Example: automatic disambiguation
2206    ///
2207    /// This example demonstrates what happens when adding a span
2208    /// of time results in an ambiguous zoned datetime. Zone aware
2209    /// arithmetic uses automatic disambiguation corresponding to the
2210    /// [`Disambiguation::Compatible`]
2211    /// strategy for resolving an ambiguous datetime to a precise instant.
2212    /// For example, in the case below, there is a gap in the clocks for 1
2213    /// hour starting at `2024-03-10 02:00:00` in `America/New_York`. The
2214    /// "compatible" strategy chooses the later time in a gap:.
2215    ///
2216    /// ```
2217    /// use jiff::{civil::date, ToSpan};
2218    ///
2219    /// let zdt = date(2024, 3, 9).at(2, 30, 0, 0).in_tz("America/New_York")?;
2220    /// let one_day_later = zdt.checked_add(1.day())?;
2221    /// assert_eq!(
2222    ///     one_day_later.to_string(),
2223    ///     "2024-03-10T03:30:00-04:00[America/New_York]",
2224    /// );
2225    ///
2226    /// # Ok::<(), Box<dyn std::error::Error>>(())
2227    /// ```
2228    ///
2229    /// And this example demonstrates the "compatible" strategy when arithmetic
2230    /// results in an ambiguous datetime in a fold. In this case, we make use
2231    /// of the fact that the 1 o'clock hour was repeated on `2024-11-03`.
2232    ///
2233    /// ```
2234    /// use jiff::{civil::date, ToSpan};
2235    ///
2236    /// let zdt = date(2024, 11, 2).at(1, 30, 0, 0).in_tz("America/New_York")?;
2237    /// let one_day_later = zdt.checked_add(1.day())?;
2238    /// assert_eq!(
2239    ///     one_day_later.to_string(),
2240    ///     // This corresponds to the first iteration of the 1 o'clock hour,
2241    ///     // i.e., when DST is still in effect. It's the earlier time.
2242    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
2243    /// );
2244    ///
2245    /// # Ok::<(), Box<dyn std::error::Error>>(())
2246    /// ```
2247    ///
2248    /// # Example: negative spans are supported
2249    ///
2250    /// ```
2251    /// use jiff::{civil::date, ToSpan};
2252    ///
2253    /// let zdt = date(2024, 3, 31)
2254    ///     .at(19, 5, 59, 999_999_999)
2255    ///     .in_tz("America/New_York")?;
2256    /// assert_eq!(
2257    ///     zdt.checked_add(-1.months())?,
2258    ///     date(2024, 2, 29).
2259    ///         at(19, 5, 59, 999_999_999)
2260    ///         .in_tz("America/New_York")?,
2261    /// );
2262    ///
2263    /// # Ok::<(), Box<dyn std::error::Error>>(())
2264    /// ```
2265    ///
2266    /// # Example: error on overflow
2267    ///
2268    /// ```
2269    /// use jiff::{civil::date, ToSpan};
2270    ///
2271    /// let zdt = date(2024, 3, 31)
2272    ///     .at(13, 13, 13, 13)
2273    ///     .in_tz("America/New_York")?;
2274    /// assert!(zdt.checked_add(9000.years()).is_err());
2275    /// assert!(zdt.checked_add(-19000.years()).is_err());
2276    ///
2277    /// # Ok::<(), Box<dyn std::error::Error>>(())
2278    /// ```
2279    ///
2280    /// # Example: adding absolute durations
2281    ///
2282    /// This shows how to add signed and unsigned absolute durations to a
2283    /// `ZonedDateTime`.
2284    ///
2285    /// ```
2286    /// use std::time::Duration;
2287    ///
2288    /// use jiff::{civil::date, SignedDuration};
2289    ///
2290    /// let zdt = date(2024, 2, 29).at(0, 0, 0, 0).in_tz("America/New_York")?;
2291    ///
2292    /// let dur = SignedDuration::from_hours(25);
2293    /// assert_eq!(
2294    ///     zdt.checked_add(dur)?,
2295    ///     date(2024, 3, 1).at(1, 0, 0, 0).in_tz("America/New_York")?,
2296    /// );
2297    /// assert_eq!(
2298    ///     zdt.checked_add(-dur)?,
2299    ///     date(2024, 2, 27).at(23, 0, 0, 0).in_tz("America/New_York")?,
2300    /// );
2301    ///
2302    /// let dur = Duration::from_secs(25 * 60 * 60);
2303    /// assert_eq!(
2304    ///     zdt.checked_add(dur)?,
2305    ///     date(2024, 3, 1).at(1, 0, 0, 0).in_tz("America/New_York")?,
2306    /// );
2307    /// // One cannot negate an unsigned duration,
2308    /// // but you can subtract it!
2309    /// assert_eq!(
2310    ///     zdt.checked_sub(dur)?,
2311    ///     date(2024, 2, 27).at(23, 0, 0, 0).in_tz("America/New_York")?,
2312    /// );
2313    ///
2314    /// # Ok::<(), Box<dyn std::error::Error>>(())
2315    /// ```
2316    #[inline]
2317    pub fn checked_add<A: Into<ZonedDateTimeArithmetic>>(
2318        &self,
2319        duration: A,
2320    ) -> Result<ZonedDateTime, Error> {
2321        self.clone().checked_add_consuming(duration)
2322    }
2323
2324    /// Like `checked_add`, but consumes `self` and thus avoids cloning
2325    /// the `TimeZone`.
2326    ///
2327    /// This is currently only accessible via the `impl Add<...> for
2328    /// ZonedDateTime` trait implementation.
2329    #[inline]
2330    fn checked_add_consuming<A: Into<ZonedDateTimeArithmetic>>(
2331        self,
2332        duration: A,
2333    ) -> Result<ZonedDateTime, Error> {
2334        let duration: ZonedDateTimeArithmetic = duration.into();
2335        duration.checked_add(self)
2336    }
2337
2338    #[inline]
2339    fn checked_add_span(self, span: &Span) -> Result<ZonedDateTime, Error> {
2340        let span_calendar = span.only_calendar();
2341        // If our duration only consists of "time" (hours, minutes, etc), then
2342        // we can short-circuit and do timestamp math. This also avoids dealing
2343        // with ambiguity and time zone bullshit.
2344        if span_calendar.is_zero() {
2345            return self
2346                .timestamp()
2347                .checked_add(span)
2348                .map(|ts| ts.to_zoned_datetime(self.time_zone().clone()))
2349                .context(E::AddTimestamp);
2350        }
2351        let span_time = span.only_time();
2352        let dt = self
2353            .datetime()
2354            .checked_add(span_calendar)
2355            .context(E::AddDateTime)?;
2356
2357        let tz = self.inner.time_zone;
2358        // `DateTime::to_zoned_datetime` uses the same "compatible"
2359        // disambiguation, but skips the second offset lookup (in
2360        // `ts.to_zoned_datetime()` below) in the unambiguous case.
2361        if span_time.is_zero() {
2362            return dt
2363                .to_zoned_datetime(tz)
2364                .context(E::ConvertDateTimeToTimestamp);
2365        }
2366        let mut ts = tz
2367            .to_ambiguous_timestamp(dt)
2368            .compatible()
2369            .context(E::ConvertDateTimeToTimestamp)?;
2370        ts = ts.checked_add(span_time).context(E::AddTimestamp)?;
2371        Ok(ts.to_zoned_datetime(tz))
2372    }
2373
2374    #[inline]
2375    fn checked_add_duration(
2376        self,
2377        duration: SignedDuration,
2378    ) -> Result<ZonedDateTime, Error> {
2379        self.timestamp()
2380            .checked_add(duration)
2381            .map(|ts| ts.to_zoned_datetime(self.inner.time_zone))
2382    }
2383
2384    /// This routine is identical to [`ZonedDateTime::checked_add`] with the
2385    /// duration negated.
2386    ///
2387    /// # Errors
2388    ///
2389    /// This has the same error conditions as [`ZonedDateTime::checked_add`].
2390    ///
2391    /// # Example
2392    ///
2393    /// This routine can be used via the `-` operator. Note though that if it
2394    /// fails, it will result in a panic. Note that we use `&zdt - ...` instead
2395    /// of `zdt - ...` since `Sub` is implemented for `&ZonedDateTime` and not
2396    /// `ZonedDateTime`. This is because `ZonedDateTime` is not `Copy`.
2397    ///
2398    /// ```
2399    /// use std::time::Duration;
2400    ///
2401    /// use jiff::{civil::date, SignedDuration, ToSpan};
2402    ///
2403    /// let zdt = date(1995, 12, 7)
2404    ///     .at(3, 24, 30, 3_500)
2405    ///     .in_tz("America/New_York")?;
2406    /// let got = &zdt - 20.years().months(4).nanoseconds(500);
2407    /// assert_eq!(
2408    ///     got,
2409    ///     date(1975, 8, 7).at(3, 24, 30, 3_000).in_tz("America/New_York")?,
2410    /// );
2411    ///
2412    /// let dur = SignedDuration::new(24 * 60 * 60, 500);
2413    /// assert_eq!(
2414    ///     &zdt - dur,
2415    ///     date(1995, 12, 6).at(3, 24, 30, 3_000).in_tz("America/New_York")?,
2416    /// );
2417    ///
2418    /// let dur = Duration::new(24 * 60 * 60, 500);
2419    /// assert_eq!(
2420    ///     &zdt - dur,
2421    ///     date(1995, 12, 6).at(3, 24, 30, 3_000).in_tz("America/New_York")?,
2422    /// );
2423    ///
2424    /// # Ok::<(), Box<dyn std::error::Error>>(())
2425    /// ```
2426    #[inline]
2427    pub fn checked_sub<A: Into<ZonedDateTimeArithmetic>>(
2428        &self,
2429        duration: A,
2430    ) -> Result<ZonedDateTime, Error> {
2431        self.clone().checked_sub_consuming(duration)
2432    }
2433
2434    /// Like `checked_sub`, but consumes `self` and thus avoids cloning
2435    /// the `TimeZone`.
2436    ///
2437    /// This is currently only accessible via the `impl Sub<...> for
2438    /// ZonedDateTime` trait implementation.
2439    #[inline]
2440    fn checked_sub_consuming<A: Into<ZonedDateTimeArithmetic>>(
2441        self,
2442        duration: A,
2443    ) -> Result<ZonedDateTime, Error> {
2444        let duration: ZonedDateTimeArithmetic = duration.into();
2445        duration.checked_neg().and_then(|za| za.checked_add(self))
2446    }
2447
2448    /// This routine is identical to [`ZonedDateTime::checked_add`], except the
2449    /// result saturates on overflow. That is, instead of overflow, either
2450    /// [`Timestamp::MIN`] or [`Timestamp::MAX`] (in this `ZonedDateTime`
2451    /// value's time zone) is returned.
2452    ///
2453    /// # Properties
2454    ///
2455    /// The properties of this routine are identical to
2456    /// [`ZonedDateTime::checked_add`], except that if saturation occurs, then
2457    /// the result is not reversible.
2458    ///
2459    /// # Example
2460    ///
2461    /// ```
2462    /// use jiff::{civil::date, SignedDuration, Timestamp, ToSpan};
2463    ///
2464    /// let zdt = date(2024, 3, 31)
2465    ///     .at(13, 13, 13, 13)
2466    ///     .in_tz("America/New_York")?;
2467    /// assert_eq!(
2468    ///     Timestamp::MAX,
2469    ///     zdt.saturating_add(9000.years()).timestamp(),
2470    /// );
2471    /// assert_eq!(
2472    ///     Timestamp::MIN,
2473    ///     zdt.saturating_add(-19000.years()).timestamp(),
2474    /// );
2475    /// assert_eq!(
2476    ///     Timestamp::MAX,
2477    ///     zdt.saturating_add(SignedDuration::MAX).timestamp(),
2478    /// );
2479    /// assert_eq!(
2480    ///     Timestamp::MIN,
2481    ///     zdt.saturating_add(SignedDuration::MIN).timestamp(),
2482    /// );
2483    /// assert_eq!(
2484    ///     Timestamp::MAX,
2485    ///     zdt.saturating_add(std::time::Duration::MAX).timestamp(),
2486    /// );
2487    ///
2488    /// # Ok::<(), Box<dyn std::error::Error>>(())
2489    /// ```
2490    #[inline]
2491    pub fn saturating_add<A: Into<ZonedDateTimeArithmetic>>(
2492        &self,
2493        duration: A,
2494    ) -> ZonedDateTime {
2495        let duration: ZonedDateTimeArithmetic = duration.into();
2496        self.checked_add(duration).unwrap_or_else(|_| {
2497            let ts = if duration.is_negative() {
2498                Timestamp::MIN
2499            } else {
2500                Timestamp::MAX
2501            };
2502            ts.to_zoned_datetime(self.time_zone().clone())
2503        })
2504    }
2505
2506    /// This routine is identical to [`ZonedDateTime::saturating_add`] with the
2507    /// span parameter negated.
2508    ///
2509    /// # Example
2510    ///
2511    /// ```
2512    /// use jiff::{civil::date, SignedDuration, Timestamp, ToSpan};
2513    ///
2514    /// let zdt = date(2024, 3, 31)
2515    ///     .at(13, 13, 13, 13)
2516    ///     .in_tz("America/New_York")?;
2517    /// assert_eq!(
2518    ///     Timestamp::MIN,
2519    ///     zdt.saturating_sub(19000.years()).timestamp(),
2520    /// );
2521    /// assert_eq!(
2522    ///     Timestamp::MAX,
2523    ///     zdt.saturating_sub(-9000.years()).timestamp(),
2524    /// );
2525    /// assert_eq!(
2526    ///     Timestamp::MIN,
2527    ///     zdt.saturating_sub(SignedDuration::MAX).timestamp(),
2528    /// );
2529    /// assert_eq!(
2530    ///     Timestamp::MAX,
2531    ///     zdt.saturating_sub(SignedDuration::MIN).timestamp(),
2532    /// );
2533    /// assert_eq!(
2534    ///     Timestamp::MIN,
2535    ///     zdt.saturating_sub(std::time::Duration::MAX).timestamp(),
2536    /// );
2537    ///
2538    /// # Ok::<(), Box<dyn std::error::Error>>(())
2539    /// ```
2540    #[inline]
2541    pub fn saturating_sub<A: Into<ZonedDateTimeArithmetic>>(
2542        &self,
2543        duration: A,
2544    ) -> ZonedDateTime {
2545        let duration: ZonedDateTimeArithmetic = duration.into();
2546        let Ok(duration) = duration.checked_neg() else {
2547            return Timestamp::MIN.to_zoned_datetime(self.time_zone().clone());
2548        };
2549        self.saturating_add(duration)
2550    }
2551
2552    /// Returns a span representing the elapsed time from this zoned datetime
2553    /// until the given `other` zoned datetime.
2554    ///
2555    /// When `other` occurs before this datetime, then the span returned will
2556    /// be negative.
2557    ///
2558    /// Depending on the input provided, the span returned is rounded. It may
2559    /// also be balanced up to bigger units than the default. By default, the
2560    /// span returned is balanced such that the biggest possible unit is hours.
2561    /// This default is an API guarantee. Users can rely on the default not
2562    /// returning any calendar units in the default configuration.
2563    ///
2564    /// This operation is configured by providing a [`ZonedDateTimeDifference`]
2565    /// value. Since this routine accepts anything that implements
2566    /// `Into<ZonedDateTimeDifference>`, once can pass a `&ZonedDateTime`
2567    /// directly. One can also pass a `(Unit, &ZonedDateTime)`, where `Unit` is
2568    /// treated as [`ZonedDateTimeDifference::largest`].
2569    ///
2570    /// # Properties
2571    ///
2572    /// It is guaranteed that if the returned span is subtracted from `other`,
2573    /// and if no rounding is requested, and if the largest unit requested
2574    /// is at most `Unit::Hour`, then the original zoned datetime will be
2575    /// returned.
2576    ///
2577    /// This routine is equivalent to `self.since(other).map(|span| -span)`
2578    /// if no rounding options are set. If rounding options are set, then
2579    /// it's equivalent to
2580    /// `self.since(other_without_rounding_options).map(|span| -span)`,
2581    /// followed by a call to [`Span::round`] with the appropriate rounding
2582    /// options set. This is because the negation of a span can result in
2583    /// different rounding results depending on the rounding mode.
2584    ///
2585    /// # Errors
2586    ///
2587    /// An error can occur in the following scenarios:
2588    ///
2589    /// * When the requested configuration would result in a span that is
2590    /// beyond allowable limits. For example, the nanosecond component of a
2591    /// span cannot represent the span of time between the minimum and maximum
2592    /// zoned datetime supported by Jiff. Therefore, if one requests a span
2593    /// with its largest unit set to [`Unit::Nanosecond`], then it's possible
2594    /// for this routine to fail.
2595    /// * When `ZonedDateTimeDifference` is misconfigured. For example, if the
2596    /// smallest unit provided is bigger than the largest unit.
2597    /// * When units greater than `Unit::Hour` are requested _and_ if the time
2598    /// zones in the provided zoned datetimes are distinct. (See [`TimeZone`]'s
2599    /// section on equality for details on how equality is determined.) This
2600    /// error occurs because the length of a day may vary depending on the time
2601    /// zone. To work around this restriction, convert one or both of the zoned
2602    /// datetimes into the same time zone.
2603    ///
2604    /// It is guaranteed that if one provides a datetime with the default
2605    /// [`ZonedDateTimeDifference`] configuration, then this routine will never
2606    /// fail.
2607    ///
2608    /// # Example
2609    ///
2610    /// ```
2611    /// use jiff::{civil::date, ToSpan};
2612    ///
2613    /// let earlier = date(2006, 8, 24)
2614    ///     .at(22, 30, 0, 0)
2615    ///     .in_tz("America/New_York")?;
2616    /// let later = date(2019, 1, 31)
2617    ///     .at(21, 0, 0, 0)
2618    ///     .in_tz("America/New_York")?;
2619    /// assert_eq!(
2620    ///     earlier.until(&later)?,
2621    ///     109_031.hours().minutes(30).fieldwise(),
2622    /// );
2623    ///
2624    /// // Flipping the dates is fine, but you'll get a negative span.
2625    /// assert_eq!(
2626    ///     later.until(&earlier)?,
2627    ///     -109_031.hours().minutes(30).fieldwise(),
2628    /// );
2629    ///
2630    /// # Ok::<(), Box<dyn std::error::Error>>(())
2631    /// ```
2632    ///
2633    /// # Example: using bigger units
2634    ///
2635    /// This example shows how to expand the span returned to bigger units.
2636    /// This makes use of a `From<(Unit, &ZonedDateTime)> for
2637    /// ZonedDateTimeDifference` trait implementation.
2638    ///
2639    /// ```
2640    /// use jiff::{civil::date, Unit, ToSpan};
2641    ///
2642    /// let zdt1 = date(1995, 12, 07)
2643    ///     .at(3, 24, 30, 3500)
2644    ///     .in_tz("America/New_York")?;
2645    /// let zdt2 = date(2019, 01, 31)
2646    ///     .at(15, 30, 0, 0)
2647    ///     .in_tz("America/New_York")?;
2648    ///
2649    /// // The default limits durations to using "hours" as the biggest unit.
2650    /// let span = zdt1.until(&zdt2)?;
2651    /// assert_eq!(span.to_string(), "PT202956H5M29.9999965S");
2652    ///
2653    /// // But we can ask for units all the way up to years.
2654    /// let span = zdt1.until((Unit::Year, &zdt2))?;
2655    /// assert_eq!(
2656    ///     format!("{span:#}"),
2657    ///     "23y 1mo 24d 12h 5m 29s 999ms 996µs 500ns",
2658    /// );
2659    /// # Ok::<(), Box<dyn std::error::Error>>(())
2660    /// ```
2661    ///
2662    /// # Example: rounding the result
2663    ///
2664    /// This shows how one might find the difference between two zoned
2665    /// datetimes and have the result rounded such that sub-seconds are
2666    /// removed.
2667    ///
2668    /// In this case, we need to hand-construct a [`ZonedDateTimeDifference`]
2669    /// in order to gain full configurability.
2670    ///
2671    /// ```
2672    /// use jiff::{civil::date, Unit, ToSpan, ZonedDateTimeDifference};
2673    ///
2674    /// let zdt1 = date(1995, 12, 07)
2675    ///     .at(3, 24, 30, 3500)
2676    ///     .in_tz("America/New_York")?;
2677    /// let zdt2 = date(2019, 01, 31)
2678    ///     .at(15, 30, 0, 0)
2679    ///     .in_tz("America/New_York")?;
2680    ///
2681    /// let span = zdt1.until(
2682    ///     ZonedDateTimeDifference::from(&zdt2).smallest(Unit::Second),
2683    /// )?;
2684    /// assert_eq!(format!("{span:#}"), "202956h 5m 29s");
2685    ///
2686    /// // We can combine smallest and largest units too!
2687    /// let span = zdt1.until(
2688    ///     ZonedDateTimeDifference::from(&zdt2)
2689    ///         .smallest(Unit::Second)
2690    ///         .largest(Unit::Year),
2691    /// )?;
2692    /// assert_eq!(span.to_string(), "P23Y1M24DT12H5M29S");
2693    ///
2694    /// # Ok::<(), Box<dyn std::error::Error>>(())
2695    /// ```
2696    ///
2697    /// # Example: units biggers than days inhibit reversibility
2698    ///
2699    /// If you ask for units bigger than hours, then adding the span returned
2700    /// to the `other` zoned datetime is not guaranteed to result in the
2701    /// original zoned datetime. For example:
2702    ///
2703    /// ```
2704    /// use jiff::{civil::date, Unit, ToSpan};
2705    ///
2706    /// let zdt1 = date(2024, 3, 2).at(0, 0, 0, 0).in_tz("America/New_York")?;
2707    /// let zdt2 = date(2024, 5, 1).at(0, 0, 0, 0).in_tz("America/New_York")?;
2708    ///
2709    /// let span = zdt1.until((Unit::Month, &zdt2))?;
2710    /// assert_eq!(span, 1.month().days(29).fieldwise());
2711    /// let maybe_original = zdt2.checked_sub(span)?;
2712    /// // Not the same as the original datetime!
2713    /// assert_eq!(
2714    ///     maybe_original,
2715    ///     date(2024, 3, 3).at(0, 0, 0, 0).in_tz("America/New_York")?,
2716    /// );
2717    ///
2718    /// // But in the default configuration, hours are always the biggest unit
2719    /// // and reversibility is guaranteed.
2720    /// let span = zdt1.until(&zdt2)?;
2721    /// assert_eq!(span.to_string(), "PT1439H");
2722    /// let is_original = zdt2.checked_sub(span)?;
2723    /// assert_eq!(is_original, zdt1);
2724    ///
2725    /// # Ok::<(), Box<dyn std::error::Error>>(())
2726    /// ```
2727    ///
2728    /// This occurs because spans are added as if by adding the biggest units
2729    /// first, and then the smaller units. Because months vary in length,
2730    /// their meaning can change depending on how the span is added. In this
2731    /// case, adding one month to `2024-03-02` corresponds to 31 days, but
2732    /// subtracting one month from `2024-05-01` corresponds to 30 days.
2733    ///
2734    /// # Example: two different time zones results in an error
2735    ///
2736    /// When calendar units are requested and the time zones are distinct,
2737    /// then an error occurs:
2738    ///
2739    /// ```
2740    /// use jiff::{civil::date, Unit, ToSpan};
2741    ///
2742    /// let zdt1 = date(2024, 3, 2).at(0, 0, 0, 0).in_tz("America/New_York")?;
2743    /// let zdt2 = date(2024, 5, 1).at(0, 0, 0, 0).in_tz("America/Los_Angeles")?;
2744    ///
2745    /// assert_eq!(
2746    ///     zdt1.until((Unit::Month, &zdt2)).unwrap_err().to_string(),
2747    ///     "computing the span between zoned datetimes, with month units, \
2748    ///      requires that the time zones are equivalent, \
2749    ///      but the zoned datetimes have distinct time zones",
2750    /// );
2751    ///
2752    /// # Ok::<(), Box<dyn std::error::Error>>(())
2753    /// ```
2754    ///
2755    /// However, even when the time zone identifiers are not precisely
2756    /// equivalent, it's still possible for this to succeed. For example,
2757    /// [`TimeZone`] equality uses the concept of primary identifiers. So if
2758    /// the two time zones have the same primary identifier, then this
2759    /// operation still works:
2760    ///
2761    /// ```
2762    /// use jiff::{civil::date, Unit, ToSpan};
2763    /// # if jiff::tz::TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
2764    ///
2765    /// let zdt1 = date(2024, 3, 2).at(0, 0, 0, 0).in_tz("Asia/Calcutta")?;
2766    /// let zdt2 = date(2024, 5, 1).at(0, 0, 0, 0).in_tz("Asia/Kolkata")?;
2767    /// let span = zdt1.until((Unit::Month, &zdt2))?;
2768    /// assert_eq!(span, 1.month().days(29).fieldwise());
2769    ///
2770    /// # Ok::<(), Box<dyn std::error::Error>>(())
2771    /// ```
2772    #[inline]
2773    pub fn until<'a, A: Into<ZonedDateTimeDifference<'a>>>(
2774        &self,
2775        other: A,
2776    ) -> Result<Span, Error> {
2777        let args: ZonedDateTimeDifference = other.into();
2778        let span = args.until_with_largest_unit(self)?;
2779        if args.rounding_may_change_span() {
2780            span.round(args.round.relative(self))
2781        } else {
2782            Ok(span)
2783        }
2784    }
2785
2786    /// This routine is identical to [`ZonedDateTime::until`], but the order of
2787    /// the parameters is flipped.
2788    ///
2789    /// # Errors
2790    ///
2791    /// This has the same error conditions as [`ZonedDateTime::until`].
2792    ///
2793    /// # Example
2794    ///
2795    /// This routine can be used via the `-` operator. Since the default
2796    /// configuration is used and because a `Span` can represent the difference
2797    /// between any two possible zoned datetimes, it will never panic. Note
2798    /// that we use `&zdt1 - &zdt2` instead of `zdt1 - zdt2` since `Sub` is
2799    /// implemented for `&ZonedDateTime` and not `ZonedDateTime`. This is
2800    /// because `ZonedDateTime` is not `Copy`.
2801    ///
2802    /// ```
2803    /// use jiff::{civil::date, ToSpan};
2804    ///
2805    /// let earlier = date(2006, 8, 24)
2806    ///     .at(22, 30, 0, 0)
2807    ///     .in_tz("America/New_York")?;
2808    /// let later = date(2019, 1, 31)
2809    ///     .at(21, 0, 0, 0)
2810    ///     .in_tz("America/New_York")?;
2811    /// assert_eq!(&later - &earlier, 109_031.hours().minutes(30).fieldwise());
2812    ///
2813    /// # Ok::<(), Box<dyn std::error::Error>>(())
2814    /// ```
2815    #[inline]
2816    pub fn since<'a, A: Into<ZonedDateTimeDifference<'a>>>(
2817        &self,
2818        other: A,
2819    ) -> Result<Span, Error> {
2820        let args: ZonedDateTimeDifference = other.into();
2821        let span = -args.until_with_largest_unit(self)?;
2822        if args.rounding_may_change_span() {
2823            span.round(args.round.relative(self))
2824        } else {
2825            Ok(span)
2826        }
2827    }
2828
2829    /// Returns an absolute duration representing the elapsed time from this
2830    /// zoned datetime until the given `other` zoned datetime.
2831    ///
2832    /// When `other` occurs before this zoned datetime, then the duration
2833    /// returned will be negative.
2834    ///
2835    /// Unlike [`ZonedDateTime::until`], this always returns a duration
2836    /// corresponding to a 96-bit integer of nanoseconds between two
2837    /// zoned datetimes.
2838    ///
2839    /// # Fallibility
2840    ///
2841    /// This routine never panics or returns an error. Since there are no
2842    /// configuration options that can be incorrectly provided, no error is
2843    /// possible when calling this routine. In contrast,
2844    /// [`ZonedDateTime::until`] can return an error in some cases due to
2845    /// misconfiguration. But like this routine, [`ZonedDateTime::until`] never
2846    /// panics or returns an error in its default configuration.
2847    ///
2848    /// # When should I use this versus [`ZonedDateTime::until`]?
2849    ///
2850    /// See the type documentation for [`SignedDuration`] for the section on
2851    /// when one should use [`Span`] and when one should use `SignedDuration`.
2852    /// In short, use `Span` (and therefore `Timestamp::until`) unless you have
2853    /// a specific reason to do otherwise.
2854    ///
2855    /// # Example
2856    ///
2857    /// ```
2858    /// use jiff::{civil::date, SignedDuration};
2859    ///
2860    /// let earlier = date(2006, 8, 24)
2861    ///     .at(22, 30, 0, 0)
2862    ///     .in_tz("America/New_York")?;
2863    /// let later = date(2019, 1, 31)
2864    ///     .at(21, 0, 0, 0)
2865    ///     .in_tz("America/New_York")?;
2866    /// assert_eq!(
2867    ///     earlier.duration_until(&later),
2868    ///     SignedDuration::from_hours(109_031)
2869    ///         + SignedDuration::from_mins(30),
2870    /// );
2871    ///
2872    /// // Flipping the dates is fine, but you'll get a negative span.
2873    /// assert_eq!(
2874    ///     later.duration_until(&earlier),
2875    ///     -SignedDuration::from_hours(109_031)
2876    ///         + -SignedDuration::from_mins(30),
2877    /// );
2878    ///
2879    /// # Ok::<(), Box<dyn std::error::Error>>(())
2880    /// ```
2881    ///
2882    /// # Example: difference with [`ZonedDateTime::until`]
2883    ///
2884    /// The main difference between this routine and `ZonedDateTime::until` is
2885    /// that the latter can return units other than a 96-bit integer of
2886    /// nanoseconds. While a 96-bit integer of nanoseconds can be converted
2887    /// into other units like hours, this can only be done for uniform units.
2888    /// (Uniform units are units for which each individual unit always
2889    /// corresponds to the same elapsed time regardless of the datetime it is
2890    /// relative to.) This can't be done for units like years, months or days.
2891    ///
2892    /// ```
2893    /// use jiff::{civil::date, SignedDuration, Span, SpanRound, ToSpan, Unit};
2894    ///
2895    /// let zdt1 = date(2024, 3, 10).at(0, 0, 0, 0).in_tz("America/New_York")?;
2896    /// let zdt2 = date(2024, 3, 11).at(0, 0, 0, 0).in_tz("America/New_York")?;
2897    ///
2898    /// let span = zdt1.until((Unit::Day, &zdt2))?;
2899    /// assert_eq!(format!("{span:#}"), "1d");
2900    ///
2901    /// let duration = zdt1.duration_until(&zdt2);
2902    /// // This day was only 23 hours long!
2903    /// assert_eq!(duration, SignedDuration::from_hours(23));
2904    /// // There's no way to extract years, months or days from the signed
2905    /// // duration like one might extract hours (because every hour
2906    /// // is the same length). Instead, you actually have to convert
2907    /// // it to a span and then balance it by providing a relative date!
2908    /// let options = SpanRound::new().largest(Unit::Day).relative(&zdt1);
2909    /// let span = Span::try_from(duration)?.round(options)?;
2910    /// assert_eq!(format!("{span:#}"), "1d");
2911    ///
2912    /// # Ok::<(), Box<dyn std::error::Error>>(())
2913    /// ```
2914    ///
2915    /// # Example: getting an unsigned duration
2916    ///
2917    /// If you're looking to find the duration between two zoned datetimes as
2918    /// a [`std::time::Duration`], you'll need to use this method to get a
2919    /// [`SignedDuration`] and then convert it to a `std::time::Duration`:
2920    ///
2921    /// ```
2922    /// use std::time::Duration;
2923    ///
2924    /// use jiff::civil::date;
2925    ///
2926    /// let zdt1 = date(2024, 7, 1).at(0, 0, 0, 0).in_tz("America/New_York")?;
2927    /// let zdt2 = date(2024, 8, 1).at(0, 0, 0, 0).in_tz("America/New_York")?;
2928    /// let duration = Duration::try_from(zdt1.duration_until(&zdt2))?;
2929    /// assert_eq!(duration, Duration::from_secs(31 * 24 * 60 * 60));
2930    ///
2931    /// // Note that unsigned durations cannot represent all
2932    /// // possible differences! If the duration would be negative,
2933    /// // then the conversion fails:
2934    /// assert!(Duration::try_from(zdt2.duration_until(&zdt1)).is_err());
2935    ///
2936    /// # Ok::<(), Box<dyn std::error::Error>>(())
2937    /// ```
2938    #[inline]
2939    pub fn duration_until(&self, other: &ZonedDateTime) -> SignedDuration {
2940        SignedDuration::zoned_datetime_until(self, other)
2941    }
2942
2943    /// This routine is identical to [`ZonedDateTime::duration_until`], but the
2944    /// order of the parameters is flipped.
2945    ///
2946    /// # Example
2947    ///
2948    /// ```
2949    /// use jiff::{civil::date, SignedDuration};
2950    ///
2951    /// let earlier = date(2006, 8, 24)
2952    ///     .at(22, 30, 0, 0)
2953    ///     .in_tz("America/New_York")?;
2954    /// let later = date(2019, 1, 31)
2955    ///     .at(21, 0, 0, 0)
2956    ///     .in_tz("America/New_York")?;
2957    /// assert_eq!(
2958    ///     later.duration_since(&earlier),
2959    ///     SignedDuration::from_hours(109_031)
2960    ///         + SignedDuration::from_mins(30),
2961    /// );
2962    ///
2963    /// # Ok::<(), Box<dyn std::error::Error>>(())
2964    /// ```
2965    #[inline]
2966    pub fn duration_since(&self, other: &ZonedDateTime) -> SignedDuration {
2967        SignedDuration::zoned_datetime_until(other, self)
2968    }
2969
2970    /// Rounds this zoned datetime according to the [`ZonedDateTimeRound`]
2971    /// configuration given.
2972    ///
2973    /// The principal option is [`ZonedDateTimeRound::smallest`], which allows
2974    /// one to configure the smallest units in the returned zoned datetime.
2975    /// Rounding is what determines whether that unit should keep its current
2976    /// value or whether it should be incremented. Moreover, the amount it
2977    /// should be incremented can be configured via
2978    /// [`ZonedDateTimeRound::increment`]. Finally, the rounding strategy
2979    /// itself can be configured via [`ZonedDateTimeRound::mode`].
2980    ///
2981    /// Note that this routine is generic and accepts anything that implements
2982    /// `Into<ZonedDateTimeRound>`. Some notable implementations are:
2983    ///
2984    /// * `From<Unit> for ZonedDateTimeRound`, which will automatically create
2985    /// a `ZonedDateTimeRound::new().smallest(unit)` from the unit provided.
2986    /// * `From<(Unit, i64)> for ZonedDateTimeRound`, which will automatically
2987    /// create a `ZonedDateTimeRound::new().smallest(unit).increment(number)`
2988    /// from the unit and increment provided.
2989    ///
2990    /// # Errors
2991    ///
2992    /// This returns an error if the smallest unit configured on the given
2993    /// [`ZonedDateTimeRound`] is bigger than days. An error is also returned
2994    /// if the rounding increment is greater than 1 when the units are days.
2995    /// (Currently, rounding to the nearest week, month or year is not
2996    /// supported.)
2997    ///
2998    /// When the smallest unit is less than days, the rounding increment must
2999    /// divide evenly into the next highest unit after the smallest unit
3000    /// configured (and must not be equivalent to it). For example, if the
3001    /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
3002    /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
3003    /// Namely, any integer that divides evenly into `1,000` nanoseconds since
3004    /// there are `1,000` nanoseconds in the next highest unit (microseconds).
3005    ///
3006    /// This can also return an error in some cases where rounding would
3007    /// require arithmetic that exceeds the maximum zoned datetime value.
3008    ///
3009    /// # Example
3010    ///
3011    /// This is a basic example that demonstrates rounding a zoned datetime to
3012    /// the nearest day. This also demonstrates calling this method with the
3013    /// smallest unit directly, instead of constructing a `ZonedDateTimeRound`
3014    /// manually.
3015    ///
3016    /// ```
3017    /// use jiff::{civil::date, Unit};
3018    ///
3019    /// // rounds up
3020    /// let zdt = date(2024, 6, 19).at(15, 0, 0, 0).in_tz("America/New_York")?;
3021    /// assert_eq!(
3022    ///     zdt.round(Unit::Day)?,
3023    ///     date(2024, 6, 20).at(0, 0, 0, 0).in_tz("America/New_York")?,
3024    /// );
3025    ///
3026    /// // rounds down
3027    /// let zdt = date(2024, 6, 19).at(10, 0, 0, 0).in_tz("America/New_York")?;
3028    /// assert_eq!(
3029    ///     zdt.round(Unit::Day)?,
3030    ///     date(2024, 6, 19).at(0, 0, 0, 0).in_tz("America/New_York")?,
3031    /// );
3032    ///
3033    /// # Ok::<(), Box<dyn std::error::Error>>(())
3034    /// ```
3035    ///
3036    /// # Example: changing the rounding mode
3037    ///
3038    /// The default rounding mode is [`RoundMode::HalfExpand`], which
3039    /// breaks ties by rounding away from zero. But other modes like
3040    /// [`RoundMode::Trunc`] can be used too:
3041    ///
3042    /// ```
3043    /// use jiff::{
3044    ///     RoundMode, Unit, ZonedDateTime, ZonedDateTimeRound, civil::date,
3045    /// };
3046    ///
3047    /// let zdt = date(2024, 6, 19).at(15, 0, 0, 0).in_tz("America/New_York")?;
3048    /// assert_eq!(
3049    ///     zdt.round(Unit::Day)?,
3050    ///     date(2024, 6, 20).at(0, 0, 0, 0).in_tz("America/New_York")?,
3051    /// );
3052    /// // The default will round up to the next day for any time past noon (as
3053    /// // shown above), but using truncation rounding will always round down.
3054    /// assert_eq!(
3055    ///     zdt.round(
3056    ///         ZonedDateTimeRound::new()
3057    ///             .smallest(Unit::Day)
3058    ///             .mode(RoundMode::Trunc),
3059    ///     )?,
3060    ///     date(2024, 6, 19).at(0, 0, 0, 0).in_tz("America/New_York")?,
3061    /// );
3062    ///
3063    /// # Ok::<(), Box<dyn std::error::Error>>(())
3064    /// ```
3065    ///
3066    /// # Example: rounding to the nearest 5 minute increment
3067    ///
3068    /// ```
3069    /// use jiff::{civil::date, Unit};
3070    ///
3071    /// // rounds down
3072    /// let zdt = date(2024, 6, 19)
3073    ///     .at(15, 27, 29, 999_999_999)
3074    ///     .in_tz("America/New_York")?;
3075    /// assert_eq!(
3076    ///     zdt.round((Unit::Minute, 5))?,
3077    ///     date(2024, 6, 19).at(15, 25, 0, 0).in_tz("America/New_York")?,
3078    /// );
3079    /// // rounds up
3080    /// let zdt = date(2024, 6, 19)
3081    ///     .at(15, 27, 30, 0)
3082    ///     .in_tz("America/New_York")?;
3083    /// assert_eq!(
3084    ///     zdt.round((Unit::Minute, 5))?,
3085    ///     date(2024, 6, 19).at(15, 30, 0, 0).in_tz("America/New_York")?,
3086    /// );
3087    ///
3088    /// # Ok::<(), Box<dyn std::error::Error>>(())
3089    /// ```
3090    ///
3091    /// # Example: behavior near time zone transitions
3092    ///
3093    /// When rounding this zoned datetime near time zone transitions (such as
3094    /// DST), the "sensible" thing is done by default. Namely, rounding will
3095    /// jump to the closest instant, even if the change in civil clock time is
3096    /// large. For example, when rounding up into a gap, the civil clock time
3097    /// will jump over the gap, but the corresponding change in the instant is
3098    /// as one might expect:
3099    ///
3100    /// ```
3101    /// use jiff::{Unit, ZonedDateTime};
3102    ///
3103    /// let zdt1: ZonedDateTime =
3104    ///     "2024-03-10T01:59:00-05[America/New_York]".parse()?;
3105    /// let zdt2 = zdt1.round(Unit::Hour)?;
3106    /// assert_eq!(
3107    ///     zdt2.to_string(),
3108    ///     "2024-03-10T03:00:00-04:00[America/New_York]",
3109    /// );
3110    ///
3111    /// # Ok::<(), Box<dyn std::error::Error>>(())
3112    /// ```
3113    ///
3114    /// Similarly, when rounding inside a fold, rounding will respect whether
3115    /// it's the first or second time the clock has repeated the hour. For the
3116    /// DST transition in New York on `2024-11-03` from offset `-04` to `-05`,
3117    /// here is an example that rounds the first 1 o'clock hour:
3118    ///
3119    /// ```
3120    /// use jiff::{Unit, ZonedDateTime};
3121    ///
3122    /// let zdt1: ZonedDateTime =
3123    ///     "2024-11-03T01:59:01-04[America/New_York]".parse()?;
3124    /// let zdt2 = zdt1.round(Unit::Minute)?;
3125    /// assert_eq!(
3126    ///     zdt2.to_string(),
3127    ///     "2024-11-03T01:59:00-04:00[America/New_York]",
3128    /// );
3129    ///
3130    /// # Ok::<(), Box<dyn std::error::Error>>(())
3131    /// ```
3132    ///
3133    /// And now the second 1 o'clock hour. Notice how the rounded result stays
3134    /// in the second 1 o'clock hour.
3135    ///
3136    /// ```
3137    /// use jiff::{Unit, ZonedDateTime};
3138    ///
3139    /// let zdt1: ZonedDateTime =
3140    ///     "2024-11-03T01:59:01-05[America/New_York]".parse()?;
3141    /// let zdt2 = zdt1.round(Unit::Minute)?;
3142    /// assert_eq!(
3143    ///     zdt2.to_string(),
3144    ///     "2024-11-03T01:59:00-05:00[America/New_York]",
3145    /// );
3146    ///
3147    /// # Ok::<(), Box<dyn std::error::Error>>(())
3148    /// ```
3149    ///
3150    /// # Example: rounding to nearest day takes length of day into account
3151    ///
3152    /// Some days are shorter than 24 hours, and so rounding down will occur
3153    /// even when the time is past noon:
3154    ///
3155    /// ```
3156    /// use jiff::{Unit, ZonedDateTime};
3157    ///
3158    /// let zdt1: ZonedDateTime =
3159    ///     "2025-03-09T12:15-04[America/New_York]".parse()?;
3160    /// let zdt2 = zdt1.round(Unit::Day)?;
3161    /// assert_eq!(
3162    ///     zdt2.to_string(),
3163    ///     "2025-03-09T00:00:00-05:00[America/New_York]",
3164    /// );
3165    ///
3166    /// // For 23 hour days, 12:30 is the tipping point to round up in the
3167    /// // default rounding configuration:
3168    /// let zdt1: ZonedDateTime =
3169    ///     "2025-03-09T12:30-04[America/New_York]".parse()?;
3170    /// let zdt2 = zdt1.round(Unit::Day)?;
3171    /// assert_eq!(
3172    ///     zdt2.to_string(),
3173    ///     "2025-03-10T00:00:00-04:00[America/New_York]",
3174    /// );
3175    ///
3176    /// # Ok::<(), Box<dyn std::error::Error>>(())
3177    /// ```
3178    ///
3179    /// And some days are longer than 24 hours, and so rounding _up_ will occur
3180    /// even when the time is before noon:
3181    ///
3182    /// ```
3183    /// use jiff::{Unit, ZonedDateTime};
3184    ///
3185    /// let zdt1: ZonedDateTime =
3186    ///     "2025-11-02T11:45-05[America/New_York]".parse()?;
3187    /// let zdt2 = zdt1.round(Unit::Day)?;
3188    /// assert_eq!(
3189    ///     zdt2.to_string(),
3190    ///     "2025-11-03T00:00:00-05:00[America/New_York]",
3191    /// );
3192    ///
3193    /// // For 25 hour days, 11:30 is the tipping point to round up in the
3194    /// // default rounding configuration. So 11:29 will round down:
3195    /// let zdt1: ZonedDateTime =
3196    ///     "2025-11-02T11:29-05[America/New_York]".parse()?;
3197    /// let zdt2 = zdt1.round(Unit::Day)?;
3198    /// assert_eq!(
3199    ///     zdt2.to_string(),
3200    ///     "2025-11-02T00:00:00-04:00[America/New_York]",
3201    /// );
3202    ///
3203    /// # Ok::<(), Box<dyn std::error::Error>>(())
3204    /// ```
3205    ///
3206    /// # Example: overflow error
3207    ///
3208    /// This example demonstrates that it's possible for this operation to
3209    /// result in an error from zoned datetime arithmetic overflow.
3210    ///
3211    /// ```
3212    /// use jiff::{Timestamp, Unit};
3213    ///
3214    /// let zdt = Timestamp::MAX.in_tz("America/New_York")?;
3215    /// assert!(zdt.round(Unit::Day).is_err());
3216    ///
3217    /// # Ok::<(), Box<dyn std::error::Error>>(())
3218    /// ```
3219    ///
3220    /// This occurs because rounding to the nearest day for the maximum
3221    /// timestamp would result in rounding up to the next day. But the next day
3222    /// is greater than the maximum, and so this returns an error.
3223    #[inline]
3224    pub fn round<R: Into<ZonedDateTimeRound>>(
3225        &self,
3226        options: R,
3227    ) -> Result<ZonedDateTime, Error> {
3228        let options: ZonedDateTimeRound = options.into();
3229        options.round(self)
3230    }
3231
3232    /// Return an iterator of periodic zoned datetimes determined by the given
3233    /// span.
3234    ///
3235    /// The given span may be negative, in which case, the iterator will move
3236    /// backwards through time. The iterator won't stop until either the span
3237    /// itself overflows, or it would otherwise exceed the minimum or maximum
3238    /// `ZonedDateTime` value.
3239    ///
3240    /// When the given span is positive, the zoned datetimes yielded are
3241    /// monotonically increasing. When the given span is negative, the zoned
3242    /// datetimes yielded as monotonically decreasing. When the given span is
3243    /// zero, then all values yielded are identical and the time series is
3244    /// infinite.
3245    ///
3246    /// # Example: when to check a glucose monitor
3247    ///
3248    /// When my cat had diabetes, my veterinarian installed a glucose monitor
3249    /// and instructed me to scan it about every 5 hours. This example lists
3250    /// all of the times I needed to scan it for the 2 days following its
3251    /// installation:
3252    ///
3253    /// ```
3254    /// use jiff::{civil::datetime, ToSpan};
3255    ///
3256    /// let start = datetime(2023, 7, 15, 16, 30, 0, 0)
3257    ///     .in_tz("America/New_York")?;
3258    /// let end = start.checked_add(2.days())?;
3259    /// let mut scan_times = vec![];
3260    /// for zdt in start.series(5.hours()).take_while(|zdt| zdt <= end) {
3261    ///     scan_times.push(zdt.datetime());
3262    /// }
3263    /// assert_eq!(scan_times, vec![
3264    ///     datetime(2023, 7, 15, 16, 30, 0, 0),
3265    ///     datetime(2023, 7, 15, 21, 30, 0, 0),
3266    ///     datetime(2023, 7, 16, 2, 30, 0, 0),
3267    ///     datetime(2023, 7, 16, 7, 30, 0, 0),
3268    ///     datetime(2023, 7, 16, 12, 30, 0, 0),
3269    ///     datetime(2023, 7, 16, 17, 30, 0, 0),
3270    ///     datetime(2023, 7, 16, 22, 30, 0, 0),
3271    ///     datetime(2023, 7, 17, 3, 30, 0, 0),
3272    ///     datetime(2023, 7, 17, 8, 30, 0, 0),
3273    ///     datetime(2023, 7, 17, 13, 30, 0, 0),
3274    /// ]);
3275    ///
3276    /// # Ok::<(), Box<dyn std::error::Error>>(())
3277    /// ```
3278    ///
3279    /// # Example: behavior during daylight saving time transitions
3280    ///
3281    /// Even when there is a daylight saving time transition, the time series
3282    /// returned handles it correctly by continuing to move forward.
3283    ///
3284    /// This first example shows what happens when there is a gap in time (it
3285    /// is automatically skipped):
3286    ///
3287    /// ```
3288    /// use jiff::{civil::date, ToSpan};
3289    ///
3290    /// let zdt = date(2025, 3, 9).at(1, 0, 0, 0).in_tz("America/New_York")?;
3291    /// let mut it = zdt.series(30.minutes());
3292    ///
3293    /// assert_eq!(
3294    ///     it.next().map(|zdt| zdt.to_string()),
3295    ///     Some("2025-03-09T01:00:00-05:00[America/New_York]".to_string()),
3296    /// );
3297    /// assert_eq!(
3298    ///     it.next().map(|zdt| zdt.to_string()),
3299    ///     Some("2025-03-09T01:30:00-05:00[America/New_York]".to_string()),
3300    /// );
3301    /// assert_eq!(
3302    ///     it.next().map(|zdt| zdt.to_string()),
3303    ///     Some("2025-03-09T03:00:00-04:00[America/New_York]".to_string()),
3304    /// );
3305    /// assert_eq!(
3306    ///     it.next().map(|zdt| zdt.to_string()),
3307    ///     Some("2025-03-09T03:30:00-04:00[America/New_York]".to_string()),
3308    /// );
3309    ///
3310    /// # Ok::<(), Box<dyn std::error::Error>>(())
3311    /// ```
3312    ///
3313    /// And similarly, when there is a fold in time, the fold is repeated:
3314    ///
3315    /// ```
3316    /// use jiff::{civil::date, ToSpan};
3317    ///
3318    /// let zdt = date(2025, 11, 2).at(0, 30, 0, 0).in_tz("America/New_York")?;
3319    /// let mut it = zdt.series(30.minutes());
3320    ///
3321    /// assert_eq!(
3322    ///     it.next().map(|zdt| zdt.to_string()),
3323    ///     Some("2025-11-02T00:30:00-04:00[America/New_York]".to_string()),
3324    /// );
3325    /// assert_eq!(
3326    ///     it.next().map(|zdt| zdt.to_string()),
3327    ///     Some("2025-11-02T01:00:00-04:00[America/New_York]".to_string()),
3328    /// );
3329    /// assert_eq!(
3330    ///     it.next().map(|zdt| zdt.to_string()),
3331    ///     Some("2025-11-02T01:30:00-04:00[America/New_York]".to_string()),
3332    /// );
3333    /// assert_eq!(
3334    ///     it.next().map(|zdt| zdt.to_string()),
3335    ///     Some("2025-11-02T01:00:00-05:00[America/New_York]".to_string()),
3336    /// );
3337    /// assert_eq!(
3338    ///     it.next().map(|zdt| zdt.to_string()),
3339    ///     Some("2025-11-02T01:30:00-05:00[America/New_York]".to_string()),
3340    /// );
3341    /// assert_eq!(
3342    ///     it.next().map(|zdt| zdt.to_string()),
3343    ///     Some("2025-11-02T02:00:00-05:00[America/New_York]".to_string()),
3344    /// );
3345    ///
3346    /// # Ok::<(), Box<dyn std::error::Error>>(())
3347    /// ```
3348    ///
3349    /// # Example: ensures values are monotonically increasing (or decreasing)
3350    ///
3351    /// Because of odd time zone transitions, it's possible that adding
3352    /// different calendar units to the same zoned datetime will yield the
3353    /// same result. For example, `2011-12-30` did not exist on the clocks
3354    /// in the `Pacific/Apia` time zone. (Because Samoa switched sides of the
3355    /// International Date Line.) This means that adding `1 day` to
3356    /// `2011-12-29` yields the same result as adding `2 days`:
3357    ///
3358    /// ```
3359    /// use jiff::{civil, ToSpan};
3360    ///
3361    /// let zdt = civil::date(2011, 12, 29).in_tz("Pacific/Apia")?;
3362    /// assert_eq!(
3363    ///     zdt.checked_add(1.day())?.to_string(),
3364    ///     "2011-12-31T00:00:00+14:00[Pacific/Apia]",
3365    /// );
3366    /// assert_eq!(
3367    ///     zdt.checked_add(2.days())?.to_string(),
3368    ///     "2011-12-31T00:00:00+14:00[Pacific/Apia]",
3369    /// );
3370    /// assert_eq!(
3371    ///     zdt.checked_add(3.days())?.to_string(),
3372    ///     "2012-01-01T00:00:00+14:00[Pacific/Apia]",
3373    /// );
3374    ///
3375    /// # Ok::<(), Box<dyn std::error::Error>>(())
3376    /// ```
3377    ///
3378    /// This might lead one to believe that `ZonedDateTime::series` could emit
3379    /// the same instant twice. But it takes this into account and ensures all
3380    /// values occur after the previous value (or before if the `Span` given is
3381    /// negative):
3382    ///
3383    /// ```
3384    /// use jiff::{civil::date, ToSpan};
3385    ///
3386    /// let zdt = date(2011, 12, 28).in_tz("Pacific/Apia")?;
3387    /// let mut it = zdt.series(1.day());
3388    ///
3389    /// assert_eq!(
3390    ///     it.next().map(|zdt| zdt.to_string()),
3391    ///     Some("2011-12-28T00:00:00-10:00[Pacific/Apia]".to_string()),
3392    /// );
3393    /// assert_eq!(
3394    ///     it.next().map(|zdt| zdt.to_string()),
3395    ///     Some("2011-12-29T00:00:00-10:00[Pacific/Apia]".to_string()),
3396    /// );
3397    /// assert_eq!(
3398    ///     it.next().map(|zdt| zdt.to_string()),
3399    ///     Some("2011-12-31T00:00:00+14:00[Pacific/Apia]".to_string()),
3400    /// );
3401    /// assert_eq!(
3402    ///     it.next().map(|zdt| zdt.to_string()),
3403    ///     Some("2012-01-01T00:00:00+14:00[Pacific/Apia]".to_string()),
3404    /// );
3405    ///
3406    /// # Ok::<(), Box<dyn std::error::Error>>(())
3407    /// ```
3408    ///
3409    /// And similarly for a negative `Span`:
3410    ///
3411    /// ```
3412    /// use jiff::{civil::date, ToSpan};
3413    ///
3414    /// let zdt = date(2012, 1, 1).in_tz("Pacific/Apia")?;
3415    /// let mut it = zdt.series(-1.day());
3416    ///
3417    /// assert_eq!(
3418    ///     it.next().map(|zdt| zdt.to_string()),
3419    ///     Some("2012-01-01T00:00:00+14:00[Pacific/Apia]".to_string()),
3420    /// );
3421    /// assert_eq!(
3422    ///     it.next().map(|zdt| zdt.to_string()),
3423    ///     Some("2011-12-31T00:00:00+14:00[Pacific/Apia]".to_string()),
3424    /// );
3425    /// assert_eq!(
3426    ///     it.next().map(|zdt| zdt.to_string()),
3427    ///     Some("2011-12-29T00:00:00-10:00[Pacific/Apia]".to_string()),
3428    /// );
3429    /// assert_eq!(
3430    ///     it.next().map(|zdt| zdt.to_string()),
3431    ///     Some("2011-12-28T00:00:00-10:00[Pacific/Apia]".to_string()),
3432    /// );
3433    ///
3434    /// # Ok::<(), Box<dyn std::error::Error>>(())
3435    /// ```
3436    ///
3437    /// An exception to this is if a zero `Span` is provided. Then all values
3438    /// emitted are necessarily equivalent:
3439    ///
3440    /// ```
3441    /// use jiff::{civil::date, ToSpan};
3442    ///
3443    /// let zdt = date(2011, 12, 28).in_tz("Pacific/Apia")?;
3444    /// let mut it = zdt.series(0.days());
3445    ///
3446    /// assert_eq!(
3447    ///     it.next().map(|zdt| zdt.to_string()),
3448    ///     Some("2011-12-28T00:00:00-10:00[Pacific/Apia]".to_string()),
3449    /// );
3450    /// assert_eq!(
3451    ///     it.next().map(|zdt| zdt.to_string()),
3452    ///     Some("2011-12-28T00:00:00-10:00[Pacific/Apia]".to_string()),
3453    /// );
3454    ///
3455    /// # Ok::<(), Box<dyn std::error::Error>>(())
3456    /// ```
3457    #[inline]
3458    pub fn series(&self, period: Span) -> ZonedDateTimeSeries {
3459        ZonedDateTimeSeries {
3460            start: self.clone(),
3461            prev: None,
3462            period,
3463            step: 0,
3464        }
3465    }
3466
3467    /// Returns the heap memory usage, in bytes, of this zoned.
3468    ///
3469    /// This does **not** include the stack size used up by this zoned.
3470    /// To compute that, use `std::mem::size_of::<ZonedDateTime>()`.
3471    pub fn memory_usage(&self) -> usize {
3472        self.inner.time_zone.memory_usage()
3473    }
3474}
3475
3476/// Parsing and formatting using a "printf"-style API.
3477impl ZonedDateTime {
3478    /// Parses a zoned datetime in `input` matching the given `format`.
3479    ///
3480    /// The format string uses a "printf"-style API where conversion
3481    /// specifiers can be used as place holders to match components of
3482    /// a datetime. For details on the specifiers supported, see the
3483    /// [`fmt::strtime`] module documentation.
3484    ///
3485    /// # Warning
3486    ///
3487    /// The `strtime` module APIs do not require an IANA time zone identifier
3488    /// to parse a `ZonedDateTime`. If one is not used, then if you format a
3489    /// zoned datetime in a time zone like `America/New_York` and then parse it
3490    /// back again, the zoned datetime you get back will be a "fixed offset"
3491    /// zoned datetime. This in turn means it will not perform daylight saving
3492    /// time safe arithmetic.
3493    ///
3494    /// However, the `%Q` directive may be used to both format and parse an
3495    /// IANA time zone identifier. It is strongly recommended to use this
3496    /// directive whenever one is formatting or parsing `ZonedDateTime` values.
3497    ///
3498    /// # Errors
3499    ///
3500    /// This returns an error when parsing failed. This might happen because
3501    /// the format string itself was invalid, or because the input didn't match
3502    /// the format string.
3503    ///
3504    /// This also returns an error if there wasn't sufficient information to
3505    /// construct a zoned datetime. For example, if an offset wasn't parsed.
3506    ///
3507    /// # Example
3508    ///
3509    /// This example shows how to parse a zoned datetime:
3510    ///
3511    /// ```
3512    /// use jiff::ZonedDateTime;
3513    ///
3514    /// let zdt = ZonedDateTime::strptime(
3515    ///     "%F %H:%M %:Q",
3516    ///     "2024-07-14 21:14 America/New_York",
3517    /// )?;
3518    /// assert_eq!(
3519    ///     zdt.to_string(),
3520    ///     "2024-07-14T21:14:00-04:00[America/New_York]",
3521    /// );
3522    ///
3523    /// # Ok::<(), Box<dyn std::error::Error>>(())
3524    /// ```
3525    #[inline]
3526    pub fn strptime(
3527        format: impl AsRef<[u8]>,
3528        input: impl AsRef<[u8]>,
3529    ) -> Result<ZonedDateTime, Error> {
3530        fmt::strtime::parse(format, input)
3531            .and_then(|tm| tm.to_zoned_datetime())
3532    }
3533
3534    /// Formats this zoned datetime according to the given `format`.
3535    ///
3536    /// The format string uses a "printf"-style API where conversion
3537    /// specifiers can be used as place holders to format components of
3538    /// a datetime. For details on the specifiers supported, see the
3539    /// [`fmt::strtime`] module documentation.
3540    ///
3541    /// # Warning
3542    ///
3543    /// The `strtime` module APIs do not require an IANA time zone identifier
3544    /// to parse a `ZonedDateTime`. If one is not used, then if you format a
3545    /// zoned datetime in a time zone like `America/New_York` and then parse it
3546    /// back again, the zoned datetime you get back will be a "fixed offset"
3547    /// zoned datetime. This in turn means it will not perform daylight saving
3548    /// time safe arithmetic.
3549    ///
3550    /// However, the `%Q` directive may be used to both format and parse an
3551    /// IANA time zone identifier. It is strongly recommended to use this
3552    /// directive whenever one is formatting or parsing `ZonedDateTime` values
3553    /// since it permits correctly round-tripping `ZonedDateTime` values.
3554    ///
3555    /// # Errors and panics
3556    ///
3557    /// This will never error or panic. In particular,
3558    /// [lenient mode](crate::fmt::strtime::Config::lenient) is enabled, which
3559    /// means that all possible strings have some non-error interpretation.
3560    /// Note that because of this, and since Jiff may add new conversion
3561    /// specifiers in the future, the behavior of a format string may change
3562    /// when it would otherwise be invalid.
3563    ///
3564    /// To format in a way that surfaces errors, use either
3565    /// [`fmt::strtime::format`] or [`fmt::strtime::BrokenDownTime::format`].
3566    ///
3567    /// # Example
3568    ///
3569    /// While the output of the Unix `date` command is likely locale specific,
3570    /// this is what it looks like on my system:
3571    ///
3572    /// ```
3573    /// use jiff::civil::date;
3574    ///
3575    /// let zdt = date(2024, 7, 15)
3576    ///     .at(16, 24, 59, 0)
3577    ///     .in_tz("America/New_York")?;
3578    /// let string = zdt.strftime("%a %b %e %I:%M:%S %p %Z %Y").to_string();
3579    /// assert_eq!(string, "Mon Jul 15 04:24:59 PM EDT 2024");
3580    ///
3581    /// # Ok::<(), Box<dyn std::error::Error>>(())
3582    /// ```
3583    ///
3584    /// # Example: errors are silently ignored
3585    ///
3586    /// If the formatting string is malformed in some way, then it is silently
3587    /// ignored. For example, when using an invalid formatting directive:
3588    ///
3589    /// ```
3590    /// use jiff::ZonedDateTime;
3591    ///
3592    /// let zdt = ZonedDateTime::UNIX_EPOCH;
3593    /// let string = zdt.strftime("%Y %").to_string();
3594    /// assert_eq!(string, "1970 %");
3595    /// ```
3596    ///
3597    /// If one wants to surface errors from a formatting string, use a lower
3598    /// level API:
3599    ///
3600    /// ```
3601    /// use jiff::ZonedDateTime;
3602    ///
3603    /// let zdt = ZonedDateTime::UNIX_EPOCH;
3604    /// assert_eq!(
3605    ///     jiff::fmt::strtime::format("%Y %", &zdt).unwrap_err().to_string(),
3606    ///     "strftime formatting failed: invalid format string, \
3607    ///      expected byte after `%`, but found end of format string",
3608    /// );
3609    /// ```
3610    #[inline]
3611    pub fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(
3612        &self,
3613        format: &'f F,
3614    ) -> fmt::strtime::Display<'f> {
3615        fmt::strtime::Display { fmt: format.as_ref(), tm: self.into() }
3616    }
3617}
3618
3619impl Default for ZonedDateTime {
3620    #[inline]
3621    fn default() -> ZonedDateTime {
3622        ZonedDateTime::UNIX_EPOCH
3623    }
3624}
3625
3626/// Converts a `ZonedDateTime` datetime into a human readable datetime string.
3627///
3628/// (This `Debug` representation currently emits the same string as the
3629/// `Display` representation, but this is not a guarantee.)
3630///
3631/// Options currently supported:
3632///
3633/// * [`std::fmt::Formatter::precision`] can be set to control the precision
3634/// of the fractional second component.
3635///
3636/// # Example
3637///
3638/// ```
3639/// use jiff::civil::date;
3640///
3641/// let zdt = date(2024, 6, 15)
3642///     .at(7, 0, 0, 123_000_000)
3643///     .in_tz("America/New_York")?;
3644/// assert_eq!(
3645///     format!("{zdt:.6?}"),
3646///     "2024-06-15T07:00:00.123000-04:00[America/New_York]",
3647/// );
3648/// // Precision values greater than 9 are clamped to 9.
3649/// assert_eq!(
3650///     format!("{zdt:.300?}"),
3651///     "2024-06-15T07:00:00.123000000-04:00[America/New_York]",
3652/// );
3653/// // A precision of 0 implies the entire fractional
3654/// // component is always truncated.
3655/// assert_eq!(
3656///     format!("{zdt:.0?}"),
3657///     "2024-06-15T07:00:00-04:00[America/New_York]",
3658/// );
3659///
3660/// # Ok::<(), Box<dyn std::error::Error>>(())
3661/// ```
3662impl core::fmt::Debug for ZonedDateTime {
3663    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3664        core::fmt::Display::fmt(self, f)
3665    }
3666}
3667
3668/// Converts a `ZonedDateTime` datetime into a RFC 9557 compliant string.
3669///
3670/// # Formatting options supported
3671///
3672/// * [`std::fmt::Formatter::precision`] can be set to control the precision
3673/// of the fractional second component. When not set, the minimum precision
3674/// required to losslessly render the value is used.
3675///
3676/// # Example
3677///
3678/// This shows the default rendering:
3679///
3680/// ```
3681/// use jiff::civil::date;
3682///
3683/// // No fractional seconds:
3684/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
3685/// assert_eq!(
3686///     format!("{zdt}"),
3687///     "2024-06-15T07:00:00-04:00[America/New_York]",
3688/// );
3689///
3690/// // With fractional seconds:
3691/// let zdt = date(2024, 6, 15)
3692///     .at(7, 0, 0, 123_000_000)
3693///     .in_tz("America/New_York")?;
3694/// assert_eq!(
3695///     format!("{zdt}"),
3696///     "2024-06-15T07:00:00.123-04:00[America/New_York]",
3697/// );
3698///
3699/// # Ok::<(), Box<dyn std::error::Error>>(())
3700/// ```
3701///
3702/// # Example: setting the precision
3703///
3704/// ```
3705/// use jiff::civil::date;
3706///
3707/// let zdt = date(2024, 6, 15)
3708///     .at(7, 0, 0, 123_000_000)
3709///     .in_tz("America/New_York")?;
3710/// assert_eq!(
3711///     format!("{zdt:.6}"),
3712///     "2024-06-15T07:00:00.123000-04:00[America/New_York]",
3713/// );
3714/// // Precision values greater than 9 are clamped to 9.
3715/// assert_eq!(
3716///     format!("{zdt:.300}"),
3717///     "2024-06-15T07:00:00.123000000-04:00[America/New_York]",
3718/// );
3719/// // A precision of 0 implies the entire fractional
3720/// // component is always truncated.
3721/// assert_eq!(
3722///     format!("{zdt:.0}"),
3723///     "2024-06-15T07:00:00-04:00[America/New_York]",
3724/// );
3725///
3726/// # Ok::<(), Box<dyn std::error::Error>>(())
3727/// ```
3728impl core::fmt::Display for ZonedDateTime {
3729    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
3730        use crate::fmt::StdFmtWrite;
3731
3732        let precision =
3733            f.precision().map(|p| u8::try_from(p).unwrap_or(u8::MAX));
3734        temporal::DateTimePrinter::new()
3735            .precision(precision)
3736            .print_zoned_datetime(self, StdFmtWrite(f))
3737            .map_err(|_| core::fmt::Error)
3738    }
3739}
3740
3741#[cfg(feature = "defmt")]
3742impl defmt::Format for ZonedDateTime {
3743    fn format(&self, f: defmt::Formatter) {
3744        use crate::fmt::{DefmtWrite, temporal::DEFAULT_DATETIME_PRINTER};
3745
3746        defmt::unwrap!(
3747            DEFAULT_DATETIME_PRINTER.print_zoned_datetime(self, DefmtWrite(f))
3748        );
3749    }
3750}
3751
3752/// Parses a zoned timestamp from the Temporal datetime format.
3753///
3754/// See the [`fmt::temporal`](crate::fmt::temporal) for more information on
3755/// the precise format.
3756///
3757/// Note that this is only enabled when the `std` feature
3758/// is enabled because it requires access to a global
3759/// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase).
3760impl core::str::FromStr for ZonedDateTime {
3761    type Err = Error;
3762
3763    fn from_str(string: &str) -> Result<ZonedDateTime, Error> {
3764        DEFAULT_DATETIME_PARSER.parse_zoned_datetime(string)
3765    }
3766}
3767
3768impl Eq for ZonedDateTime {}
3769
3770impl PartialEq for ZonedDateTime {
3771    #[inline]
3772    fn eq(&self, rhs: &ZonedDateTime) -> bool {
3773        self.timestamp().eq(&rhs.timestamp())
3774    }
3775}
3776
3777impl<'a> PartialEq<ZonedDateTime> for &'a ZonedDateTime {
3778    #[inline]
3779    fn eq(&self, rhs: &ZonedDateTime) -> bool {
3780        (**self).eq(rhs)
3781    }
3782}
3783
3784impl Ord for ZonedDateTime {
3785    #[inline]
3786    fn cmp(&self, rhs: &ZonedDateTime) -> core::cmp::Ordering {
3787        self.timestamp().cmp(&rhs.timestamp())
3788    }
3789}
3790
3791impl PartialOrd for ZonedDateTime {
3792    #[inline]
3793    fn partial_cmp(&self, rhs: &ZonedDateTime) -> Option<core::cmp::Ordering> {
3794        Some(self.cmp(rhs))
3795    }
3796}
3797
3798impl<'a> PartialOrd<ZonedDateTime> for &'a ZonedDateTime {
3799    #[inline]
3800    fn partial_cmp(&self, rhs: &ZonedDateTime) -> Option<core::cmp::Ordering> {
3801        (**self).partial_cmp(rhs)
3802    }
3803}
3804
3805impl core::hash::Hash for ZonedDateTime {
3806    #[inline]
3807    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
3808        self.timestamp().hash(state);
3809    }
3810}
3811
3812#[cfg(feature = "std")]
3813impl TryFrom<std::time::SystemTime> for ZonedDateTime {
3814    type Error = Error;
3815
3816    #[inline]
3817    fn try_from(
3818        system_time: std::time::SystemTime,
3819    ) -> Result<ZonedDateTime, Error> {
3820        let timestamp = Timestamp::try_from(system_time)?;
3821        Ok(ZonedDateTime::new(timestamp, TimeZone::system()))
3822    }
3823}
3824
3825/// Converts a zoned datetime to a system time.
3826///
3827/// This is equivalent to converting its timestamp to a system time, including
3828/// its platform-dependent range and precision limits.
3829#[cfg(feature = "std")]
3830impl TryFrom<ZonedDateTime> for std::time::SystemTime {
3831    type Error = Error;
3832
3833    #[inline]
3834    fn try_from(time: ZonedDateTime) -> Result<std::time::SystemTime, Error> {
3835        time.timestamp().try_into()
3836    }
3837}
3838
3839/// Converts a borrowed zoned datetime to a system time.
3840///
3841/// This is equivalent to converting its timestamp to a system time, including
3842/// its platform-dependent range and precision limits.
3843#[cfg(feature = "std")]
3844impl<'a> TryFrom<&'a ZonedDateTime> for std::time::SystemTime {
3845    type Error = Error;
3846
3847    #[inline]
3848    fn try_from(
3849        time: &'a ZonedDateTime,
3850    ) -> Result<std::time::SystemTime, Error> {
3851        time.timestamp().try_into()
3852    }
3853}
3854
3855/// Adds a span of time to a zoned datetime.
3856///
3857/// This uses checked arithmetic and panics on overflow. To handle overflow
3858/// without panics, use [`ZonedDateTime::checked_add`].
3859///
3860/// Using this implementation will result in consuming the `ZonedDateTime`
3861/// value. Since it is not `Copy`, this will prevent further use. If this is
3862/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
3863/// `ZonedDateTime::checked_add` or cloning the `ZonedDateTime` value.
3864impl<'a> core::ops::Add<Span> for ZonedDateTime {
3865    type Output = ZonedDateTime;
3866
3867    #[inline]
3868    fn add(self, rhs: Span) -> ZonedDateTime {
3869        self.checked_add_consuming(rhs)
3870            .expect("adding span to zoned datetime overflowed")
3871    }
3872}
3873
3874/// Adds a span of time to a borrowed zoned datetime.
3875///
3876/// This uses checked arithmetic and panics on overflow. To handle overflow
3877/// without panics, use [`ZonedDateTime::checked_add`].
3878impl<'a> core::ops::Add<Span> for &'a ZonedDateTime {
3879    type Output = ZonedDateTime;
3880
3881    #[inline]
3882    fn add(self, rhs: Span) -> ZonedDateTime {
3883        self.checked_add(rhs)
3884            .expect("adding span to zoned datetime overflowed")
3885    }
3886}
3887
3888/// Adds a span of time to a zoned datetime in place.
3889///
3890/// This uses checked arithmetic and panics on overflow. To handle overflow
3891/// without panics, use [`ZonedDateTime::checked_add`].
3892impl core::ops::AddAssign<Span> for ZonedDateTime {
3893    #[inline]
3894    fn add_assign(&mut self, rhs: Span) {
3895        *self = core::mem::take(self) + rhs;
3896    }
3897}
3898
3899/// Subtracts a span of time from a zoned datetime.
3900///
3901/// This uses checked arithmetic and panics on overflow. To handle overflow
3902/// without panics, use [`ZonedDateTime::checked_sub`].
3903///
3904/// Using this implementation will result in consuming the `ZonedDateTime`
3905/// value. Since it is not `Copy`, this will prevent further use. If this is
3906/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
3907/// `ZonedDateTime::checked_sub` or cloning the `ZonedDateTime` value.
3908impl<'a> core::ops::Sub<Span> for ZonedDateTime {
3909    type Output = ZonedDateTime;
3910
3911    #[inline]
3912    fn sub(self, rhs: Span) -> ZonedDateTime {
3913        self.checked_sub_consuming(rhs)
3914            .expect("subtracting span from zoned datetime overflowed")
3915    }
3916}
3917
3918/// Subtracts a span of time from a borrowed zoned datetime.
3919///
3920/// This uses checked arithmetic and panics on overflow. To handle overflow
3921/// without panics, use [`ZonedDateTime::checked_sub`].
3922impl<'a> core::ops::Sub<Span> for &'a ZonedDateTime {
3923    type Output = ZonedDateTime;
3924
3925    #[inline]
3926    fn sub(self, rhs: Span) -> ZonedDateTime {
3927        self.checked_sub(rhs)
3928            .expect("subtracting span from zoned datetime overflowed")
3929    }
3930}
3931
3932/// Subtracts a span of time from a zoned datetime in place.
3933///
3934/// This uses checked arithmetic and panics on overflow. To handle overflow
3935/// without panics, use [`ZonedDateTime::checked_sub`].
3936impl core::ops::SubAssign<Span> for ZonedDateTime {
3937    #[inline]
3938    fn sub_assign(&mut self, rhs: Span) {
3939        *self = core::mem::take(self) - rhs;
3940    }
3941}
3942
3943/// Computes the span of time between two zoned datetimes.
3944///
3945/// This will return a negative span when the zoned datetime being subtracted
3946/// is greater.
3947///
3948/// Since this uses the default configuration for calculating a span between
3949/// two zoned datetimes (no rounding and largest units is hours), this will
3950/// never panic or fail in any way. It is guaranteed that the largest non-zero
3951/// unit in the `Span` returned will be hours.
3952///
3953/// To configure the largest unit or enable rounding, use
3954/// [`ZonedDateTime::since`].
3955///
3956/// Using this implementation will result in consuming the `ZonedDateTime`
3957/// value. Since it is not `Copy`, this will prevent further use. If this is
3958/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
3959/// `ZonedDateTime::since`, `ZonedDateTime::until` or cloning the
3960/// `ZonedDateTime` value.
3961impl core::ops::Sub for ZonedDateTime {
3962    type Output = Span;
3963
3964    #[inline]
3965    fn sub(self, rhs: ZonedDateTime) -> Span {
3966        (&self).sub(&rhs)
3967    }
3968}
3969
3970/// Computes the span of time between two borrowed zoned datetimes.
3971///
3972/// This will return a negative span when the zoned datetime being subtracted
3973/// is greater.
3974///
3975/// Since this uses the default configuration for calculating a span between
3976/// two zoned datetimes (no rounding and largest units is hours), this will
3977/// never panic or fail in any way. It is guaranteed that the largest non-zero
3978/// unit in the `Span` returned will be hours.
3979///
3980/// To configure the largest unit or enable rounding, use
3981/// [`ZonedDateTime::since`].
3982impl<'a> core::ops::Sub for &'a ZonedDateTime {
3983    type Output = Span;
3984
3985    #[inline]
3986    fn sub(self, rhs: &'a ZonedDateTime) -> Span {
3987        self.since(rhs).expect("since never fails when given ZonedDateTime")
3988    }
3989}
3990
3991/// Adds a signed duration of time to a zoned datetime.
3992///
3993/// This uses checked arithmetic and panics on overflow. To handle overflow
3994/// without panics, use [`ZonedDateTime::checked_add`].
3995///
3996/// Using this implementation will result in consuming the `ZonedDateTime`
3997/// value. Since it is not `Copy`, this will prevent further use. If this is
3998/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
3999/// `ZonedDateTime::checked_add` or cloning the `ZonedDateTime` value.
4000impl core::ops::Add<SignedDuration> for ZonedDateTime {
4001    type Output = ZonedDateTime;
4002
4003    #[inline]
4004    fn add(self, rhs: SignedDuration) -> ZonedDateTime {
4005        self.checked_add_consuming(rhs)
4006            .expect("adding signed duration to zoned datetime overflowed")
4007    }
4008}
4009
4010/// Adds a signed duration of time to a borrowed zoned datetime.
4011///
4012/// This uses checked arithmetic and panics on overflow. To handle overflow
4013/// without panics, use [`ZonedDateTime::checked_add`].
4014impl<'a> core::ops::Add<SignedDuration> for &'a ZonedDateTime {
4015    type Output = ZonedDateTime;
4016
4017    #[inline]
4018    fn add(self, rhs: SignedDuration) -> ZonedDateTime {
4019        self.checked_add(rhs)
4020            .expect("adding signed duration to zoned datetime overflowed")
4021    }
4022}
4023
4024/// Adds a signed duration of time to a zoned datetime in place.
4025///
4026/// This uses checked arithmetic and panics on overflow. To handle overflow
4027/// without panics, use [`ZonedDateTime::checked_add`].
4028impl core::ops::AddAssign<SignedDuration> for ZonedDateTime {
4029    #[inline]
4030    fn add_assign(&mut self, rhs: SignedDuration) {
4031        *self = core::mem::take(self) + rhs;
4032    }
4033}
4034
4035/// Subtracts a signed duration of time from a zoned datetime.
4036///
4037/// This uses checked arithmetic and panics on overflow. To handle overflow
4038/// without panics, use [`ZonedDateTime::checked_sub`].
4039///
4040/// Using this implementation will result in consuming the `ZonedDateTime`
4041/// value. Since it is not `Copy`, this will prevent further use. If this is
4042/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
4043/// `ZonedDateTime::checked_sub` or cloning the `ZonedDateTime` value.
4044impl core::ops::Sub<SignedDuration> for ZonedDateTime {
4045    type Output = ZonedDateTime;
4046
4047    #[inline]
4048    fn sub(self, rhs: SignedDuration) -> ZonedDateTime {
4049        self.checked_sub_consuming(rhs).expect(
4050            "subtracting signed duration from zoned datetime overflowed",
4051        )
4052    }
4053}
4054
4055/// Subtracts a signed duration of time from a borrowed zoned datetime.
4056///
4057/// This uses checked arithmetic and panics on overflow. To handle overflow
4058/// without panics, use [`ZonedDateTime::checked_sub`].
4059impl<'a> core::ops::Sub<SignedDuration> for &'a ZonedDateTime {
4060    type Output = ZonedDateTime;
4061
4062    #[inline]
4063    fn sub(self, rhs: SignedDuration) -> ZonedDateTime {
4064        self.checked_sub(rhs).expect(
4065            "subtracting signed duration from zoned datetime overflowed",
4066        )
4067    }
4068}
4069
4070/// Subtracts a signed duration of time from a zoned datetime in place.
4071///
4072/// This uses checked arithmetic and panics on overflow. To handle overflow
4073/// without panics, use [`ZonedDateTime::checked_sub`].
4074impl core::ops::SubAssign<SignedDuration> for ZonedDateTime {
4075    #[inline]
4076    fn sub_assign(&mut self, rhs: SignedDuration) {
4077        *self = core::mem::take(self) - rhs;
4078    }
4079}
4080
4081/// Adds an unsigned duration of time to a zoned datetime.
4082///
4083/// This uses checked arithmetic and panics on overflow. To handle overflow
4084/// without panics, use [`ZonedDateTime::checked_add`].
4085///
4086/// Using this implementation will result in consuming the `ZonedDateTime`
4087/// value. Since it is not `Copy`, this will prevent further use. If this is
4088/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
4089/// `ZonedDateTime::checked_add` or cloning the `ZonedDateTime` value.
4090impl core::ops::Add<UnsignedDuration> for ZonedDateTime {
4091    type Output = ZonedDateTime;
4092
4093    #[inline]
4094    fn add(self, rhs: UnsignedDuration) -> ZonedDateTime {
4095        self.checked_add_consuming(rhs)
4096            .expect("adding unsigned duration to zoned datetime overflowed")
4097    }
4098}
4099
4100/// Adds an unsigned duration of time to a borrowed zoned datetime.
4101///
4102/// This uses checked arithmetic and panics on overflow. To handle overflow
4103/// without panics, use [`ZonedDateTime::checked_add`].
4104impl<'a> core::ops::Add<UnsignedDuration> for &'a ZonedDateTime {
4105    type Output = ZonedDateTime;
4106
4107    #[inline]
4108    fn add(self, rhs: UnsignedDuration) -> ZonedDateTime {
4109        self.checked_add(rhs)
4110            .expect("adding unsigned duration to zoned datetime overflowed")
4111    }
4112}
4113
4114/// Adds an unsigned duration of time to a zoned datetime in place.
4115///
4116/// This uses checked arithmetic and panics on overflow. To handle overflow
4117/// without panics, use [`ZonedDateTime::checked_add`].
4118impl core::ops::AddAssign<UnsignedDuration> for ZonedDateTime {
4119    #[inline]
4120    fn add_assign(&mut self, rhs: UnsignedDuration) {
4121        *self = core::mem::take(self) + rhs;
4122    }
4123}
4124
4125/// Subtracts an unsigned duration of time from a zoned datetime.
4126///
4127/// This uses checked arithmetic and panics on overflow. To handle overflow
4128/// without panics, use [`ZonedDateTime::checked_sub`].
4129///
4130/// Using this implementation will result in consuming the `ZonedDateTime`
4131/// value. Since it is not `Copy`, this will prevent further use. If this is
4132/// undesirable, consider using the trait implementation for `&ZonedDateTime`,
4133/// `ZonedDateTime::checked_sub` or cloning the `ZonedDateTime` value.
4134impl core::ops::Sub<UnsignedDuration> for ZonedDateTime {
4135    type Output = ZonedDateTime;
4136
4137    #[inline]
4138    fn sub(self, rhs: UnsignedDuration) -> ZonedDateTime {
4139        self.checked_sub_consuming(rhs).expect(
4140            "subtracting unsigned duration from zoned datetime overflowed",
4141        )
4142    }
4143}
4144
4145/// Subtracts an unsigned duration of time from a borrowed zoned datetime.
4146///
4147/// This uses checked arithmetic and panics on overflow. To handle overflow
4148/// without panics, use [`ZonedDateTime::checked_sub`].
4149impl<'a> core::ops::Sub<UnsignedDuration> for &'a ZonedDateTime {
4150    type Output = ZonedDateTime;
4151
4152    #[inline]
4153    fn sub(self, rhs: UnsignedDuration) -> ZonedDateTime {
4154        self.checked_sub(rhs).expect(
4155            "subtracting unsigned duration from zoned datetime overflowed",
4156        )
4157    }
4158}
4159
4160/// Subtracts an unsigned duration of time from a zoned datetime in place.
4161///
4162/// This uses checked arithmetic and panics on overflow. To handle overflow
4163/// without panics, use [`ZonedDateTime::checked_sub`].
4164impl core::ops::SubAssign<UnsignedDuration> for ZonedDateTime {
4165    #[inline]
4166    fn sub_assign(&mut self, rhs: UnsignedDuration) {
4167        *self = core::mem::take(self) - rhs;
4168    }
4169}
4170
4171#[cfg(feature = "serde")]
4172impl serde_core::Serialize for ZonedDateTime {
4173    #[inline]
4174    fn serialize<S: serde_core::Serializer>(
4175        &self,
4176        serializer: S,
4177    ) -> Result<S::Ok, S::Error> {
4178        serializer.collect_str(self)
4179    }
4180}
4181
4182#[cfg(feature = "serde")]
4183impl<'de> serde_core::Deserialize<'de> for ZonedDateTime {
4184    #[inline]
4185    fn deserialize<D: serde_core::Deserializer<'de>>(
4186        deserializer: D,
4187    ) -> Result<ZonedDateTime, D::Error> {
4188        use serde_core::de;
4189
4190        struct ZonedDateTimeVisitor;
4191
4192        impl<'de> de::Visitor<'de> for ZonedDateTimeVisitor {
4193            type Value = ZonedDateTime;
4194
4195            fn expecting(
4196                &self,
4197                f: &mut core::fmt::Formatter,
4198            ) -> core::fmt::Result {
4199                f.write_str("a zoned datetime string")
4200            }
4201
4202            #[inline]
4203            fn visit_bytes<E: de::Error>(
4204                self,
4205                value: &[u8],
4206            ) -> Result<ZonedDateTime, E> {
4207                DEFAULT_DATETIME_PARSER
4208                    .parse_zoned_datetime(value)
4209                    .map_err(de::Error::custom)
4210            }
4211
4212            #[inline]
4213            fn visit_str<E: de::Error>(
4214                self,
4215                value: &str,
4216            ) -> Result<ZonedDateTime, E> {
4217                self.visit_bytes(value.as_bytes())
4218            }
4219        }
4220
4221        deserializer.deserialize_str(ZonedDateTimeVisitor)
4222    }
4223}
4224
4225#[cfg(test)]
4226impl quickcheck::Arbitrary for ZonedDateTime {
4227    fn arbitrary(g: &mut quickcheck::Gen) -> ZonedDateTime {
4228        let timestamp = Timestamp::arbitrary(g);
4229        let tz = TimeZone::UTC; // TODO: do something better here?
4230        ZonedDateTime::new(timestamp, tz)
4231    }
4232
4233    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
4234        let timestamp = self.timestamp();
4235        alloc::boxed::Box::new(
4236            timestamp
4237                .shrink()
4238                .map(|timestamp| ZonedDateTime::new(timestamp, TimeZone::UTC)),
4239        )
4240    }
4241}
4242
4243/// An iterator over periodic zoned datetimes, created by
4244/// [`ZonedDateTime::series`].
4245///
4246/// It is exhausted when the next value would exceed the limits of a [`Span`]
4247/// or [`ZonedDateTime`] value.
4248///
4249/// This iterator is created by [`ZonedDateTime::series`].
4250#[derive(#[automatically_derived]impl ::core::clone::Clone for ZonedDateTimeSeries {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ZonedDateTimeSeries {
            start: ::core::clone::Clone::clone(&self.start),
            prev: ::core::clone::Clone::clone(&self.prev),
            period: ::core::clone::Clone::clone(&self.period),
            step: ::core::clone::Clone::clone(&self.step),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ZonedDateTimeSeries {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ZonedDateTimeSeries start prev period step", &self.start,
            &self.prev, &self.period, &&self.step)
    }
}Debug)]
4251pub struct ZonedDateTimeSeries {
4252    start: ZonedDateTime,
4253    prev: Option<Timestamp>,
4254    period: Span,
4255    step: i64,
4256}
4257
4258impl Iterator for ZonedDateTimeSeries {
4259    type Item = ZonedDateTime;
4260
4261    #[inline]
4262    fn next(&mut self) -> Option<ZonedDateTime> {
4263        // This loop is necessary because adding, e.g., `N * 1 day` may not
4264        // always result in a timestamp that is strictly greater than
4265        // `(N-1) * 1 day`. For example, `Pacific/Apia` never had `2011-12-30`
4266        // on their clocks. So adding `1 day` to `2011-12-29` yields the same
4267        // value as adding `2 days` (that is, `2011-12-31`).
4268        //
4269        // This may seem odd, but Temporal has the same behavior (as of
4270        // 2025-10-15):
4271        //
4272        //   >>> zdt = Temporal.ZonedDateTime.from("2011-12-29[Pacific/Apia]")
4273        //   Object { … }
4274        //   >>> zdt.toString()
4275        //   "2011-12-29T00:00:00-10:00[Pacific/Apia]"
4276        //   >>> zdt.add({days: 1}).toString()
4277        //   "2011-12-31T00:00:00+14:00[Pacific/Apia]"
4278        //   >>> zdt.add({days: 2}).toString()
4279        //   "2011-12-31T00:00:00+14:00[Pacific/Apia]"
4280        //
4281        // Since we are generating a time series specifically here, it seems
4282        // weird to yield two results that are equivalent instants in time.
4283        // So we use a loop here to guarantee that every instant yielded is
4284        // always strictly *after* the previous instant yielded.
4285        loop {
4286            let span = self.period.checked_mul(self.step).ok()?;
4287            self.step = self.step.checked_add(1)?;
4288            let zdt = self.start.checked_add(span).ok()?;
4289            if self.prev.map_or(true, |prev| {
4290                if self.period.is_positive() {
4291                    prev < zdt.timestamp()
4292                } else if self.period.is_negative() {
4293                    prev > zdt.timestamp()
4294                } else {
4295                    if !self.period.is_zero() {
    ::core::panicking::panic("assertion failed: self.period.is_zero()")
};assert!(self.period.is_zero());
4296                    // In the case of a zero span, the caller has clearly
4297                    // opted into an infinite repeating sequence.
4298                    true
4299                }
4300            }) {
4301                self.prev = Some(zdt.timestamp());
4302                return Some(zdt);
4303            }
4304        }
4305    }
4306}
4307
4308impl core::iter::FusedIterator for ZonedDateTimeSeries {}
4309
4310/// Options for [`Timestamp::checked_add`] and [`Timestamp::checked_sub`].
4311///
4312/// This type provides a way to ergonomically add one of a few different
4313/// duration types to a [`Timestamp`].
4314///
4315/// The main way to construct values of this type is with its `From` trait
4316/// implementations:
4317///
4318/// * `From<Span> for ZonedDateTimeArithmetic` adds (or subtracts) the given
4319/// span to the receiver timestamp.
4320/// * `From<SignedDuration> for ZonedDateTimeArithmetic` adds (or subtracts)
4321/// the given signed duration to the receiver timestamp.
4322/// * `From<std::time::Duration> for ZonedDateTimeArithmetic` adds (or
4323/// subtracts) the given unsigned duration to the receiver timestamp.
4324///
4325/// # Example
4326///
4327/// ```
4328/// use std::time::Duration;
4329///
4330/// use jiff::{SignedDuration, Timestamp, ToSpan};
4331///
4332/// let ts: Timestamp = "2024-02-28T00:00:00Z".parse()?;
4333/// assert_eq!(
4334///     ts.checked_add(48.hours())?,
4335///     "2024-03-01T00:00:00Z".parse()?,
4336/// );
4337/// assert_eq!(
4338///     ts.checked_add(SignedDuration::from_hours(48))?,
4339///     "2024-03-01T00:00:00Z".parse()?,
4340/// );
4341/// assert_eq!(
4342///     ts.checked_add(Duration::from_secs(48 * 60 * 60))?,
4343///     "2024-03-01T00:00:00Z".parse()?,
4344/// );
4345///
4346/// # Ok::<(), Box<dyn std::error::Error>>(())
4347/// ```
4348#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ZonedDateTimeArithmetic {
}
#[automatically_derived]impl ::core::clone::Clone for ZonedDateTimeArithmetic
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Duration>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ZonedDateTimeArithmetic
    {
}Copy, #[automatically_derived]impl ::core::fmt::Debug for ZonedDateTimeArithmetic {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ZonedDateTimeArithmetic duration", &&self.duration)
    }
}Debug)]
4349pub struct ZonedDateTimeArithmetic {
4350    duration: Duration,
4351}
4352
4353impl ZonedDateTimeArithmetic {
4354    #[inline]
4355    fn checked_add(self, zdt: ZonedDateTime) -> Result<ZonedDateTime, Error> {
4356        match self.duration.to_signed()? {
4357            SDuration::Span(span) => zdt.checked_add_span(span),
4358            SDuration::Absolute(sdur) => zdt.checked_add_duration(sdur),
4359        }
4360    }
4361
4362    #[inline]
4363    fn checked_neg(self) -> Result<ZonedDateTimeArithmetic, Error> {
4364        let duration = self.duration.checked_neg()?;
4365        Ok(ZonedDateTimeArithmetic { duration })
4366    }
4367
4368    #[inline]
4369    fn is_negative(&self) -> bool {
4370        self.duration.is_negative()
4371    }
4372}
4373
4374impl From<Span> for ZonedDateTimeArithmetic {
4375    fn from(span: Span) -> ZonedDateTimeArithmetic {
4376        let duration = Duration::from(span);
4377        ZonedDateTimeArithmetic { duration }
4378    }
4379}
4380
4381impl From<SignedDuration> for ZonedDateTimeArithmetic {
4382    fn from(sdur: SignedDuration) -> ZonedDateTimeArithmetic {
4383        let duration = Duration::from(sdur);
4384        ZonedDateTimeArithmetic { duration }
4385    }
4386}
4387
4388impl From<UnsignedDuration> for ZonedDateTimeArithmetic {
4389    fn from(udur: UnsignedDuration) -> ZonedDateTimeArithmetic {
4390        let duration = Duration::from(udur);
4391        ZonedDateTimeArithmetic { duration }
4392    }
4393}
4394
4395impl<'a> From<&'a Span> for ZonedDateTimeArithmetic {
4396    fn from(span: &'a Span) -> ZonedDateTimeArithmetic {
4397        ZonedDateTimeArithmetic::from(*span)
4398    }
4399}
4400
4401impl<'a> From<&'a SignedDuration> for ZonedDateTimeArithmetic {
4402    fn from(sdur: &'a SignedDuration) -> ZonedDateTimeArithmetic {
4403        ZonedDateTimeArithmetic::from(*sdur)
4404    }
4405}
4406
4407impl<'a> From<&'a UnsignedDuration> for ZonedDateTimeArithmetic {
4408    fn from(udur: &'a UnsignedDuration) -> ZonedDateTimeArithmetic {
4409        ZonedDateTimeArithmetic::from(*udur)
4410    }
4411}
4412
4413/// Options for [`ZonedDateTime::since`] and [`ZonedDateTime::until`].
4414///
4415/// This type provides a way to configure the calculation of spans between two
4416/// [`ZonedDateTime`] values. In particular, both `ZonedDateTime::since` and
4417/// `ZonedDateTime::until` accept anything that implements
4418/// `Into<ZonedDateTimeDifference>`. There are a few key trait implementations
4419/// that make this convenient:
4420///
4421/// * `From<&ZonedDateTime> for ZonedDateTimeDifference` will construct a
4422/// configuration consisting of just the zoned datetime. So for example,
4423/// `zdt1.since(zdt2)` returns the span from `zdt2` to `zdt1`.
4424/// * `From<(Unit, &ZonedDateTime)>` is a convenient way to specify the largest
4425/// units that should be present on the span returned. By default, the largest
4426/// units are days. Using this trait implementation is equivalent to
4427/// `ZonedDateTimeDifference::new(&zdt).largest(unit)`.
4428///
4429/// One can also provide a `ZonedDateTimeDifference` value directly. Doing so
4430/// is necessary to use the rounding features of calculating a span. For
4431/// example, setting the smallest unit (defaults to [`Unit::Nanosecond`]), the
4432/// rounding mode (defaults to [`RoundMode::Trunc`]) and the rounding increment
4433/// (defaults to `1`). The defaults are selected such that no rounding occurs.
4434///
4435/// Rounding a span as part of calculating it is provided as a convenience.
4436/// Callers may choose to round the span as a distinct step via
4437/// [`Span::round`], but callers may need to provide a reference date for
4438/// rounding larger units. By coupling rounding with routines like
4439/// [`ZonedDateTime::since`], the reference date can be set automatically based
4440/// on the input to `ZonedDateTime::since`.
4441///
4442/// # Example
4443///
4444/// This example shows how to round a span between two zoned datetimes to the
4445/// nearest half-hour, with ties breaking away from zero.
4446///
4447/// ```
4448/// use jiff::{
4449///     RoundMode, ToSpan, Unit, ZonedDateTime, ZonedDateTimeDifference,
4450/// };
4451///
4452/// let zdt1 = "2024-03-15 08:14:00.123456789[America/New_York]"
4453///     .parse::<ZonedDateTime>()?;
4454/// let zdt2 =
4455///     "2030-03-22 15:00[America/New_York]".parse::<ZonedDateTime>()?;
4456/// let span = zdt1.until(
4457///     ZonedDateTimeDifference::new(&zdt2)
4458///         .smallest(Unit::Minute)
4459///         .largest(Unit::Year)
4460///         .mode(RoundMode::HalfExpand)
4461///         .increment(30),
4462/// )?;
4463/// assert_eq!(span, 6.years().days(7).hours(7).fieldwise());
4464///
4465/// # Ok::<(), Box<dyn std::error::Error>>(())
4466/// ```
4467#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for ZonedDateTimeDifference<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for
    ZonedDateTimeDifference<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'a ZonedDateTime>;
        let _: ::core::clone::AssertParamIsClone<SpanRound<'static>>;
        *self
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for
    ZonedDateTimeDifference<'a> {
}Copy, #[automatically_derived]impl<'a> ::core::fmt::Debug for
    ZonedDateTimeDifference<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ZonedDateTimeDifference zoned round", &self.zoned, &&self.round)
    }
}Debug)]
4468pub struct ZonedDateTimeDifference<'a> {
4469    zoned: &'a ZonedDateTime,
4470    round: SpanRound<'static>,
4471}
4472
4473impl<'a> ZonedDateTimeDifference<'a> {
4474    /// Create a new default configuration for computing the span between the
4475    /// given zoned datetime and some other zoned datetime (specified as the
4476    /// receiver in [`ZonedDateTime::since`] or [`ZonedDateTime::until`]).
4477    #[inline]
4478    pub fn new(zoned: &'a ZonedDateTime) -> ZonedDateTimeDifference<'a> {
4479        // We use truncation rounding by default since it seems that's
4480        // what is generally expected when computing the difference between
4481        // datetimes.
4482        //
4483        // See: https://github.com/tc39/proposal-temporal/issues/1122
4484        let round = SpanRound::new().mode(RoundMode::Trunc);
4485        ZonedDateTimeDifference { zoned, round }
4486    }
4487
4488    /// Set the smallest units allowed in the span returned.
4489    ///
4490    /// When a largest unit is not specified and the smallest unit is hours
4491    /// or greater, then the largest unit is automatically set to be equal to
4492    /// the smallest unit.
4493    ///
4494    /// # Errors
4495    ///
4496    /// The smallest units must be no greater than the largest units. If this
4497    /// is violated, then computing a span with this configuration will result
4498    /// in an error.
4499    ///
4500    /// # Example
4501    ///
4502    /// This shows how to round a span between two zoned datetimes to the
4503    /// nearest number of weeks.
4504    ///
4505    /// ```
4506    /// use jiff::{
4507    ///     RoundMode, ToSpan, Unit, ZonedDateTime, ZonedDateTimeDifference,
4508    /// };
4509    ///
4510    /// let zdt1 =
4511    ///     "2024-03-15 08:14[America/New_York]".parse::<ZonedDateTime>()?;
4512    /// let zdt2 =
4513    ///     "2030-11-22 08:30[America/New_York]".parse::<ZonedDateTime>()?;
4514    /// let span = zdt1.until(
4515    ///     ZonedDateTimeDifference::new(&zdt2)
4516    ///         .smallest(Unit::Week)
4517    ///         .largest(Unit::Week)
4518    ///         .mode(RoundMode::HalfExpand),
4519    /// )?;
4520    /// assert_eq!(format!("{span:#}"), "349w");
4521    ///
4522    /// # Ok::<(), Box<dyn std::error::Error>>(())
4523    /// ```
4524    #[inline]
4525    pub fn smallest(self, unit: Unit) -> ZonedDateTimeDifference<'a> {
4526        ZonedDateTimeDifference { round: self.round.smallest(unit), ..self }
4527    }
4528
4529    /// Set the largest units allowed in the span returned.
4530    ///
4531    /// When a largest unit is not specified and the smallest unit is hours
4532    /// or greater, then the largest unit is automatically set to be equal to
4533    /// the smallest unit. Otherwise, when the largest unit is not specified,
4534    /// it is set to hours.
4535    ///
4536    /// Once a largest unit is set, there is no way to change this rounding
4537    /// configuration back to using the "automatic" default. Instead, callers
4538    /// must create a new configuration.
4539    ///
4540    /// # Errors
4541    ///
4542    /// The largest units, when set, must be at least as big as the smallest
4543    /// units (which defaults to [`Unit::Nanosecond`]). If this is violated,
4544    /// then computing a span with this configuration will result in an error.
4545    ///
4546    /// # Example
4547    ///
4548    /// This shows how to round a span between two zoned datetimes to units no
4549    /// bigger than seconds.
4550    ///
4551    /// ```
4552    /// use jiff::{ToSpan, Unit, ZonedDateTime, ZonedDateTimeDifference};
4553    ///
4554    /// let zdt1 =
4555    ///     "2024-03-15 08:14[America/New_York]".parse::<ZonedDateTime>()?;
4556    /// let zdt2 =
4557    ///     "2030-11-22 08:30[America/New_York]".parse::<ZonedDateTime>()?;
4558    /// let span = zdt1.until(
4559    ///     ZonedDateTimeDifference::new(&zdt2).largest(Unit::Second),
4560    /// )?;
4561    /// assert_eq!(span.to_string(), "PT211079760S");
4562    ///
4563    /// # Ok::<(), Box<dyn std::error::Error>>(())
4564    /// ```
4565    #[inline]
4566    pub fn largest(self, unit: Unit) -> ZonedDateTimeDifference<'a> {
4567        ZonedDateTimeDifference { round: self.round.largest(unit), ..self }
4568    }
4569
4570    /// Set the rounding mode.
4571    ///
4572    /// This defaults to [`RoundMode::Trunc`] since it's plausible that
4573    /// rounding "up" in the context of computing the span between
4574    /// two zoned datetimes could be surprising in a number of cases. The
4575    /// [`RoundMode::HalfExpand`] mode corresponds to typical rounding you
4576    /// might have learned about in school. But a variety of other rounding
4577    /// modes exist.
4578    ///
4579    /// # Example
4580    ///
4581    /// This shows how to always round "up" towards positive infinity.
4582    ///
4583    /// ```
4584    /// use jiff::{
4585    ///     RoundMode, ToSpan, Unit, ZonedDateTime, ZonedDateTimeDifference,
4586    /// };
4587    ///
4588    /// let zdt1 =
4589    ///     "2024-03-15 08:10[America/New_York]".parse::<ZonedDateTime>()?;
4590    /// let zdt2 =
4591    ///     "2024-03-15 08:11[America/New_York]".parse::<ZonedDateTime>()?;
4592    /// let span = zdt1.until(
4593    ///     ZonedDateTimeDifference::new(&zdt2)
4594    ///         .smallest(Unit::Hour)
4595    ///         .mode(RoundMode::Ceil),
4596    /// )?;
4597    /// // Only one minute elapsed, but we asked to always round up!
4598    /// assert_eq!(span, 1.hour().fieldwise());
4599    ///
4600    /// // Since `Ceil` always rounds toward positive infinity, the behavior
4601    /// // flips for a negative span.
4602    /// let span = zdt1.since(
4603    ///     ZonedDateTimeDifference::new(&zdt2)
4604    ///         .smallest(Unit::Hour)
4605    ///         .mode(RoundMode::Ceil),
4606    /// )?;
4607    /// assert_eq!(span, 0.hour().fieldwise());
4608    ///
4609    /// # Ok::<(), Box<dyn std::error::Error>>(())
4610    /// ```
4611    #[inline]
4612    pub fn mode(self, mode: RoundMode) -> ZonedDateTimeDifference<'a> {
4613        ZonedDateTimeDifference { round: self.round.mode(mode), ..self }
4614    }
4615
4616    /// Set the rounding increment for the smallest unit.
4617    ///
4618    /// The default value is `1`. Other values permit rounding the smallest
4619    /// unit to the nearest integer increment specified. For example, if the
4620    /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
4621    /// `30` would result in rounding in increments of a half hour. That is,
4622    /// the only minute value that could result would be `0` or `30`.
4623    ///
4624    /// # Errors
4625    ///
4626    /// When the smallest unit is less than days, the rounding increment must
4627    /// divide evenly into the next highest unit after the smallest unit
4628    /// configured (and must not be equivalent to it). For example, if the
4629    /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
4630    /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
4631    /// Namely, any integer that divides evenly into `1,000` nanoseconds since
4632    /// there are `1,000` nanoseconds in the next highest unit (microseconds).
4633    ///
4634    /// In all cases, the increment must be greater than zero and less than
4635    /// or equal to `1_000_000_000`.
4636    ///
4637    /// The error will occur when computing the span, and not when setting
4638    /// the increment here.
4639    ///
4640    /// # Example
4641    ///
4642    /// This shows how to round the span between two zoned datetimes to the
4643    /// nearest 5 minute increment.
4644    ///
4645    /// ```
4646    /// use jiff::{
4647    ///     RoundMode, ToSpan, Unit, ZonedDateTime, ZonedDateTimeDifference,
4648    /// };
4649    ///
4650    /// let zdt1 =
4651    ///     "2024-03-15 08:19[America/New_York]".parse::<ZonedDateTime>()?;
4652    /// let zdt2 =
4653    ///     "2024-03-15 12:52[America/New_York]".parse::<ZonedDateTime>()?;
4654    /// let span = zdt1.until(
4655    ///     ZonedDateTimeDifference::new(&zdt2)
4656    ///         .smallest(Unit::Minute)
4657    ///         .increment(5)
4658    ///         .mode(RoundMode::HalfExpand),
4659    /// )?;
4660    /// assert_eq!(format!("{span:#}"), "4h 35m");
4661    ///
4662    /// # Ok::<(), Box<dyn std::error::Error>>(())
4663    /// ```
4664    #[inline]
4665    pub fn increment(self, increment: i64) -> ZonedDateTimeDifference<'a> {
4666        ZonedDateTimeDifference {
4667            round: self.round.increment(increment),
4668            ..self
4669        }
4670    }
4671
4672    /// Returns true if and only if this configuration could change the span
4673    /// via rounding.
4674    #[inline]
4675    fn rounding_may_change_span(&self) -> bool {
4676        self.round.rounding_may_change_span()
4677    }
4678
4679    /// Returns the span of time from `dt1` to the datetime in this
4680    /// configuration. The biggest units allowed are determined by the
4681    /// `smallest` and `largest` settings, but defaults to `Unit::Day`.
4682    #[inline]
4683    fn until_with_largest_unit(
4684        &self,
4685        zdt1: &ZonedDateTime,
4686    ) -> Result<Span, Error> {
4687        let zdt2 = self.zoned;
4688
4689        let sign = Sign::from_ordinals(zdt2, zdt1);
4690        if sign.is_zero() {
4691            return Ok(Span::new());
4692        }
4693
4694        let largest = self
4695            .round
4696            .get_largest()
4697            .unwrap_or_else(|| self.round.get_smallest().max(Unit::Hour));
4698        if largest < Unit::Day {
4699            return zdt1.timestamp().until((largest, zdt2.timestamp()));
4700        }
4701        if zdt1.time_zone() != zdt2.time_zone() {
4702            return Err(Error::from(E::MismatchTimeZoneUntil { largest }));
4703        }
4704        let tz = zdt1.time_zone();
4705
4706        let dt1 = zdt1.datetime();
4707        let mut end_date = zdt2.date();
4708        if Sign::from_ordinals(end_date, dt1.date()) != sign {
4709            return zdt1.timestamp().until((Unit::Hour, zdt2.timestamp()));
4710        }
4711        let to_intermediate = |date: Date| {
4712            if date == dt1.date() {
4713                // Preserve the start's offset when it is in a fold.
4714                return Ok(zdt1.clone());
4715            }
4716            date.to_datetime(dt1.time())
4717                .to_zoned_datetime(tz.clone())
4718                .context(E::ConvertIntermediateDatetime)
4719        };
4720        // Only borrow a day when the intermediate timestamp passes the end.
4721        // Clock times alone can have the opposite order during a fold.
4722        let mut zmid = to_intermediate(end_date)?;
4723        if Sign::from_ordinals(zdt2, &zmid) == -sign {
4724            end_date = end_date
4725                .checked_add(Span::new().days(-sign.as_i64()))
4726                .context(E::AddDays)?;
4727            zmid = to_intermediate(end_date)?;
4728            // A skipped date can require a second correction.
4729            if Sign::from_ordinals(zdt2, &zmid) == -sign {
4730                end_date = end_date
4731                    .checked_add(Span::new().days(-sign.as_i64()))
4732                    .context(E::AddDays)?;
4733                zmid = to_intermediate(end_date)?;
4734                {
    match (&(Sign::from_ordinals(zdt2, &zmid)), &(-sign)) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("intermediate datetime should not pass the end after two day corrections")));
            }
        }
    }
};assert_ne!(
4735                    Sign::from_ordinals(zdt2, &zmid),
4736                    -sign,
4737                    "intermediate datetime should not pass the end \
4738                     after two day corrections",
4739                );
4740            }
4741        }
4742        let remainder =
4743            zdt2.timestamp().as_duration() - zmid.timestamp().as_duration();
4744
4745        let date_span = dt1.date().until((largest, end_date))?;
4746        Ok(Span::from_invariant_duration(Unit::Hour, remainder)
4747            .expect("difference between time always fits in span")
4748            .years(date_span.get_years())
4749            .months(date_span.get_months())
4750            .weeks(date_span.get_weeks())
4751            .days(date_span.get_days()))
4752    }
4753}
4754
4755impl<'a> From<&'a ZonedDateTime> for ZonedDateTimeDifference<'a> {
4756    #[inline]
4757    fn from(zdt: &'a ZonedDateTime) -> ZonedDateTimeDifference<'a> {
4758        ZonedDateTimeDifference::new(zdt)
4759    }
4760}
4761
4762impl<'a> From<(Unit, &'a ZonedDateTime)> for ZonedDateTimeDifference<'a> {
4763    #[inline]
4764    fn from(
4765        (largest, zdt): (Unit, &'a ZonedDateTime),
4766    ) -> ZonedDateTimeDifference<'a> {
4767        ZonedDateTimeDifference::new(zdt).largest(largest)
4768    }
4769}
4770
4771/// Options for [`ZonedDateTime::round`].
4772///
4773/// This type provides a way to configure the rounding of a zoned datetime. In
4774/// particular, `ZonedDateTime::round` accepts anything that implements the
4775/// `Into<ZonedDateTimeRound>` trait. There are some trait implementations that
4776/// therefore make calling `ZonedDateTime::round` in some common cases more
4777/// ergonomic:
4778///
4779/// * `From<Unit> for ZonedDateTimeRound` will construct a rounding
4780/// configuration that rounds to the unit given. Specifically,
4781/// `ZonedDateTimeRound::new().smallest(unit)`.
4782/// * `From<(Unit, i64)> for ZonedDateTimeRound` is like the one above, but
4783/// also specifies the rounding increment for
4784/// [`ZonedDateTimeRound::increment`].
4785///
4786/// Note that in the default configuration, no rounding occurs.
4787///
4788/// # Example
4789///
4790/// This example shows how to round a zoned datetime to the nearest second:
4791///
4792/// ```
4793/// use jiff::{Unit, ZonedDateTime, civil::date};
4794///
4795/// let zdt: ZonedDateTime =
4796///     "2024-06-20 16:24:59.5[America/New_York]".parse()?;
4797/// assert_eq!(
4798///     zdt.round(Unit::Second)?,
4799///     // The second rounds up and causes minutes to increase.
4800///     date(2024, 6, 20).at(16, 25, 0, 0).in_tz("America/New_York")?,
4801/// );
4802///
4803/// # Ok::<(), Box<dyn std::error::Error>>(())
4804/// ```
4805///
4806/// The above makes use of the fact that `Unit` implements
4807/// `Into<ZonedDateTimeRound>`. If you want to change the rounding mode to,
4808/// say, truncation, then you'll need to construct a `ZonedDateTimeRound`
4809/// explicitly since there are no convenience `Into` trait implementations for
4810/// [`RoundMode`].
4811///
4812/// ```
4813/// use jiff::{
4814///     RoundMode, Unit, ZonedDateTime, ZonedDateTimeRound, civil::date,
4815/// };
4816///
4817/// let zdt: ZonedDateTime =
4818///     "2024-06-20 16:24:59.5[America/New_York]".parse()?;
4819/// assert_eq!(
4820///     zdt.round(
4821///         ZonedDateTimeRound::new()
4822///             .smallest(Unit::Second)
4823///             .mode(RoundMode::Trunc),
4824///     )?,
4825///     // The second just gets truncated as if it wasn't there.
4826///     date(2024, 6, 20).at(16, 24, 59, 0).in_tz("America/New_York")?,
4827/// );
4828///
4829/// # Ok::<(), Box<dyn std::error::Error>>(())
4830/// ```
4831#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ZonedDateTimeRound {
}
#[automatically_derived]impl ::core::clone::Clone for ZonedDateTimeRound {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DateTimeRound>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ZonedDateTimeRound { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ZonedDateTimeRound {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ZonedDateTimeRound round", &&self.round)
    }
}Debug)]
4832pub struct ZonedDateTimeRound {
4833    round: DateTimeRound,
4834}
4835
4836impl ZonedDateTimeRound {
4837    /// Create a new default configuration for rounding a [`ZonedDateTime`].
4838    #[inline]
4839    pub fn new() -> ZonedDateTimeRound {
4840        ZonedDateTimeRound { round: DateTimeRound::new() }
4841    }
4842
4843    /// Set the smallest units allowed in the zoned datetime returned after
4844    /// rounding.
4845    ///
4846    /// Any units below the smallest configured unit will be used, along
4847    /// with the rounding increment and rounding mode, to determine
4848    /// the value of the smallest unit. For example, when rounding
4849    /// `2024-06-20T03:25:30[America/New_York]` to the nearest minute, the `30`
4850    /// second unit will result in rounding the minute unit of `25` up to `26`
4851    /// and zeroing out everything below minutes.
4852    ///
4853    /// This defaults to [`Unit::Nanosecond`].
4854    ///
4855    /// # Errors
4856    ///
4857    /// The smallest units must be no greater than [`Unit::Day`]. And when the
4858    /// smallest unit is `Unit::Day`, the rounding increment must be equal to
4859    /// `1`. Otherwise an error will be returned from [`ZonedDateTime::round`].
4860    ///
4861    /// # Example
4862    ///
4863    /// ```
4864    /// use jiff::{civil::date, Unit, ZonedDateTimeRound};
4865    ///
4866    /// let zdt = date(2024, 6, 20)
4867    ///     .at(3, 25, 30, 0)
4868    ///     .in_tz("America/New_York")?;
4869    /// assert_eq!(
4870    ///     zdt.round(ZonedDateTimeRound::new().smallest(Unit::Minute))?,
4871    ///     date(2024, 6, 20).at(3, 26, 0, 0).in_tz("America/New_York")?,
4872    /// );
4873    /// // Or, utilize the `From<Unit> for ZonedDateTimeRound` impl:
4874    /// assert_eq!(
4875    ///     zdt.round(Unit::Minute)?,
4876    ///     date(2024, 6, 20).at(3, 26, 0, 0).in_tz("America/New_York")?,
4877    /// );
4878    ///
4879    /// # Ok::<(), Box<dyn std::error::Error>>(())
4880    /// ```
4881    #[inline]
4882    pub fn smallest(self, unit: Unit) -> ZonedDateTimeRound {
4883        ZonedDateTimeRound { round: self.round.smallest(unit) }
4884    }
4885
4886    /// Set the rounding mode.
4887    ///
4888    /// This defaults to [`RoundMode::HalfExpand`], which rounds away from
4889    /// zero. It matches the kind of rounding you might have been taught in
4890    /// school.
4891    ///
4892    /// # Example
4893    ///
4894    /// This shows how to always round zoned datetimes up towards positive
4895    /// infinity.
4896    ///
4897    /// ```
4898    /// use jiff::{
4899    ///     RoundMode, Unit, ZonedDateTime, ZonedDateTimeRound, civil::date,
4900    /// };
4901    ///
4902    /// let zdt: ZonedDateTime =
4903    ///     "2024-06-20 03:25:01[America/New_York]".parse()?;
4904    /// assert_eq!(
4905    ///     zdt.round(
4906    ///         ZonedDateTimeRound::new()
4907    ///             .smallest(Unit::Minute)
4908    ///             .mode(RoundMode::Ceil),
4909    ///     )?,
4910    ///     date(2024, 6, 20).at(3, 26, 0, 0).in_tz("America/New_York")?,
4911    /// );
4912    ///
4913    /// # Ok::<(), Box<dyn std::error::Error>>(())
4914    /// ```
4915    #[inline]
4916    pub fn mode(self, mode: RoundMode) -> ZonedDateTimeRound {
4917        ZonedDateTimeRound { round: self.round.mode(mode) }
4918    }
4919
4920    /// Set the rounding increment for the smallest unit.
4921    ///
4922    /// The default value is `1`. Other values permit rounding the smallest
4923    /// unit to the nearest integer increment specified. For example, if the
4924    /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
4925    /// `30` would result in rounding in increments of a half hour. That is,
4926    /// the only minute value that could result would be `0` or `30`.
4927    ///
4928    /// # Errors
4929    ///
4930    /// When the smallest unit is `Unit::Day`, then the rounding increment must
4931    /// be `1` or else [`ZonedDateTime::round`] will return an error.
4932    ///
4933    /// For other units, the rounding increment must divide evenly into the
4934    /// next highest unit above the smallest unit set. The rounding increment
4935    /// must also not be equal to the next highest unit. For example, if the
4936    /// smallest unit is [`Unit::Nanosecond`], then *some* of the valid values
4937    /// for the rounding increment are `1`, `2`, `4`, `5`, `100` and `500`.
4938    /// Namely, any integer that divides evenly into `1,000` nanoseconds since
4939    /// there are `1,000` nanoseconds in the next highest unit (microseconds).
4940    ///
4941    /// In all cases, the increment must be greater than zero and less than or
4942    /// equal to `1_000_000_000`.
4943    ///
4944    /// # Example
4945    ///
4946    /// This example shows how to round a zoned datetime to the nearest 10
4947    /// minute increment.
4948    ///
4949    /// ```
4950    /// use jiff::{
4951    ///     RoundMode, Unit, ZonedDateTime, ZonedDateTimeRound, civil::date,
4952    /// };
4953    ///
4954    /// let zdt: ZonedDateTime =
4955    ///     "2024-06-20 03:24:59[America/New_York]".parse()?;
4956    /// assert_eq!(
4957    ///     zdt.round((Unit::Minute, 10))?,
4958    ///     date(2024, 6, 20).at(3, 20, 0, 0).in_tz("America/New_York")?,
4959    /// );
4960    ///
4961    /// # Ok::<(), Box<dyn std::error::Error>>(())
4962    /// ```
4963    #[inline]
4964    pub fn increment(self, increment: i64) -> ZonedDateTimeRound {
4965        ZonedDateTimeRound { round: self.round.increment(increment) }
4966    }
4967
4968    /// Does the actual rounding.
4969    ///
4970    /// Most of the work is farmed out to civil datetime rounding.
4971    pub(crate) fn round(
4972        &self,
4973        zdt: &ZonedDateTime,
4974    ) -> Result<ZonedDateTime, Error> {
4975        let start = zdt.datetime();
4976        if self.round.get_smallest() == Unit::Day {
4977            return self.round_days(zdt);
4978        }
4979        let end = self.round.round(start)?;
4980        // Like in the ZonedDateTimeWith API, in order to avoid small changes
4981        // to clock time hitting a 1 hour disambiguation shift, we use offset
4982        // conflict resolution to do our best to "prefer" the offset we already
4983        // have.
4984        let amb = OffsetConflict::PreferOffset.resolve(
4985            end,
4986            zdt.offset(),
4987            zdt.time_zone().clone(),
4988        )?;
4989        amb.compatible()
4990    }
4991
4992    /// Does rounding when the smallest unit is equal to days. We don't reuse
4993    /// civil datetime rounding for this since the length of a day for a zoned
4994    /// datetime might not be 24 hours.
4995    ///
4996    /// Ref: https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.round
4997    fn round_days(&self, zdt: &ZonedDateTime) -> Result<ZonedDateTime, Error> {
4998        if true {
    {
        match (&self.round.get_smallest(), &Unit::Day) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.round.get_smallest(), Unit::Day);
4999
5000        // Rounding by days requires an increment of 1. We just re-use the
5001        // civil datetime rounding checks, which has the same constraint.
5002        Increment::for_datetime(Unit::Day, self.round.get_increment())?;
5003
5004        // FIXME: We should be doing this with a &TimeZone, but will need a
5005        // refactor so that we do zone-aware arithmetic using just a Timestamp
5006        // and a &TimeZone. Fixing just this should just be some minor annoying
5007        // work. The grander refactor is something like an `Unzoned` type, but
5008        // I'm not sure that's really worth it. ---AG
5009        let start = zdt.start_of_day().context(E::FailedStartOfDay)?;
5010        let end = start.tomorrow().context(E::FailedLengthOfDay)?;
5011        // I don't believe this is actually possible, since adding 1 day should
5012        // always advance the underlying timestamp by some amount. On the
5013        // other hand, it's somewhat tricky to reason about this because of the
5014        // impact of time zone transition data on the length of a day. So we
5015        // conservatively report an error here.
5016        //
5017        // (The specific problem is that if `day_length` is zero, then our
5018        // rounding API will panic because it doesn't know what to do with a
5019        // zero increment.)
5020        if start.timestamp() == end.timestamp() {
5021            return Err(Error::from(E::FailedLengthOfDay));
5022        }
5023        let day_length =
5024            end.timestamp().as_duration() - start.timestamp().as_duration();
5025        let progress =
5026            zdt.timestamp().as_duration() - start.timestamp().as_duration();
5027        let rounded =
5028            self.round.get_mode().round_by_duration(progress, day_length)?;
5029        let nanos = start
5030            .timestamp()
5031            .as_duration()
5032            .checked_add(rounded)
5033            .ok_or(E::FailedSpanNanoseconds)?;
5034        Ok(Timestamp::from_duration(nanos)?
5035            .to_zoned_datetime(zdt.time_zone().clone()))
5036    }
5037}
5038
5039impl Default for ZonedDateTimeRound {
5040    #[inline]
5041    fn default() -> ZonedDateTimeRound {
5042        ZonedDateTimeRound::new()
5043    }
5044}
5045
5046impl From<Unit> for ZonedDateTimeRound {
5047    #[inline]
5048    fn from(unit: Unit) -> ZonedDateTimeRound {
5049        ZonedDateTimeRound::default().smallest(unit)
5050    }
5051}
5052
5053impl From<(Unit, i64)> for ZonedDateTimeRound {
5054    #[inline]
5055    fn from((unit, increment): (Unit, i64)) -> ZonedDateTimeRound {
5056        ZonedDateTimeRound::from(unit).increment(increment)
5057    }
5058}
5059
5060/// A builder for setting the fields on a [`ZonedDateTime`].
5061///
5062/// This builder is constructed via [`ZonedDateTime::with`].
5063///
5064/// # Example
5065///
5066/// The builder ensures one can chain together the individual components of a
5067/// zoned datetime without it failing at an intermediate step. For example,
5068/// if you had a date of `2024-10-31T00:00:00[America/New_York]` and wanted
5069/// to change both the day and the month, and each setting was validated
5070/// independent of the other, you would need to be careful to set the day first
5071/// and then the month. In some cases, you would need to set the month first
5072/// and then the day!
5073///
5074/// But with the builder, you can set values in any order:
5075///
5076/// ```
5077/// use jiff::civil::date;
5078///
5079/// let zdt1 = date(2024, 10, 31).at(0, 0, 0, 0).in_tz("America/New_York")?;
5080/// let zdt2 = zdt1.with().month(11).day(30).build()?;
5081/// assert_eq!(
5082///     zdt2,
5083///     date(2024, 11, 30).at(0, 0, 0, 0).in_tz("America/New_York")?,
5084/// );
5085///
5086/// let zdt1 = date(2024, 4, 30).at(0, 0, 0, 0).in_tz("America/New_York")?;
5087/// let zdt2 = zdt1.with().day(31).month(7).build()?;
5088/// assert_eq!(
5089///     zdt2,
5090///     date(2024, 7, 31).at(0, 0, 0, 0).in_tz("America/New_York")?,
5091/// );
5092///
5093/// # Ok::<(), Box<dyn std::error::Error>>(())
5094/// ```
5095#[derive(#[automatically_derived]impl ::core::clone::Clone for ZonedDateTimeWith {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ZonedDateTimeWith {
            original: ::core::clone::Clone::clone(&self.original),
            datetime_with: ::core::clone::Clone::clone(&self.datetime_with),
            offset: ::core::clone::Clone::clone(&self.offset),
            disambiguation: ::core::clone::Clone::clone(&self.disambiguation),
            offset_conflict: ::core::clone::Clone::clone(&self.offset_conflict),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ZonedDateTimeWith {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "ZonedDateTimeWith original datetime_with offset disambiguation offset_conflict",
            &self.original, &self.datetime_with, &self.offset,
            &self.disambiguation, &&self.offset_conflict)
    }
}Debug)]
5096pub struct ZonedDateTimeWith {
5097    original: ZonedDateTime,
5098    datetime_with: DateTimeWith,
5099    offset: Option<Offset>,
5100    disambiguation: Disambiguation,
5101    offset_conflict: OffsetConflict,
5102}
5103
5104impl ZonedDateTimeWith {
5105    #[inline]
5106    fn new(original: ZonedDateTime) -> ZonedDateTimeWith {
5107        let datetime_with = original.datetime().with();
5108        ZonedDateTimeWith {
5109            original,
5110            datetime_with,
5111            offset: None,
5112            disambiguation: Disambiguation::default(),
5113            offset_conflict: OffsetConflict::PreferOffset,
5114        }
5115    }
5116
5117    /// Create a new `ZonedDateTime` from the fields set on this configuration.
5118    ///
5119    /// An error occurs when the fields combine to an invalid zoned datetime.
5120    ///
5121    /// For any fields not set on this configuration, the values are taken from
5122    /// the [`ZonedDateTime`] that originally created this configuration. When
5123    /// no values are set, this routine is guaranteed to succeed and will
5124    /// always return the original zoned datetime without modification.
5125    ///
5126    /// # Example
5127    ///
5128    /// This creates a zoned datetime corresponding to the last day in the year
5129    /// at noon:
5130    ///
5131    /// ```
5132    /// use jiff::civil::date;
5133    ///
5134    /// let zdt = date(2023, 1, 1).at(12, 0, 0, 0).in_tz("America/New_York")?;
5135    /// assert_eq!(
5136    ///     zdt.with().day_of_year_no_leap(365).build()?,
5137    ///     date(2023, 12, 31).at(12, 0, 0, 0).in_tz("America/New_York")?,
5138    /// );
5139    ///
5140    /// // It also works with leap years for the same input:
5141    /// let zdt = date(2024, 1, 1).at(12, 0, 0, 0).in_tz("America/New_York")?;
5142    /// assert_eq!(
5143    ///     zdt.with().day_of_year_no_leap(365).build()?,
5144    ///     date(2024, 12, 31).at(12, 0, 0, 0).in_tz("America/New_York")?,
5145    /// );
5146    ///
5147    /// # Ok::<(), Box<dyn std::error::Error>>(())
5148    /// ```
5149    ///
5150    /// # Example: error for invalid zoned datetime
5151    ///
5152    /// If the fields combine to form an invalid datetime, then an error is
5153    /// returned:
5154    ///
5155    /// ```
5156    /// use jiff::civil::date;
5157    ///
5158    /// let zdt = date(2024, 11, 30)
5159    ///     .at(15, 30, 0, 0)
5160    ///     .in_tz("America/New_York")?;
5161    /// assert!(zdt.with().day(31).build().is_err());
5162    ///
5163    /// let zdt = date(2024, 2, 29)
5164    ///     .at(15, 30, 0, 0)
5165    ///     .in_tz("America/New_York")?;
5166    /// assert!(zdt.with().year(2023).build().is_err());
5167    ///
5168    /// # Ok::<(), Box<dyn std::error::Error>>(())
5169    /// ```
5170    #[inline]
5171    pub fn build(self) -> Result<ZonedDateTime, Error> {
5172        let dt = self.datetime_with.build()?;
5173        let ZonedDateTimeInner { offset, time_zone, .. } = self.original.inner;
5174        let offset = self.offset.unwrap_or(offset);
5175        let ambiguous = self.offset_conflict.resolve(dt, offset, time_zone)?;
5176        ambiguous.disambiguate(self.disambiguation)
5177    }
5178
5179    /// Set the year, month and day fields via the `Date` given.
5180    ///
5181    /// This overrides any previous year, month or day settings.
5182    ///
5183    /// # Example
5184    ///
5185    /// This shows how to create a new zoned datetime with a different date:
5186    ///
5187    /// ```
5188    /// use jiff::civil::date;
5189    ///
5190    /// let zdt1 = date(2005, 11, 5)
5191    ///     .at(15, 30, 0, 0)
5192    ///     .in_tz("America/New_York")?;
5193    /// let zdt2 = zdt1.with().date(date(2017, 10, 31)).build()?;
5194    /// // The date changes but the time remains the same.
5195    /// assert_eq!(
5196    ///     zdt2,
5197    ///     date(2017, 10, 31).at(15, 30, 0, 0).in_tz("America/New_York")?,
5198    /// );
5199    ///
5200    /// # Ok::<(), Box<dyn std::error::Error>>(())
5201    /// ```
5202    #[inline]
5203    pub fn date(self, date: Date) -> ZonedDateTimeWith {
5204        ZonedDateTimeWith {
5205            datetime_with: self.datetime_with.date(date),
5206            ..self
5207        }
5208    }
5209
5210    /// Set the hour, minute, second, millisecond, microsecond and nanosecond
5211    /// fields via the `Time` given.
5212    ///
5213    /// This overrides any previous hour, minute, second, millisecond,
5214    /// microsecond, nanosecond or subsecond nanosecond settings.
5215    ///
5216    /// # Example
5217    ///
5218    /// This shows how to create a new zoned datetime with a different time:
5219    ///
5220    /// ```
5221    /// use jiff::civil::{date, time};
5222    ///
5223    /// let zdt1 = date(2005, 11, 5)
5224    ///     .at(15, 30, 0, 0)
5225    ///     .in_tz("America/New_York")?;
5226    /// let zdt2 = zdt1.with().time(time(23, 59, 59, 123_456_789)).build()?;
5227    /// // The time changes but the date remains the same.
5228    /// assert_eq!(
5229    ///     zdt2,
5230    ///     date(2005, 11, 5)
5231    ///         .at(23, 59, 59, 123_456_789)
5232    ///         .in_tz("America/New_York")?,
5233    /// );
5234    ///
5235    /// # Ok::<(), Box<dyn std::error::Error>>(())
5236    /// ```
5237    #[inline]
5238    pub fn time(self, time: Time) -> ZonedDateTimeWith {
5239        ZonedDateTimeWith {
5240            datetime_with: self.datetime_with.time(time),
5241            ..self
5242        }
5243    }
5244
5245    /// Set the year field on a [`ZonedDateTime`].
5246    ///
5247    /// One can access this value via [`ZonedDateTime::year`].
5248    ///
5249    /// This overrides any previous year settings.
5250    ///
5251    /// # Errors
5252    ///
5253    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5254    /// the given year is outside the range `-9999..=9999`. This can also
5255    /// return an error if the resulting date is otherwise invalid.
5256    ///
5257    /// # Example
5258    ///
5259    /// This shows how to create a new zoned datetime with a different year:
5260    ///
5261    /// ```
5262    /// use jiff::civil::date;
5263    ///
5264    /// let zdt1 = date(2005, 11, 5)
5265    ///     .at(15, 30, 0, 0)
5266    ///     .in_tz("America/New_York")?;
5267    /// assert_eq!(zdt1.year(), 2005);
5268    /// let zdt2 = zdt1.with().year(2007).build()?;
5269    /// assert_eq!(zdt2.year(), 2007);
5270    ///
5271    /// # Ok::<(), Box<dyn std::error::Error>>(())
5272    /// ```
5273    ///
5274    /// # Example: only changing the year can fail
5275    ///
5276    /// For example, while `2024-02-29T01:30:00[America/New_York]` is valid,
5277    /// `2023-02-29T01:30:00[America/New_York]` is not:
5278    ///
5279    /// ```
5280    /// use jiff::civil::date;
5281    ///
5282    /// let zdt = date(2024, 2, 29).at(1, 30, 0, 0).in_tz("America/New_York")?;
5283    /// assert!(zdt.with().year(2023).build().is_err());
5284    ///
5285    /// # Ok::<(), Box<dyn std::error::Error>>(())
5286    /// ```
5287    #[inline]
5288    pub fn year(self, year: i16) -> ZonedDateTimeWith {
5289        ZonedDateTimeWith {
5290            datetime_with: self.datetime_with.year(year),
5291            ..self
5292        }
5293    }
5294
5295    /// Set the year of a zoned datetime via its era and its non-negative
5296    /// numeric component.
5297    ///
5298    /// One can access this value via [`ZonedDateTime::era_year`].
5299    ///
5300    /// # Errors
5301    ///
5302    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5303    /// the year is outside the range for the era specified. For [`Era::BCE`],
5304    /// the range is `1..=10000`. For [`Era::CE`], the range is `1..=9999`.
5305    ///
5306    /// # Example
5307    ///
5308    /// This shows that `CE` years are equivalent to the years used by this
5309    /// crate:
5310    ///
5311    /// ```
5312    /// use jiff::civil::{Era, date};
5313    ///
5314    /// let zdt1 = date(2005, 11, 5).at(8, 0, 0, 0).in_tz("America/New_York")?;
5315    /// assert_eq!(zdt1.year(), 2005);
5316    /// let zdt2 = zdt1.with().era_year(2007, Era::CE).build()?;
5317    /// assert_eq!(zdt2.year(), 2007);
5318    ///
5319    /// // CE years are always positive and can be at most 9999:
5320    /// assert!(zdt1.with().era_year(-5, Era::CE).build().is_err());
5321    /// assert!(zdt1.with().era_year(10_000, Era::CE).build().is_err());
5322    ///
5323    /// # Ok::<(), Box<dyn std::error::Error>>(())
5324    /// ```
5325    ///
5326    /// But `BCE` years always correspond to years less than or equal to `0`
5327    /// in this crate:
5328    ///
5329    /// ```
5330    /// use jiff::civil::{Era, date};
5331    ///
5332    /// let zdt1 = date(-27, 7, 1).at(8, 22, 30, 0).in_tz("America/New_York")?;
5333    /// assert_eq!(zdt1.year(), -27);
5334    /// assert_eq!(zdt1.era_year(), (28, Era::BCE));
5335    ///
5336    /// let zdt2 = zdt1.with().era_year(509, Era::BCE).build()?;
5337    /// assert_eq!(zdt2.year(), -508);
5338    /// assert_eq!(zdt2.era_year(), (509, Era::BCE));
5339    ///
5340    /// let zdt2 = zdt1.with().era_year(10_000, Era::BCE).build()?;
5341    /// assert_eq!(zdt2.year(), -9_999);
5342    /// assert_eq!(zdt2.era_year(), (10_000, Era::BCE));
5343    ///
5344    /// // BCE years are always positive and can be at most 10000:
5345    /// assert!(zdt1.with().era_year(-5, Era::BCE).build().is_err());
5346    /// assert!(zdt1.with().era_year(10_001, Era::BCE).build().is_err());
5347    ///
5348    /// # Ok::<(), Box<dyn std::error::Error>>(())
5349    /// ```
5350    ///
5351    /// # Example: overrides `ZonedDateTimeWith::year`
5352    ///
5353    /// Setting this option will override any previous
5354    /// `ZonedDateTimeWith::year` option:
5355    ///
5356    /// ```
5357    /// use jiff::civil::{Era, date};
5358    ///
5359    /// let zdt1 = date(2024, 7, 2)
5360    ///     .at(10, 27, 10, 123)
5361    ///     .in_tz("America/New_York")?;
5362    /// let zdt2 = zdt1.with().year(2000).era_year(1900, Era::CE).build()?;
5363    /// assert_eq!(
5364    ///     zdt2,
5365    ///     date(1900, 7, 2).at(10, 27, 10, 123).in_tz("America/New_York")?,
5366    /// );
5367    ///
5368    /// # Ok::<(), Box<dyn std::error::Error>>(())
5369    /// ```
5370    ///
5371    /// Similarly, `ZonedDateTimeWith::year` will override any previous call to
5372    /// `ZonedDateTimeWith::era_year`:
5373    ///
5374    /// ```
5375    /// use jiff::civil::{Era, date};
5376    ///
5377    /// let zdt1 = date(2024, 7, 2).at(19, 0, 1, 1).in_tz("America/New_York")?;
5378    /// let zdt2 = zdt1.with().era_year(1900, Era::CE).year(2000).build()?;
5379    /// assert_eq!(
5380    ///     zdt2,
5381    ///     date(2000, 7, 2).at(19, 0, 1, 1).in_tz("America/New_York")?,
5382    /// );
5383    ///
5384    /// # Ok::<(), Box<dyn std::error::Error>>(())
5385    /// ```
5386    #[inline]
5387    pub fn era_year(self, year: i16, era: Era) -> ZonedDateTimeWith {
5388        ZonedDateTimeWith {
5389            datetime_with: self.datetime_with.era_year(year, era),
5390            ..self
5391        }
5392    }
5393
5394    /// Set the month field on a [`ZonedDateTime`].
5395    ///
5396    /// One can access this value via [`ZonedDateTime::month`].
5397    ///
5398    /// This overrides any previous month settings.
5399    ///
5400    /// # Errors
5401    ///
5402    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5403    /// the given month is outside the range `1..=12`. This can also return an
5404    /// error if the resulting date is otherwise invalid.
5405    ///
5406    /// # Example
5407    ///
5408    /// This shows how to create a new zoned datetime with a different month:
5409    ///
5410    /// ```
5411    /// use jiff::civil::date;
5412    ///
5413    /// let zdt1 = date(2005, 11, 5)
5414    ///     .at(18, 3, 59, 123_456_789)
5415    ///     .in_tz("America/New_York")?;
5416    /// assert_eq!(zdt1.month(), 11);
5417    ///
5418    /// let zdt2 = zdt1.with().month(6).build()?;
5419    /// assert_eq!(zdt2.month(), 6);
5420    ///
5421    /// # Ok::<(), Box<dyn std::error::Error>>(())
5422    /// ```
5423    ///
5424    /// # Example: only changing the month can fail
5425    ///
5426    /// For example, while `2024-10-31T00:00:00[America/New_York]` is valid,
5427    /// `2024-11-31T00:00:00[America/New_York]` is not:
5428    ///
5429    /// ```
5430    /// use jiff::civil::date;
5431    ///
5432    /// let zdt = date(2024, 10, 31).at(0, 0, 0, 0).in_tz("America/New_York")?;
5433    /// assert!(zdt.with().month(11).build().is_err());
5434    ///
5435    /// # Ok::<(), Box<dyn std::error::Error>>(())
5436    /// ```
5437    #[inline]
5438    pub fn month(self, month: i8) -> ZonedDateTimeWith {
5439        ZonedDateTimeWith {
5440            datetime_with: self.datetime_with.month(month),
5441            ..self
5442        }
5443    }
5444
5445    /// Set the day field on a [`ZonedDateTime`].
5446    ///
5447    /// One can access this value via [`ZonedDateTime::day`].
5448    ///
5449    /// This overrides any previous day settings.
5450    ///
5451    /// # Errors
5452    ///
5453    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5454    /// the given given day is outside of allowable days for the corresponding
5455    /// year and month fields.
5456    ///
5457    /// # Example
5458    ///
5459    /// This shows some examples of setting the day, including a leap day:
5460    ///
5461    /// ```
5462    /// use jiff::civil::date;
5463    ///
5464    /// let zdt1 = date(2024, 2, 5)
5465    ///     .at(21, 59, 1, 999)
5466    ///     .in_tz("America/New_York")?;
5467    /// assert_eq!(zdt1.day(), 5);
5468    /// let zdt2 = zdt1.with().day(10).build()?;
5469    /// assert_eq!(zdt2.day(), 10);
5470    /// let zdt3 = zdt1.with().day(29).build()?;
5471    /// assert_eq!(zdt3.day(), 29);
5472    ///
5473    /// # Ok::<(), Box<dyn std::error::Error>>(())
5474    /// ```
5475    ///
5476    /// # Example: changing only the day can fail
5477    ///
5478    /// This shows some examples that will fail:
5479    ///
5480    /// ```
5481    /// use jiff::civil::date;
5482    ///
5483    /// let zdt1 = date(2023, 2, 5)
5484    ///     .at(22, 58, 58, 9_999)
5485    ///     .in_tz("America/New_York")?;
5486    /// // 2023 is not a leap year
5487    /// assert!(zdt1.with().day(29).build().is_err());
5488    ///
5489    /// // September has 30 days, not 31.
5490    /// let zdt1 = date(2023, 9, 5).in_tz("America/New_York")?;
5491    /// assert!(zdt1.with().day(31).build().is_err());
5492    ///
5493    /// # Ok::<(), Box<dyn std::error::Error>>(())
5494    /// ```
5495    #[inline]
5496    pub fn day(self, day: i8) -> ZonedDateTimeWith {
5497        ZonedDateTimeWith {
5498            datetime_with: self.datetime_with.day(day),
5499            ..self
5500        }
5501    }
5502
5503    /// Set the day field on a [`ZonedDateTime`] via the ordinal number of a
5504    /// day within a year.
5505    ///
5506    /// When used, any settings for month are ignored since the month is
5507    /// determined by the day of the year.
5508    ///
5509    /// The valid values for `day` are `1..=366`. Note though that `366` is
5510    /// only valid for leap years.
5511    ///
5512    /// This overrides any previous day settings.
5513    ///
5514    /// # Errors
5515    ///
5516    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5517    /// the given day is outside the allowed range of `1..=366`, or when a
5518    /// value of `366` is given for a non-leap year.
5519    ///
5520    /// # Example
5521    ///
5522    /// This demonstrates that if a year is a leap year, then `60` corresponds
5523    /// to February 29:
5524    ///
5525    /// ```
5526    /// use jiff::civil::date;
5527    ///
5528    /// let zdt = date(2024, 1, 1)
5529    ///     .at(23, 59, 59, 999_999_999)
5530    ///     .in_tz("America/New_York")?;
5531    /// assert_eq!(
5532    ///     zdt.with().day_of_year(60).build()?,
5533    ///     date(2024, 2, 29)
5534    ///         .at(23, 59, 59, 999_999_999)
5535    ///         .in_tz("America/New_York")?,
5536    /// );
5537    ///
5538    /// # Ok::<(), Box<dyn std::error::Error>>(())
5539    /// ```
5540    ///
5541    /// But for non-leap years, day 60 is March 1:
5542    ///
5543    /// ```
5544    /// use jiff::civil::date;
5545    ///
5546    /// let zdt = date(2023, 1, 1)
5547    ///     .at(23, 59, 59, 999_999_999)
5548    ///     .in_tz("America/New_York")?;
5549    /// assert_eq!(
5550    ///     zdt.with().day_of_year(60).build()?,
5551    ///     date(2023, 3, 1)
5552    ///         .at(23, 59, 59, 999_999_999)
5553    ///         .in_tz("America/New_York")?,
5554    /// );
5555    ///
5556    /// # Ok::<(), Box<dyn std::error::Error>>(())
5557    /// ```
5558    ///
5559    /// And using `366` for a non-leap year will result in an error, since
5560    /// non-leap years only have 365 days:
5561    ///
5562    /// ```
5563    /// use jiff::civil::date;
5564    ///
5565    /// let zdt = date(2023, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York")?;
5566    /// assert!(zdt.with().day_of_year(366).build().is_err());
5567    /// // The maximal year is not a leap year, so it returns an error too.
5568    /// let zdt = date(9999, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York")?;
5569    /// assert!(zdt.with().day_of_year(366).build().is_err());
5570    ///
5571    /// # Ok::<(), Box<dyn std::error::Error>>(())
5572    /// ```
5573    #[inline]
5574    pub fn day_of_year(self, day: i16) -> ZonedDateTimeWith {
5575        ZonedDateTimeWith {
5576            datetime_with: self.datetime_with.day_of_year(day),
5577            ..self
5578        }
5579    }
5580
5581    /// Set the day field on a [`ZonedDateTime`] via the ordinal number of a
5582    /// day within a year, but ignoring leap years.
5583    ///
5584    /// When used, any settings for month are ignored since the month is
5585    /// determined by the day of the year.
5586    ///
5587    /// The valid values for `day` are `1..=365`. The value `365` always
5588    /// corresponds to the last day of the year, even for leap years. It is
5589    /// impossible for this routine to return a zoned datetime corresponding to
5590    /// February 29. (Unless there is a relevant time zone transition that
5591    /// provokes disambiguation that shifts the datetime into February 29.)
5592    ///
5593    /// This overrides any previous day settings.
5594    ///
5595    /// # Errors
5596    ///
5597    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5598    /// the given day is outside the allowed range of `1..=365`.
5599    ///
5600    /// # Example
5601    ///
5602    /// This demonstrates that `60` corresponds to March 1, regardless of
5603    /// whether the year is a leap year or not:
5604    ///
5605    /// ```
5606    /// use jiff::civil::date;
5607    ///
5608    /// let zdt = date(2023, 1, 1)
5609    ///     .at(23, 59, 59, 999_999_999)
5610    ///     .in_tz("America/New_York")?;
5611    /// assert_eq!(
5612    ///     zdt.with().day_of_year_no_leap(60).build()?,
5613    ///     date(2023, 3, 1)
5614    ///         .at(23, 59, 59, 999_999_999)
5615    ///         .in_tz("America/New_York")?,
5616    /// );
5617    ///
5618    /// let zdt = date(2024, 1, 1)
5619    ///     .at(23, 59, 59, 999_999_999)
5620    ///     .in_tz("America/New_York")?;
5621    /// assert_eq!(
5622    ///     zdt.with().day_of_year_no_leap(60).build()?,
5623    ///     date(2024, 3, 1)
5624    ///         .at(23, 59, 59, 999_999_999)
5625    ///         .in_tz("America/New_York")?,
5626    /// );
5627    ///
5628    /// # Ok::<(), Box<dyn std::error::Error>>(())
5629    /// ```
5630    ///
5631    /// And using `365` for any year will always yield the last day of the
5632    /// year:
5633    ///
5634    /// ```
5635    /// use jiff::civil::date;
5636    ///
5637    /// let zdt = date(2023, 1, 1)
5638    ///     .at(23, 59, 59, 999_999_999)
5639    ///     .in_tz("America/New_York")?;
5640    /// assert_eq!(
5641    ///     zdt.with().day_of_year_no_leap(365).build()?,
5642    ///     zdt.last_of_year()?,
5643    /// );
5644    ///
5645    /// let zdt = date(2024, 1, 1)
5646    ///     .at(23, 59, 59, 999_999_999)
5647    ///     .in_tz("America/New_York")?;
5648    /// assert_eq!(
5649    ///     zdt.with().day_of_year_no_leap(365).build()?,
5650    ///     zdt.last_of_year()?,
5651    /// );
5652    ///
5653    /// // Careful at the boundaries. The last day of the year isn't
5654    /// // representable with all time zones. For example:
5655    /// let zdt = date(9999, 1, 1)
5656    ///     .at(23, 59, 59, 999_999_999)
5657    ///     .in_tz("America/New_York")?;
5658    /// assert!(zdt.with().day_of_year_no_leap(365).build().is_err());
5659    /// // But with other time zones, it works okay:
5660    /// let zdt =
5661    ///     date(9999, 1, 1).at(23, 59, 59, 999_999_999).to_zoned_datetime(
5662    ///         jiff::tz::TimeZone::fixed(jiff::tz::Offset::MAX),
5663    ///     )?;
5664    /// assert_eq!(
5665    ///     zdt.with().day_of_year_no_leap(365).build()?,
5666    ///     zdt.last_of_year()?,
5667    /// );
5668    ///
5669    /// # Ok::<(), Box<dyn std::error::Error>>(())
5670    /// ```
5671    ///
5672    /// A value of `366` is out of bounds, even for leap years:
5673    ///
5674    /// ```
5675    /// use jiff::civil::date;
5676    ///
5677    /// let zdt = date(2024, 1, 1).at(5, 30, 0, 0).in_tz("America/New_York")?;
5678    /// assert!(zdt.with().day_of_year_no_leap(366).build().is_err());
5679    ///
5680    /// # Ok::<(), Box<dyn std::error::Error>>(())
5681    /// ```
5682    #[inline]
5683    pub fn day_of_year_no_leap(self, day: i16) -> ZonedDateTimeWith {
5684        ZonedDateTimeWith {
5685            datetime_with: self.datetime_with.day_of_year_no_leap(day),
5686            ..self
5687        }
5688    }
5689
5690    /// Set the hour field on a [`ZonedDateTime`].
5691    ///
5692    /// One can access this value via [`ZonedDateTime::hour`].
5693    ///
5694    /// This overrides any previous hour settings.
5695    ///
5696    /// # Errors
5697    ///
5698    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5699    /// the given hour is outside the range `0..=23`.
5700    ///
5701    /// # Example
5702    ///
5703    /// ```
5704    /// use jiff::civil::time;
5705    ///
5706    /// let zdt1 = time(15, 21, 59, 0)
5707    ///     .on(2010, 6, 1)
5708    ///     .in_tz("America/New_York")?;
5709    /// assert_eq!(zdt1.hour(), 15);
5710    /// let zdt2 = zdt1.with().hour(3).build()?;
5711    /// assert_eq!(zdt2.hour(), 3);
5712    ///
5713    /// # Ok::<(), Box<dyn std::error::Error>>(())
5714    /// ```
5715    #[inline]
5716    pub fn hour(self, hour: i8) -> ZonedDateTimeWith {
5717        ZonedDateTimeWith {
5718            datetime_with: self.datetime_with.hour(hour),
5719            ..self
5720        }
5721    }
5722
5723    /// Set the minute field on a [`ZonedDateTime`].
5724    ///
5725    /// One can access this value via [`ZonedDateTime::minute`].
5726    ///
5727    /// This overrides any previous minute settings.
5728    ///
5729    /// # Errors
5730    ///
5731    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5732    /// the given minute is outside the range `0..=59`.
5733    ///
5734    /// # Example
5735    ///
5736    /// ```
5737    /// use jiff::civil::time;
5738    ///
5739    /// let zdt1 = time(15, 21, 59, 0)
5740    ///     .on(2010, 6, 1)
5741    ///     .in_tz("America/New_York")?;
5742    /// assert_eq!(zdt1.minute(), 21);
5743    /// let zdt2 = zdt1.with().minute(3).build()?;
5744    /// assert_eq!(zdt2.minute(), 3);
5745    ///
5746    /// # Ok::<(), Box<dyn std::error::Error>>(())
5747    /// ```
5748    #[inline]
5749    pub fn minute(self, minute: i8) -> ZonedDateTimeWith {
5750        ZonedDateTimeWith {
5751            datetime_with: self.datetime_with.minute(minute),
5752            ..self
5753        }
5754    }
5755
5756    /// Set the second field on a [`ZonedDateTime`].
5757    ///
5758    /// One can access this value via [`ZonedDateTime::second`].
5759    ///
5760    /// This overrides any previous second settings.
5761    ///
5762    /// # Errors
5763    ///
5764    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5765    /// the given second is outside the range `0..=59`.
5766    ///
5767    /// # Example
5768    ///
5769    /// ```
5770    /// use jiff::civil::time;
5771    ///
5772    /// let zdt1 = time(15, 21, 59, 0)
5773    ///     .on(2010, 6, 1)
5774    ///     .in_tz("America/New_York")?;
5775    /// assert_eq!(zdt1.second(), 59);
5776    /// let zdt2 = zdt1.with().second(3).build()?;
5777    /// assert_eq!(zdt2.second(), 3);
5778    ///
5779    /// # Ok::<(), Box<dyn std::error::Error>>(())
5780    /// ```
5781    #[inline]
5782    pub fn second(self, second: i8) -> ZonedDateTimeWith {
5783        ZonedDateTimeWith {
5784            datetime_with: self.datetime_with.second(second),
5785            ..self
5786        }
5787    }
5788
5789    /// Set the millisecond field on a [`ZonedDateTime`].
5790    ///
5791    /// One can access this value via [`ZonedDateTime::millisecond`].
5792    ///
5793    /// This overrides any previous millisecond settings.
5794    ///
5795    /// Note that this only sets the millisecond component. It does
5796    /// not change the microsecond or nanosecond components. To set
5797    /// the fractional second component to nanosecond precision, use
5798    /// [`ZonedDateTimeWith::subsec_nanosecond`].
5799    ///
5800    /// # Errors
5801    ///
5802    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5803    /// the given millisecond is outside the range `0..=999`, or if both this
5804    /// and [`ZonedDateTimeWith::subsec_nanosecond`] are set.
5805    ///
5806    /// # Example
5807    ///
5808    /// This shows the relationship between [`ZonedDateTime::millisecond`] and
5809    /// [`ZonedDateTime::subsec_nanosecond`]:
5810    ///
5811    /// ```
5812    /// use jiff::civil::time;
5813    ///
5814    /// let zdt1 = time(15, 21, 35, 0)
5815    ///     .on(2010, 6, 1)
5816    ///     .in_tz("America/New_York")?;
5817    /// let zdt2 = zdt1.with().millisecond(123).build()?;
5818    /// assert_eq!(zdt2.subsec_nanosecond(), 123_000_000);
5819    ///
5820    /// # Ok::<(), Box<dyn std::error::Error>>(())
5821    /// ```
5822    #[inline]
5823    pub fn millisecond(self, millisecond: i16) -> ZonedDateTimeWith {
5824        ZonedDateTimeWith {
5825            datetime_with: self.datetime_with.millisecond(millisecond),
5826            ..self
5827        }
5828    }
5829
5830    /// Set the microsecond field on a [`ZonedDateTime`].
5831    ///
5832    /// One can access this value via [`ZonedDateTime::microsecond`].
5833    ///
5834    /// This overrides any previous microsecond settings.
5835    ///
5836    /// Note that this only sets the microsecond component. It does
5837    /// not change the millisecond or nanosecond components. To set
5838    /// the fractional second component to nanosecond precision, use
5839    /// [`ZonedDateTimeWith::subsec_nanosecond`].
5840    ///
5841    /// # Errors
5842    ///
5843    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5844    /// the given microsecond is outside the range `0..=999`, or if both this
5845    /// and [`ZonedDateTimeWith::subsec_nanosecond`] are set.
5846    ///
5847    /// # Example
5848    ///
5849    /// This shows the relationship between [`ZonedDateTime::microsecond`] and
5850    /// [`ZonedDateTime::subsec_nanosecond`]:
5851    ///
5852    /// ```
5853    /// use jiff::civil::time;
5854    ///
5855    /// let zdt1 = time(15, 21, 35, 0)
5856    ///     .on(2010, 6, 1)
5857    ///     .in_tz("America/New_York")?;
5858    /// let zdt2 = zdt1.with().microsecond(123).build()?;
5859    /// assert_eq!(zdt2.subsec_nanosecond(), 123_000);
5860    ///
5861    /// # Ok::<(), Box<dyn std::error::Error>>(())
5862    /// ```
5863    #[inline]
5864    pub fn microsecond(self, microsecond: i16) -> ZonedDateTimeWith {
5865        ZonedDateTimeWith {
5866            datetime_with: self.datetime_with.microsecond(microsecond),
5867            ..self
5868        }
5869    }
5870
5871    /// Set the nanosecond field on a [`ZonedDateTime`].
5872    ///
5873    /// One can access this value via [`ZonedDateTime::nanosecond`].
5874    ///
5875    /// This overrides any previous nanosecond settings.
5876    ///
5877    /// Note that this only sets the nanosecond component. It does
5878    /// not change the millisecond or microsecond components. To set
5879    /// the fractional second component to nanosecond precision, use
5880    /// [`ZonedDateTimeWith::subsec_nanosecond`].
5881    ///
5882    /// # Errors
5883    ///
5884    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5885    /// the given nanosecond is outside the range `0..=999`, or if both this
5886    /// and [`ZonedDateTimeWith::subsec_nanosecond`] are set.
5887    ///
5888    /// # Example
5889    ///
5890    /// This shows the relationship between [`ZonedDateTime::nanosecond`] and
5891    /// [`ZonedDateTime::subsec_nanosecond`]:
5892    ///
5893    /// ```
5894    /// use jiff::civil::time;
5895    ///
5896    /// let zdt1 = time(15, 21, 35, 0)
5897    ///     .on(2010, 6, 1)
5898    ///     .in_tz("America/New_York")?;
5899    /// let zdt2 = zdt1.with().nanosecond(123).build()?;
5900    /// assert_eq!(zdt2.subsec_nanosecond(), 123);
5901    ///
5902    /// # Ok::<(), Box<dyn std::error::Error>>(())
5903    /// ```
5904    #[inline]
5905    pub fn nanosecond(self, nanosecond: i16) -> ZonedDateTimeWith {
5906        ZonedDateTimeWith {
5907            datetime_with: self.datetime_with.nanosecond(nanosecond),
5908            ..self
5909        }
5910    }
5911
5912    /// Set the subsecond nanosecond field on a [`ZonedDateTime`].
5913    ///
5914    /// If you want to access this value on `ZonedDateTime`, then use
5915    /// [`ZonedDateTime::subsec_nanosecond`].
5916    ///
5917    /// This overrides any previous subsecond nanosecond settings.
5918    ///
5919    /// Note that this sets the entire fractional second component to
5920    /// nanosecond precision, and overrides any individual millisecond,
5921    /// microsecond or nanosecond settings. To set individual components, use
5922    /// [`ZonedDateTimeWith::millisecond`], [`ZonedDateTimeWith::microsecond`]
5923    /// or [`ZonedDateTimeWith::nanosecond`].
5924    ///
5925    /// # Errors
5926    ///
5927    /// This returns an error when [`ZonedDateTimeWith::build`] is called if
5928    /// the given subsecond nanosecond is outside the range `0..=999,999,999`,
5929    /// or if both this and one of [`ZonedDateTimeWith::millisecond`],
5930    /// [`ZonedDateTimeWith::microsecond`] or [`ZonedDateTimeWith::nanosecond`]
5931    /// are set.
5932    ///
5933    /// # Example
5934    ///
5935    /// This shows the relationship between constructing a `ZonedDateTime`
5936    /// value with subsecond nanoseconds and its individual subsecond fields:
5937    ///
5938    /// ```
5939    /// use jiff::civil::time;
5940    ///
5941    /// let zdt1 = time(15, 21, 35, 0)
5942    ///     .on(2010, 6, 1)
5943    ///     .in_tz("America/New_York")?;
5944    /// let zdt2 = zdt1.with().subsec_nanosecond(123_456_789).build()?;
5945    /// assert_eq!(zdt2.millisecond(), 123);
5946    /// assert_eq!(zdt2.microsecond(), 456);
5947    /// assert_eq!(zdt2.nanosecond(), 789);
5948    ///
5949    /// # Ok::<(), Box<dyn std::error::Error>>(())
5950    /// ```
5951    #[inline]
5952    pub fn subsec_nanosecond(
5953        self,
5954        subsec_nanosecond: i32,
5955    ) -> ZonedDateTimeWith {
5956        ZonedDateTimeWith {
5957            datetime_with: self
5958                .datetime_with
5959                .subsec_nanosecond(subsec_nanosecond),
5960            ..self
5961        }
5962    }
5963
5964    /// Set the offset to use in the new zoned datetime.
5965    ///
5966    /// This can be used in some cases to explicitly disambiguate a datetime
5967    /// that could correspond to multiple instants in time.
5968    ///
5969    /// How the offset is used to construct a new zoned datetime depends on the
5970    /// offset conflict resolution strategy set via
5971    /// [`ZonedDateTimeWith::offset_conflict`]. The default is
5972    /// [`OffsetConflict::PreferOffset`], which will always try to use the
5973    /// offset to resolve a datetime to an instant, unless the offset is
5974    /// incorrect for this zoned datetime's time zone. In which case, only the
5975    /// time zone is used to select the correct offset (which may involve using
5976    /// the disambiguation strategy set via
5977    /// [`ZonedDateTimeWith::disambiguation`]).
5978    ///
5979    /// # Example
5980    ///
5981    /// This example shows parsing the first time the 1 o'clock hour appeared
5982    /// on a clock in New York on 2024-11-03, and then changing only the
5983    /// offset to flip it to the second time 1 o'clock appeared on the clock:
5984    ///
5985    /// ```
5986    /// use jiff::{ZonedDateTime, tz};
5987    ///
5988    /// let zdt1: ZonedDateTime =
5989    ///     "2024-11-03 01:30-04[America/New_York]".parse()?;
5990    /// let zdt2 = zdt1.with().offset(tz::offset(-5)).build()?;
5991    /// assert_eq!(
5992    ///     zdt2.to_string(),
5993    ///     // Everything stays the same, except for the offset.
5994    ///     "2024-11-03T01:30:00-05:00[America/New_York]",
5995    /// );
5996    ///
5997    /// // If we use an invalid offset for the America/New_York time zone,
5998    /// // then it will be ignored and the disambiguation strategy set will
5999    /// // be used.
6000    /// let zdt3 = zdt1.with().offset(tz::offset(-12)).build()?;
6001    /// assert_eq!(
6002    ///     zdt3.to_string(),
6003    ///     // The default disambiguation is Compatible.
6004    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
6005    /// );
6006    /// // But we could change the disambiguation strategy to reject such
6007    /// // cases!
6008    /// let result = zdt1
6009    ///     .with()
6010    ///     .offset(tz::offset(-12))
6011    ///     .disambiguation(tz::Disambiguation::Reject)
6012    ///     .build();
6013    /// assert!(result.is_err());
6014    ///
6015    /// # Ok::<(), Box<dyn std::error::Error>>(())
6016    /// ```
6017    #[inline]
6018    pub fn offset(self, offset: Offset) -> ZonedDateTimeWith {
6019        ZonedDateTimeWith { offset: Some(offset), ..self }
6020    }
6021
6022    /// Set the conflict resolution strategy for when an offset is inconsistent
6023    /// with the time zone.
6024    ///
6025    /// See the documentation on [`OffsetConflict`] for more details about the
6026    /// different strategies one can choose.
6027    ///
6028    /// Unlike parsing (where the default is `OffsetConflict::Reject`), the
6029    /// default for `ZonedDateTimeWith` is [`OffsetConflict::PreferOffset`],
6030    /// which avoids daylight saving time disambiguation causing unexpected
6031    /// 1-hour shifts after small changes to clock time.
6032    ///
6033    /// # Example
6034    ///
6035    /// ```
6036    /// use jiff::ZonedDateTime;
6037    ///
6038    /// // Set to the "second" time 1:30 is on the clocks in New York on
6039    /// // 2024-11-03. The offset in the datetime string makes this
6040    /// // unambiguous.
6041    /// let zdt1 = "2024-11-03T01:30-05[America/New_York]"
6042    ///     .parse::<ZonedDateTime>()?;
6043    /// // Now we change the minute field:
6044    /// let zdt2 = zdt1.with().minute(34).build()?;
6045    /// assert_eq!(
6046    ///     zdt2.to_string(),
6047    ///     // Without taking the offset of the `ZonedDateTime` value into
6048    ///     // account, this would have defaulted to using the "compatible"
6049    ///     // disambiguation strategy, which would have selected the earlier
6050    ///     // offset of -04 instead of sticking with the later offset of -05.
6051    ///     "2024-11-03T01:34:00-05:00[America/New_York]",
6052    /// );
6053    ///
6054    /// // But note that if we change the clock time such that the previous
6055    /// // offset is no longer valid (by moving back before DST ended), then
6056    /// // the default strategy will automatically adapt and change the offset.
6057    /// let zdt2 = zdt1.with().hour(0).build()?;
6058    /// assert_eq!(
6059    ///     zdt2.to_string(),
6060    ///     "2024-11-03T00:30:00-04:00[America/New_York]",
6061    /// );
6062    ///
6063    /// # Ok::<(), Box<dyn std::error::Error>>(())
6064    /// ```
6065    #[inline]
6066    pub fn offset_conflict(
6067        self,
6068        strategy: OffsetConflict,
6069    ) -> ZonedDateTimeWith {
6070        ZonedDateTimeWith { offset_conflict: strategy, ..self }
6071    }
6072
6073    /// Set the disambiguation strategy for when a zoned datetime falls into a
6074    /// time zone transition "fold" or "gap."
6075    ///
6076    /// The most common manifestation of such time zone transitions is daylight
6077    /// saving time. In most cases, the transition into daylight saving time
6078    /// moves the civil time ("the time you see on the clock") ahead one hour.
6079    /// This is called a "gap" because an hour on the clock is skipped. While
6080    /// the transition out of daylight saving time moves the civil time back
6081    /// one hour. This is called a "fold" because an hour on the clock is
6082    /// repeated.
6083    ///
6084    /// In the case of a gap, an ambiguous datetime manifests as a time that
6085    /// never appears on a clock. (For example, `02:30` on `2024-03-10` in New
6086    /// York.) In the case of a fold, an ambiguous datetime manifests as a
6087    /// time that repeats itself. (For example, `01:30` on `2024-11-03` in New
6088    /// York.) So when a fold occurs, you don't know whether it's the "first"
6089    /// occurrence of that time or the "second."
6090    ///
6091    /// Time zone transitions are not just limited to daylight saving time,
6092    /// although those are the most common. In other cases, a transition occurs
6093    /// because of a change in the offset of the time zone itself. (See the
6094    /// examples below.)
6095    ///
6096    /// # Example: time zone offset change
6097    ///
6098    /// In this example, we explore a time zone offset change in Hawaii that
6099    /// occurred on `1947-06-08`. Namely, Hawaii went from a `-10:30` offset
6100    /// to a `-10:00` offset at `02:00`. This results in a 30 minute gap in
6101    /// civil time.
6102    ///
6103    /// ```
6104    /// use jiff::{ToSpan, ZonedDateTime, civil::date, tz};
6105    ///
6106    /// // This datetime is unambiguous...
6107    /// let zdt1 =
6108    ///     "1943-06-02T02:05[Pacific/Honolulu]".parse::<ZonedDateTime>()?;
6109    /// // but... 02:05 didn't exist on clocks on 1947-06-08.
6110    /// let zdt2 = zdt1
6111    ///     .with()
6112    ///     .disambiguation(tz::Disambiguation::Later)
6113    ///     .year(1947)
6114    ///     .day(8)
6115    ///     .build()?;
6116    /// // Our parser is configured to select the later time, so we jump to
6117    /// // 02:35. But if we used `Disambiguation::Earlier`, then we'd get
6118    /// // 01:35.
6119    /// assert_eq!(zdt2.datetime(), date(1947, 6, 8).at(2, 35, 0, 0));
6120    /// assert_eq!(zdt2.offset(), tz::offset(-10));
6121    ///
6122    /// // If we subtract 10 minutes from 02:35, notice that we (correctly)
6123    /// // jump to 01:55 *and* our offset is corrected to -10:30.
6124    /// let zdt3 = zdt2.checked_sub(10.minutes())?;
6125    /// assert_eq!(zdt3.datetime(), date(1947, 6, 8).at(1, 55, 0, 0));
6126    /// assert_eq!(
6127    ///     zdt3.offset(),
6128    ///     tz::offset(-10).saturating_sub(30.minutes())?,
6129    /// );
6130    ///
6131    /// # Ok::<(), Box<dyn std::error::Error>>(())
6132    /// ```
6133    ///
6134    /// # Example: offset conflict resolution and disambiguation
6135    ///
6136    /// This example shows how the disambiguation configuration can
6137    /// interact with the default offset conflict resolution strategy of
6138    /// [`OffsetConflict::PreferOffset`]:
6139    ///
6140    /// ```
6141    /// use jiff::{ZonedDateTime, civil::date, tz};
6142    ///
6143    /// // This datetime is unambiguous.
6144    /// let zdt1 =
6145    ///     "2024-03-11T02:05[America/New_York]".parse::<ZonedDateTime>()?;
6146    /// assert_eq!(zdt1.offset(), tz::offset(-4));
6147    /// // But the same time on March 10 is ambiguous because there is a gap!
6148    /// let zdt2 = zdt1
6149    ///     .with()
6150    ///     .disambiguation(tz::Disambiguation::Earlier)
6151    ///     .day(10)
6152    ///     .build()?;
6153    /// assert_eq!(zdt2.datetime(), date(2024, 3, 10).at(1, 5, 0, 0));
6154    /// assert_eq!(zdt2.offset(), tz::offset(-5));
6155    ///
6156    /// # Ok::<(), Box<dyn std::error::Error>>(())
6157    /// ```
6158    ///
6159    /// Namely, while we started with an offset of `-04`, it (along with all
6160    /// other offsets) are considered invalid during civil time gaps due to
6161    /// time zone transitions (such as the beginning of daylight saving time in
6162    /// most locations).
6163    ///
6164    /// The default disambiguation strategy is
6165    /// [`Disambiguation::Compatible`], which in the case of gaps, chooses the
6166    /// time after the gap:
6167    ///
6168    /// ```
6169    /// use jiff::{ZonedDateTime, civil::date, tz};
6170    ///
6171    /// // This datetime is unambiguous.
6172    /// let zdt1 =
6173    ///     "2024-03-11T02:05[America/New_York]".parse::<ZonedDateTime>()?;
6174    /// assert_eq!(zdt1.offset(), tz::offset(-4));
6175    /// // But the same time on March 10 is ambiguous because there is a gap!
6176    /// let zdt2 = zdt1
6177    ///     .with()
6178    ///     .day(10)
6179    ///     .build()?;
6180    /// assert_eq!(zdt2.datetime(), date(2024, 3, 10).at(3, 5, 0, 0));
6181    /// assert_eq!(zdt2.offset(), tz::offset(-4));
6182    ///
6183    /// # Ok::<(), Box<dyn std::error::Error>>(())
6184    /// ```
6185    ///
6186    /// Alternatively, one can choose to always respect the offset, and thus
6187    /// civil time for the provided time zone will be adjusted to match the
6188    /// instant prescribed by the offset. In this case, no disambiguation is
6189    /// performed:
6190    ///
6191    /// ```
6192    /// use jiff::{ZonedDateTime, civil::date, tz};
6193    ///
6194    /// // This datetime is unambiguous. But `2024-03-10T02:05` is!
6195    /// let zdt1 =
6196    ///     "2024-03-11T02:05[America/New_York]".parse::<ZonedDateTime>()?;
6197    /// assert_eq!(zdt1.offset(), tz::offset(-4));
6198    /// // But the same time on March 10 is ambiguous because there is a gap!
6199    /// let zdt2 = zdt1
6200    ///     .with()
6201    ///     .offset_conflict(tz::OffsetConflict::AlwaysOffset)
6202    ///     .day(10)
6203    ///     .build()?;
6204    /// // Why do we get this result? Because `2024-03-10T02:05-04` is
6205    /// // `2024-03-10T06:05Z`. And in `America/New_York`, the civil time
6206    /// // for that timestamp is `2024-03-10T01:05-05`.
6207    /// assert_eq!(zdt2.datetime(), date(2024, 3, 10).at(1, 5, 0, 0));
6208    /// assert_eq!(zdt2.offset(), tz::offset(-5));
6209    ///
6210    /// # Ok::<(), Box<dyn std::error::Error>>(())
6211    /// ```
6212    #[inline]
6213    pub fn disambiguation(
6214        self,
6215        strategy: Disambiguation,
6216    ) -> ZonedDateTimeWith {
6217        ZonedDateTimeWith { disambiguation: strategy, ..self }
6218    }
6219}
6220
6221#[cfg(test)]
6222mod tests {
6223    use std::io::Cursor;
6224
6225    use alloc::string::ToString;
6226
6227    use crate::{
6228        ToSpan,
6229        civil::{date, datetime},
6230        span::span_eq,
6231        tz,
6232    };
6233
6234    use super::*;
6235
6236    #[test]
6237    fn until_with_largest_unit() {
6238        if crate::tz::db().is_definitively_empty() {
6239            return;
6240        }
6241
6242        let zdt1: ZonedDateTime = date(1995, 12, 7)
6243            .at(3, 24, 30, 3500)
6244            .in_tz("Asia/Kolkata")
6245            .unwrap();
6246        let zdt2: ZonedDateTime =
6247            date(2019, 1, 31).at(15, 30, 0, 0).in_tz("Asia/Kolkata").unwrap();
6248        let span = zdt1.until(&zdt2).unwrap();
6249        span_eq!(
6250            span,
6251            202956
6252                .hours()
6253                .minutes(5)
6254                .seconds(29)
6255                .milliseconds(999)
6256                .microseconds(996)
6257                .nanoseconds(500)
6258        );
6259        let span = zdt1.until((Unit::Year, &zdt2)).unwrap();
6260        span_eq!(
6261            span,
6262            23.years()
6263                .months(1)
6264                .days(24)
6265                .hours(12)
6266                .minutes(5)
6267                .seconds(29)
6268                .milliseconds(999)
6269                .microseconds(996)
6270                .nanoseconds(500)
6271        );
6272
6273        let span = zdt2.until((Unit::Year, &zdt1)).unwrap();
6274        span_eq!(
6275            span,
6276            -23.years()
6277                .months(1)
6278                .days(24)
6279                .hours(12)
6280                .minutes(5)
6281                .seconds(29)
6282                .milliseconds(999)
6283                .microseconds(996)
6284                .nanoseconds(500)
6285        );
6286        let span = zdt1.until((Unit::Nanosecond, &zdt2)).unwrap();
6287        span_eq!(span, 730641929999996500i64.nanoseconds());
6288
6289        let zdt1: ZonedDateTime =
6290            date(2020, 1, 1).at(0, 0, 0, 0).in_tz("America/New_York").unwrap();
6291        let zdt2: ZonedDateTime = date(2020, 4, 24)
6292            .at(21, 0, 0, 0)
6293            .in_tz("America/New_York")
6294            .unwrap();
6295        let span = zdt1.until(&zdt2).unwrap();
6296        span_eq!(span, 2756.hours());
6297        let span = zdt1.until((Unit::Year, &zdt2)).unwrap();
6298        span_eq!(span, 3.months().days(23).hours(21));
6299
6300        let zdt1: ZonedDateTime = date(2000, 10, 29)
6301            .at(0, 0, 0, 0)
6302            .in_tz("America/Vancouver")
6303            .unwrap();
6304        let zdt2: ZonedDateTime = date(2000, 10, 29)
6305            .at(23, 0, 0, 5)
6306            .in_tz("America/Vancouver")
6307            .unwrap();
6308        let span = zdt1.until((Unit::Day, &zdt2)).unwrap();
6309        span_eq!(span, 24.hours().nanoseconds(5));
6310    }
6311
6312    /// Ref: https://github.com/BurntSushi/jiff/issues/685
6313    #[test]
6314    fn until_crosses_dst_day() {
6315        if crate::tz::db().is_definitively_empty() {
6316            return;
6317        }
6318
6319        let start = date(2024, 11, 3)
6320            .at(1, 50, 0, 0)
6321            .in_tz("America/New_York")
6322            .unwrap();
6323        let end: ZonedDateTime =
6324            "2024-11-03T01:00:00-05:00[America/New_York]".parse().unwrap();
6325        for largest in [Unit::Day, Unit::Week, Unit::Month, Unit::Year] {
6326            span_eq!(start.until((largest, &end)).unwrap(), 10.minutes());
6327            span_eq!(end.until((largest, &start)).unwrap(), -10.minutes());
6328        }
6329    }
6330
6331    /// Ref: https://github.com/BurntSushi/jiff/issues/685
6332    #[test]
6333    fn until_crosses_dst_day_different_date() {
6334        if crate::tz::db().is_definitively_empty() {
6335            return;
6336        }
6337
6338        let start: ZonedDateTime =
6339            "2009-11-01T00:00:00-02:30[America/St_Johns]".parse().unwrap();
6340        let end: ZonedDateTime =
6341            "2009-10-31T23:01:00-03:30[America/St_Johns]".parse().unwrap();
6342        for largest in [Unit::Day, Unit::Week, Unit::Month, Unit::Year] {
6343            span_eq!(start.until((largest, &end)).unwrap(), 1.minutes());
6344            span_eq!(end.until((largest, &start)).unwrap(), -1.minutes());
6345        }
6346    }
6347
6348    #[test]
6349    fn until_crosses_dst_multiple_days() {
6350        if crate::tz::db().is_definitively_empty() {
6351            return;
6352        }
6353
6354        let cases = [
6355            (
6356                "2024-11-01T01:50:00-04:00[America/New_York]",
6357                "2024-11-03T01:00:00-05:00[America/New_York]",
6358                2.days().minutes(10),
6359                -1.day().hours(23).minutes(10),
6360            ),
6361            (
6362                "2024-11-03T01:50:00-04:00[America/New_York]",
6363                "2024-11-04T01:00:00-05:00[America/New_York]",
6364                24.hours().minutes(10),
6365                -24.hours().minutes(10),
6366            ),
6367            (
6368                "2024-11-03T01:50:00-05:00[America/New_York]",
6369                "2024-11-04T01:00:00-05:00[America/New_York]",
6370                23.hours().minutes(10),
6371                -23.hours().minutes(10),
6372            ),
6373            (
6374                "2024-03-09T02:30:00-05:00[America/New_York]",
6375                "2024-03-10T03:00:00-04:00[America/New_York]",
6376                23.hours().minutes(30),
6377                -1.day().minutes(30),
6378            ),
6379            // The first day correction lands on a skipped date.
6380            (
6381                "2011-12-28T12:00:00-10:00[Pacific/Apia]",
6382                "2011-12-31T11:00:00+14:00[Pacific/Apia]",
6383                1.day().hours(23),
6384                -2.days().hours(23),
6385            ),
6386        ];
6387        for (start, end, forward, backward) in cases {
6388            let start: ZonedDateTime = start.parse().unwrap();
6389            let end: ZonedDateTime = end.parse().unwrap();
6390            for largest in [Unit::Day, Unit::Week, Unit::Month, Unit::Year] {
6391                let span = start.until((largest, &end)).unwrap();
6392                span_eq!(span, forward, "{start} until {end}, {largest:?}");
6393                assert_eq!(start.checked_add(span).unwrap(), end);
6394
6395                let span = end.until((largest, &start)).unwrap();
6396                span_eq!(span, backward, "{end} until {start}, {largest:?}");
6397                assert_eq!(end.checked_add(span).unwrap(), start);
6398            }
6399        }
6400    }
6401
6402    #[cfg(target_pointer_width = "64")]
6403    #[test]
6404    fn zoned_size() {
6405        #[cfg(debug_assertions)]
6406        {
6407            #[cfg(feature = "alloc")]
6408            {
6409                assert_eq!(40, core::mem::size_of::<ZonedDateTime>());
6410            }
6411            #[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
6412            {
6413                assert_eq!(40, core::mem::size_of::<ZonedDateTime>());
6414            }
6415        }
6416        #[cfg(not(debug_assertions))]
6417        {
6418            #[cfg(feature = "alloc")]
6419            {
6420                assert_eq!(40, core::mem::size_of::<ZonedDateTime>());
6421            }
6422            #[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
6423            {
6424                // This asserts the same value as the alloc value above, but
6425                // it wasn't always this way, which is why it's written out
6426                // separately. Moreover, in theory, I'd be open to regressing
6427                // this value if it led to an improvement in alloc-mode. But
6428                // more likely, it would be nice to decrease this size in
6429                // non-alloc modes.
6430                assert_eq!(40, core::mem::size_of::<ZonedDateTime>());
6431            }
6432        }
6433    }
6434
6435    /// A `serde` deserializer compatibility test.
6436    ///
6437    /// Serde YAML used to be unable to deserialize `jiff` types,
6438    /// as deserializing from bytes is not supported by the deserializer.
6439    ///
6440    /// - <https://github.com/BurntSushi/jiff/issues/138>
6441    /// - <https://github.com/BurntSushi/jiff/discussions/148>
6442    #[test]
6443    fn zoned_deserialize_yaml() {
6444        if crate::tz::db().is_definitively_empty() {
6445            return;
6446        }
6447
6448        let expected = datetime(2024, 10, 31, 16, 33, 53, 123456789)
6449            .in_tz("UTC")
6450            .unwrap();
6451
6452        let deserialized: ZonedDateTime =
6453            serde_yaml::from_str("2024-10-31T16:33:53.123456789+00:00[UTC]")
6454                .unwrap();
6455
6456        assert_eq!(deserialized, expected);
6457
6458        let deserialized: ZonedDateTime = serde_yaml::from_slice(
6459            "2024-10-31T16:33:53.123456789+00:00[UTC]".as_bytes(),
6460        )
6461        .unwrap();
6462
6463        assert_eq!(deserialized, expected);
6464
6465        let cursor = Cursor::new(b"2024-10-31T16:33:53.123456789+00:00[UTC]");
6466        let deserialized: ZonedDateTime =
6467            serde_yaml::from_reader(cursor).unwrap();
6468
6469        assert_eq!(deserialized, expected);
6470    }
6471
6472    /// This is a regression test for a case where changing a zoned datetime
6473    /// to have a time of midnight ends up producing a counter-intuitive
6474    /// result.
6475    ///
6476    /// See: <https://github.com/BurntSushi/jiff/issues/211>
6477    #[test]
6478    fn zoned_with_time_dst_after_gap() {
6479        if crate::tz::db().is_definitively_empty() {
6480            return;
6481        }
6482
6483        let zdt1: ZonedDateTime =
6484            "2024-03-31T12:00[Atlantic/Azores]".parse().unwrap();
6485        assert_eq!(
6486            zdt1.to_string(),
6487            "2024-03-31T12:00:00+00:00[Atlantic/Azores]"
6488        );
6489
6490        let zdt2 = zdt1.with().time(Time::midnight()).build().unwrap();
6491        assert_eq!(
6492            zdt2.to_string(),
6493            "2024-03-31T01:00:00+00:00[Atlantic/Azores]"
6494        );
6495    }
6496
6497    /// Similar to `zoned_with_time_dst_after_gap`, but tests what happens
6498    /// when moving from/to both sides of the gap.
6499    ///
6500    /// See: <https://github.com/BurntSushi/jiff/issues/211>
6501    #[test]
6502    fn zoned_with_time_dst_america_new_york() {
6503        if crate::tz::db().is_definitively_empty() {
6504            return;
6505        }
6506
6507        let zdt1: ZonedDateTime =
6508            "2024-03-10T01:30[America/New_York]".parse().unwrap();
6509        assert_eq!(
6510            zdt1.to_string(),
6511            "2024-03-10T01:30:00-05:00[America/New_York]"
6512        );
6513        let zdt2 = zdt1.with().hour(2).build().unwrap();
6514        assert_eq!(
6515            zdt2.to_string(),
6516            "2024-03-10T03:30:00-04:00[America/New_York]"
6517        );
6518
6519        let zdt1: ZonedDateTime =
6520            "2024-03-10T03:30[America/New_York]".parse().unwrap();
6521        assert_eq!(
6522            zdt1.to_string(),
6523            "2024-03-10T03:30:00-04:00[America/New_York]"
6524        );
6525        let zdt2 = zdt1.with().hour(2).build().unwrap();
6526        assert_eq!(
6527            zdt2.to_string(),
6528            "2024-03-10T03:30:00-04:00[America/New_York]"
6529        );
6530
6531        // I originally thought that this was difference from Temporal. Namely,
6532        // I thought that Temporal ignored the disambiguation setting (and the
6533        // bad offset). But it doesn't. I was holding it wrong.
6534        //
6535        // See: https://github.com/tc39/proposal-temporal/issues/3078
6536        let zdt1: ZonedDateTime =
6537            "2024-03-10T01:30[America/New_York]".parse().unwrap();
6538        assert_eq!(
6539            zdt1.to_string(),
6540            "2024-03-10T01:30:00-05:00[America/New_York]"
6541        );
6542        let zdt2 = zdt1
6543            .with()
6544            .offset(tz::offset(10))
6545            .hour(2)
6546            .disambiguation(Disambiguation::Earlier)
6547            .build()
6548            .unwrap();
6549        assert_eq!(
6550            zdt2.to_string(),
6551            "2024-03-10T01:30:00-05:00[America/New_York]"
6552        );
6553
6554        // This should also respect the disambiguation setting even without
6555        // explicitly specifying an invalid offset. This is because `02:30-05`
6556        // is regarded as invalid since `02:30` isn't a valid civil time on
6557        // this date in this time zone.
6558        let zdt1: ZonedDateTime =
6559            "2024-03-10T01:30[America/New_York]".parse().unwrap();
6560        assert_eq!(
6561            zdt1.to_string(),
6562            "2024-03-10T01:30:00-05:00[America/New_York]"
6563        );
6564        let zdt2 = zdt1
6565            .with()
6566            .hour(2)
6567            .disambiguation(Disambiguation::Earlier)
6568            .build()
6569            .unwrap();
6570        assert_eq!(
6571            zdt2.to_string(),
6572            "2024-03-10T01:30:00-05:00[America/New_York]"
6573        );
6574    }
6575
6576    #[test]
6577    fn zoned_precision_loss() {
6578        if crate::tz::db().is_definitively_empty() {
6579            return;
6580        }
6581
6582        let zdt1: ZonedDateTime =
6583            "2025-01-25T19:32:21.783444592+01:00[Europe/Paris]"
6584                .parse()
6585                .unwrap();
6586        let span = 1.second();
6587        let zdt2 = &zdt1 + span;
6588        assert_eq!(
6589            zdt2.to_string(),
6590            "2025-01-25T19:32:22.783444592+01:00[Europe/Paris]"
6591        );
6592        assert_eq!(zdt1, &zdt2 - span, "should be reversible");
6593    }
6594
6595    // See: https://github.com/BurntSushi/jiff/issues/290
6596    #[test]
6597    fn zoned_roundtrip_regression() {
6598        if crate::tz::db().is_definitively_empty() {
6599            return;
6600        }
6601
6602        let zdt: ZonedDateTime =
6603            "2063-03-31T10:00:00+11:00[Australia/Sydney]".parse().unwrap();
6604        assert_eq!(zdt.offset(), super::Offset::constant(11));
6605        let roundtrip =
6606            zdt.time_zone().to_zoned_datetime(zdt.datetime()).unwrap();
6607        assert_eq!(zdt, roundtrip);
6608    }
6609
6610    // See: https://github.com/BurntSushi/jiff/issues/305
6611    #[test]
6612    fn zoned_round_dst_day_length() {
6613        if crate::tz::db().is_definitively_empty() {
6614            return;
6615        }
6616
6617        let zdt1: ZonedDateTime =
6618            "2025-03-09T12:15[America/New_York]".parse().unwrap();
6619        let zdt2 = zdt1.round(Unit::Day).unwrap();
6620        // Since this day is only 23 hours long, it should round down instead
6621        // of up (as it would on a normal 24 hour day). Interestingly, the bug
6622        // was causing this to not only round up, but to a datetime that wasn't
6623        // the start of a day. Specifically, 2025-03-10T01:00:00-04:00.
6624        assert_eq!(
6625            zdt2.to_string(),
6626            "2025-03-09T00:00:00-05:00[America/New_York]"
6627        );
6628    }
6629
6630    #[test]
6631    fn zoned_round_errors() {
6632        if crate::tz::db().is_definitively_empty() {
6633            return;
6634        }
6635
6636        let zdt: ZonedDateTime =
6637            "2025-03-09T12:15[America/New_York]".parse().unwrap();
6638
6639        insta::assert_snapshot!(
6640            zdt.round(Unit::Year).unwrap_err(),
6641            @"failed rounding datetime: rounding to 'years' is not supported"
6642        );
6643        insta::assert_snapshot!(
6644            zdt.round(Unit::Month).unwrap_err(),
6645            @"failed rounding datetime: rounding to 'months' is not supported"
6646        );
6647        insta::assert_snapshot!(
6648            zdt.round(Unit::Week).unwrap_err(),
6649            @"failed rounding datetime: rounding to 'weeks' is not supported"
6650        );
6651
6652        let options =
6653            ZonedDateTimeRound::new().smallest(Unit::Day).increment(2);
6654        insta::assert_snapshot!(
6655            zdt.round(options).unwrap_err(),
6656            @"failed rounding datetime: increment for rounding to 'days' must be equal to `1`"
6657        );
6658    }
6659
6660    // This tests that if we get a time zone offset with an explicit second
6661    // component, then it must *exactly* match the correct offset for that
6662    // civil time.
6663    //
6664    // See: https://github.com/tc39/proposal-temporal/issues/3099
6665    // See: https://github.com/tc39/proposal-temporal/pull/3107
6666    #[test]
6667    fn time_zone_offset_seconds_exact_match() {
6668        if crate::tz::db().is_definitively_empty() {
6669            return;
6670        }
6671
6672        let zdt: ZonedDateTime =
6673            "1970-06-01T00:00:00-00:45[Africa/Monrovia]".parse().unwrap();
6674        assert_eq!(
6675            zdt.to_string(),
6676            "1970-06-01T00:00:00-00:45[Africa/Monrovia]"
6677        );
6678
6679        let zdt: ZonedDateTime =
6680            "1970-06-01T00:00:00-00:44:30[Africa/Monrovia]".parse().unwrap();
6681        assert_eq!(
6682            zdt.to_string(),
6683            "1970-06-01T00:00:00-00:45[Africa/Monrovia]"
6684        );
6685
6686        insta::assert_snapshot!(
6687            "1970-06-01T00:00:00-00:44:40[Africa/Monrovia]"
6688                .parse::<ZonedDateTime>()
6689                .unwrap_err(),
6690            @"datetime could not resolve to a timestamp since `reject` conflict resolution was chosen, and because datetime has offset `-00:44:40`, but the time zone `Africa/Monrovia` for the given datetime unambiguously has offset `-00:44:30`",
6691        );
6692
6693        insta::assert_snapshot!(
6694            "1970-06-01T00:00:00-00:45:00[Africa/Monrovia]"
6695                .parse::<ZonedDateTime>()
6696                .unwrap_err(),
6697            @"datetime could not resolve to a timestamp since `reject` conflict resolution was chosen, and because datetime has offset `-00:45`, but the time zone `Africa/Monrovia` for the given datetime unambiguously has offset `-00:44:30`",
6698        );
6699    }
6700
6701    // Regression test for #720. In a fold, a rounded offset must select the
6702    // first matching candidate and use its actual offset.
6703    #[test]
6704    fn time_zone_offset_rounding_in_fold() {
6705        if crate::tz::db().is_definitively_empty() {
6706            return;
6707        }
6708
6709        let tests = [
6710            (
6711                "1952-10-15T23:59:59-11:20[Pacific/Niue]",
6712                -543_069_621_000_000_000i128,
6713                -(11 * 60 * 60 + 19 * 60 + 40),
6714            ),
6715            (
6716                "1952-10-15T23:59:59-11:19:40[Pacific/Niue]",
6717                -543_069_621_000_000_000,
6718                -(11 * 60 * 60 + 19 * 60 + 40),
6719            ),
6720            (
6721                "1952-10-15T23:59:59-11:20:00[Pacific/Niue]",
6722                -543_069_601_000_000_000,
6723                -(11 * 60 * 60 + 20 * 60),
6724            ),
6725            // Each rounded offset matches only one side of this fold, and
6726            // both candidates have non-zero offset seconds.
6727            (
6728                "1919-02-28T23:59:00-00:43[Africa/Monrovia]",
6729                -1_604_359_072_000_000_000,
6730                -(43 * 60 + 8),
6731            ),
6732            (
6733                "1919-02-28T23:59:00-00:45[Africa/Monrovia]",
6734                -1_604_358_990_000_000_000,
6735                -(44 * 60 + 30),
6736            ),
6737        ];
6738        for conflict in [OffsetConflict::Reject, OffsetConflict::PreferOffset]
6739        {
6740            for disambiguation in [
6741                Disambiguation::Compatible,
6742                Disambiguation::Earlier,
6743                Disambiguation::Later,
6744                Disambiguation::Reject,
6745            ] {
6746                let parser = temporal::DateTimeParser::new()
6747                    .offset_conflict(conflict)
6748                    .disambiguation(disambiguation);
6749                for (input, expected, offset) in tests {
6750                    let zdt = parser.parse_zoned_datetime(input).unwrap();
6751                    assert_eq!(
6752                        zdt.timestamp().as_nanosecond(),
6753                        expected,
6754                        "{input}"
6755                    );
6756                    assert_eq!(zdt.offset().seconds(), offset, "{input}");
6757                }
6758            }
6759        }
6760
6761        let input = "1952-10-15T23:59:59-11:19:50[Pacific/Niue]";
6762        assert!(input.parse::<ZonedDateTime>().is_err());
6763        let zdt = temporal::DateTimeParser::new()
6764            .offset_conflict(OffsetConflict::PreferOffset)
6765            .disambiguation(Disambiguation::Later)
6766            .parse_zoned_datetime(input)
6767            .unwrap();
6768        assert_eq!(zdt.timestamp().as_nanosecond(), -543_069_601_000_000_000);
6769    }
6770
6771    // These are some interesting tests because the time zones have transitions
6772    // that are very close to one another (within 14 days!). I picked these up
6773    // from a bug report to Temporal. Their reference implementation uses
6774    // different logic to examine time zone transitions than Jiff. In contrast,
6775    // Jiff uses the IANA time zone database directly. So it was unaffected.
6776    //
6777    // [1]: https://github.com/tc39/proposal-temporal/issues/3110
6778    #[test]
6779    fn weird_time_zone_transitions() {
6780        if crate::tz::db().is_definitively_empty() {
6781            return;
6782        }
6783
6784        let zdt: ZonedDateTime =
6785            "2000-10-08T01:00:00-01:00[America/Noronha]".parse().unwrap();
6786        let sod = zdt.start_of_day().unwrap();
6787        assert_eq!(
6788            sod.to_string(),
6789            "2000-10-08T01:00:00-01:00[America/Noronha]"
6790        );
6791
6792        let zdt: ZonedDateTime =
6793            "2000-10-08T03:00:00-03:00[America/Boa_Vista]".parse().unwrap();
6794        let sod = zdt.start_of_day().unwrap();
6795        assert_eq!(
6796            sod.to_string(),
6797            "2000-10-08T01:00:00-03:00[America/Boa_Vista]",
6798        );
6799    }
6800
6801    // An interesting test from the Temporal issue tracker, where one doesn't
6802    // get a rejection during a fold when the offset is included in the
6803    // datetime string.
6804    //
6805    // See: https://github.com/tc39/proposal-temporal/issues/2892#issuecomment-3863293014
6806    #[test]
6807    fn no_reject_in_fold_when_using_with() {
6808        if crate::tz::db().is_definitively_empty() {
6809            return;
6810        }
6811
6812        let zdt1: ZonedDateTime =
6813            "2016-09-30T02:01+02:00[Europe/Amsterdam]".parse().unwrap();
6814        let zdt2 = zdt1
6815            .with()
6816            .month(10)
6817            .disambiguation(Disambiguation::Reject)
6818            .offset_conflict(OffsetConflict::Reject)
6819            .build()
6820            .unwrap();
6821        assert_eq!(
6822            zdt2.to_string(),
6823            "2016-10-30T02:01:00+02:00[Europe/Amsterdam]"
6824        );
6825
6826        let zdt3: ZonedDateTime =
6827            "2016-10-30T02:01+02:00[Europe/Amsterdam]".parse().unwrap();
6828        assert_eq!(
6829            zdt3.to_string(),
6830            "2016-10-30T02:01:00+02:00[Europe/Amsterdam]"
6831        );
6832
6833        let zdt4: ZonedDateTime =
6834            "2016-10-30T02:01+01:00[Europe/Amsterdam]".parse().unwrap();
6835        assert_eq!(
6836            zdt4.to_string(),
6837            "2016-10-30T02:01:00+01:00[Europe/Amsterdam]"
6838        );
6839    }
6840
6841    /// Adding only calendar units resolves the resulting civil datetime with
6842    /// "compatible" disambiguation. This checks the unambiguous, gap and fold
6843    /// cases, with and without a time component in the span.
6844    #[test]
6845    fn zoned_add_calendar_units_dst() {
6846        if crate::tz::db().is_definitively_empty() {
6847            return;
6848        }
6849
6850        let zdt: ZonedDateTime =
6851            "2024-01-31T02:30[America/New_York]".parse().unwrap();
6852        assert_eq!(
6853            zdt.checked_add(1.month()).unwrap().to_string(),
6854            "2024-02-29T02:30:00-05:00[America/New_York]"
6855        );
6856
6857        // Lands in a gap, so it's moved forward by the length of the gap.
6858        let zdt: ZonedDateTime =
6859            "2024-03-09T02:30[America/New_York]".parse().unwrap();
6860        assert_eq!(
6861            zdt.checked_add(1.day()).unwrap().to_string(),
6862            "2024-03-10T03:30:00-04:00[America/New_York]"
6863        );
6864        assert_eq!(
6865            zdt.checked_add(1.day().minutes(1)).unwrap().to_string(),
6866            "2024-03-10T03:31:00-04:00[America/New_York]"
6867        );
6868
6869        // Lands in a fold, so the earlier offset is picked.
6870        let zdt: ZonedDateTime =
6871            "2024-11-02T01:30[America/New_York]".parse().unwrap();
6872        assert_eq!(
6873            zdt.checked_add(1.day()).unwrap().to_string(),
6874            "2024-11-03T01:30:00-04:00[America/New_York]"
6875        );
6876        assert_eq!(
6877            zdt.checked_add(1.day().hours(1)).unwrap().to_string(),
6878            "2024-11-03T01:30:00-05:00[America/New_York]"
6879        );
6880    }
6881
6882    // See: https://github.com/BurntSushi/jiff/issues/678
6883    #[test]
6884    fn zoned_pre_epoch_fractional_transition() {
6885        if crate::tz::db().is_definitively_empty() {
6886            return;
6887        }
6888
6889        let zone = crate::tz::db().get("Europe/Istanbul").unwrap();
6890        for (input, expected) in [
6891            (
6892                "1910-09-30T22:03:03Z",
6893                "1910-09-30T23:59:59+01:57[Europe/Istanbul]",
6894            ),
6895            (
6896                "1910-09-30T22:03:03.999999999Z",
6897                "1910-09-30T23:59:59.999999999+01:57[Europe/Istanbul]",
6898            ),
6899            (
6900                "1910-09-30T22:03:04Z",
6901                "1910-10-01T00:03:04+02:00[Europe/Istanbul]",
6902            ),
6903        ] {
6904            let instant: Timestamp = input.parse().unwrap();
6905            assert_eq!(
6906                instant.to_zoned_datetime(zone.clone()).to_string(),
6907                expected
6908            );
6909        }
6910    }
6911}