jiff/
zoned.rs

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