icu_time 2.2.0

Processing of dates, times, and time zones with a focus on i18n and interop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

//! Types for resolving and manipulating time zones.
//!
//! # Fields
//!
//! In ICU4X, a [`TimeZoneInfo`] consists of up to four different fields:
//!
//! 1. The time zone ID
//! 2. The offset from UTC
//! 3. A timestamp, as time zone names can change over time
//!
//! ## Time Zone
//!
//! The time zone ID corresponds to a time zone from the time zone database. The time zone ID
//! usually corresponds to the largest city in the time zone.
//!
//! There are two mostly-interchangeable standards for time zone IDs:
//!
//! 1. IANA time zone IDs, like `"America/Chicago"`
//! 2. BCP-47 time zone IDs, like `"uschi"`
//!
//! ICU4X uses BCP-47 time zone IDs for all of its APIs. To get a BCP-47 time zone from an
//! IANA time zone, use [`IanaParser`].
//!
//! ## UTC Offset
//!
//! The UTC offset precisely states the time difference between the time zone in question and
//! Coordinated Universal Time (UTC).
//!
//! In localized strings, it is often rendered as "UTC-6", meaning 6 hours less than UTC (some locales
//! use the term "GMT" instead of "UTC").
//!
//! ## Timestamp
//!
//! Some time zones change names over time, such as when changing "metazone". For example, Portugal changed from
//! "Western European Time" to "Central European Time" and back in the 1990s, without changing time zone ID
//! (`Europe/Lisbon`, `ptlis`). Therefore, a timestamp is needed to resolve such generic time zone names.
//!
//! It is not required to set the timestamp on [`TimeZoneInfo`]. If it is not set, some string
//! formats may be unsupported.
//!
//! # Obtaining time zone information
//!
//! This crate does not ship time zone offset information. Other Rust crates such as [`chrono_tz`](https://docs.rs/chrono-tz) or [`jiff`](https://docs.rs/jiff)
//! are available for this purpose. See our [`example`](https://github.com/unicode-org/icu4x/blob/main/components/icu/examples/chrono_jiff.rs).

pub mod iana;
mod offset;
pub mod windows;
mod zone_name_timestamp;

use icu_calendar::types::RataDie;
use icu_calendar::AsCalendar;
#[cfg(feature = "compiled_data")]
use icu_locale_core::subtags::Region;
#[doc(inline)]
pub use offset::InvalidOffsetError;
pub use offset::UtcOffset;
pub use offset::VariantOffsets;
#[allow(deprecated)]
pub use offset::VariantOffsetsCalculator;
#[allow(deprecated)]
pub use offset::VariantOffsetsCalculatorBorrowed;

#[doc(no_inline)]
pub use iana::{IanaParser, IanaParserBorrowed};
#[doc(no_inline)]
pub use windows::{WindowsParser, WindowsParserBorrowed};

pub use zone_name_timestamp::ZoneNameTimestamp;

use crate::scaffold::IntoOption;
use crate::DateTime;
use crate::Time;
use core::fmt;
use core::ops::Deref;
use icu_calendar::Iso;
use icu_locale_core::subtags::{subtag, Subtag};
use icu_provider::prelude::yoke;
use zerovec::ule::{AsULE, ULE};

/// Time zone data model choices.
pub mod models {
    use super::*;
    mod private {
        pub trait Sealed {}
    }

    /// Trait encoding a particular data model for time zones.
    ///
    /// <div class="stab unstable">
    /// 🚫 This trait is sealed; it cannot be implemented by user code. If an API requests an item that implements this
    /// trait, please consider using a type from the implementors listed below.
    /// </div>
    pub trait TimeZoneModel: private::Sealed {
        /// The zone variant, if required for this time zone model.
        type TimeZoneVariant: IntoOption<TimeZoneVariant> + fmt::Debug + Copy;
        /// The local time, if required for this time zone model.
        type ZoneNameTimestamp: IntoOption<ZoneNameTimestamp> + fmt::Debug + Copy;
    }

    /// A time zone containing a time zone ID and optional offset.
    #[derive(Debug, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct Base;

    impl private::Sealed for Base {}
    impl TimeZoneModel for Base {
        type TimeZoneVariant = ();
        type ZoneNameTimestamp = ();
    }

    /// A time zone containing a time zone ID, optional offset, and local time.
    #[derive(Debug, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct AtTime;

    impl private::Sealed for AtTime {}
    impl TimeZoneModel for AtTime {
        type TimeZoneVariant = ();
        type ZoneNameTimestamp = ZoneNameTimestamp;
    }

    /// A time zone containing a time zone ID, optional offset, local time, and zone variant.
    #[derive(Debug, PartialEq, Eq)]
    #[non_exhaustive]
    #[deprecated(
        since = "2.1.0",
        note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore. use `TimeZoneInfo<AtTime>`"
    )]
    pub struct Full;

    #[allow(deprecated)]
    impl private::Sealed for Full {}
    #[allow(deprecated)]
    impl TimeZoneModel for Full {
        type TimeZoneVariant = TimeZoneVariant;
        type ZoneNameTimestamp = ZoneNameTimestamp;
    }
}

/// A CLDR time zone identity.
///
/// **The primary definition of this type is in the [`icu_time`](https://docs.rs/icu_time) crate. Other ICU4X crates re-export it for convenience.**
///
/// This can be created directly from BCP-47 strings, or it can be parsed from IANA IDs.
///
/// CLDR uses difference equivalence classes than IANA. For example, `Europe/Oslo` is
/// an alias to `Europe/Berlin` in IANA (because they agree since 1970), but these are
/// different identities in CLDR, as we want to be able to say "Norway Time" and
/// "Germany Time". On the other hand `Europe/Belfast` and `Europe/London` are the same
/// CLDR identity ("UK Time").
///
/// See the docs on [`zone`](crate::zone) for more information.
///
/// ```
/// use icu::locale::subtags::subtag;
/// use icu::time::zone::{IanaParser, TimeZone};
///
/// let parser = IanaParser::new();
/// assert_eq!(parser.parse("Europe/Oslo"), TimeZone(subtag!("noosl")));
/// assert_eq!(parser.parse("Europe/Berlin"), TimeZone(subtag!("deber")));
/// assert_eq!(parser.parse("Europe/Belfast"), TimeZone(subtag!("gblon")));
/// assert_eq!(parser.parse("Europe/London"), TimeZone(subtag!("gblon")));
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd, yoke::Yokeable, ULE, Hash)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_time::provider))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[allow(clippy::exhaustive_structs)] // This is a stable newtype
pub struct TimeZone(pub Subtag);

impl TimeZone {
    /// The synthetic `Etc/Unknown` time zone.
    ///
    /// This is the result of parsing unknown zones. It's important that such parsing does not
    /// fail, as new zones are added all the time, and ICU4X might not be up to date.
    pub const UNKNOWN: Self = Self(subtag!("unk"));

    /// Whether this [`TimeZone`] equals [`TimeZone::UNKNOWN`].
    pub const fn is_unknown(self) -> bool {
        matches!(self, Self::UNKNOWN)
    }

    /// Construct a [`TimeZone`] from an IANA time zone ID.
    ///
    /// See [`IanaParser`].
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    #[cfg(feature = "compiled_data")]
    pub fn from_iana_id(iana_id: &str) -> Self {
        IanaParser::new().parse(iana_id)
    }

    /// Construct a [`TimeZone`] from a Windows time zone ID and region.
    ///
    /// See [`WindowsParser`].
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    #[cfg(feature = "compiled_data")]
    pub fn from_windows_id(windows_id: &str, region: Option<Region>) -> Self {
        WindowsParser::new()
            .parse(windows_id, region)
            .unwrap_or(Self::UNKNOWN)
    }

    /// Construct a [`TimeZone`] from the platform-specific ID.
    ///
    /// On Windows systems, this resolves to [`TimeZone::from_windows_id`], on
    /// all other systems to [`TimeZone::from_iana_id`].
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    #[cfg(feature = "compiled_data")]
    pub fn from_system_id(id: &str, _region: Option<Region>) -> Self {
        #[cfg(target_os = "windows")]
        return Self::from_windows_id(id, _region);
        #[cfg(not(target_os = "windows"))]
        return Self::from_iana_id(id);
    }
}

impl Deref for TimeZone {
    type Target = Subtag;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsULE for TimeZone {
    type ULE = Self;

    #[inline]
    fn to_unaligned(self) -> Self::ULE {
        self
    }

    #[inline]
    fn from_unaligned(unaligned: Self::ULE) -> Self {
        unaligned
    }
}

#[cfg(feature = "alloc")]
impl<'a> zerovec::maps::ZeroMapKV<'a> for TimeZone {
    type Container = zerovec::ZeroVec<'a, TimeZone>;
    type Slice = zerovec::ZeroSlice<TimeZone>;
    type GetType = TimeZone;
    type OwnedType = TimeZone;
}

/// A utility type that can hold time zone information.
///
/// **The primary definition of this type is in the [`icu_time`](https://docs.rs/icu_time) crate. Other ICU4X crates re-export it for convenience.**
///
/// See the docs on [`zone`](self) for more information.
///
/// # Examples
///
/// ```
/// use icu::calendar::Date;
/// use icu::locale::subtags::subtag;
/// use icu::time::zone::TimeZoneVariant;
/// use icu::time::zone::UtcOffset;
/// use icu::time::zone::ZoneNameTimestamp;
/// use icu::time::DateTime;
/// use icu::time::Time;
/// use icu::time::TimeZone;
///
/// // Parse the IANA ID
/// let id = TimeZone::from_iana_id("America/Chicago");
///
/// // Alternatively, use the BCP47 ID directly
/// let id = TimeZone(subtag!("uschi"));
///
/// // Create a TimeZoneInfo<Base> by associating the ID with an offset
/// let time_zone = id.with_offset(UtcOffset::try_from_seconds(-6 * 3600).ok());
///
/// // Extend to a `TimeZoneInfo<AtTime>` by adding a timestamp ...
/// let time_zone_at_time = time_zone.with_zone_name_timestamp(
///     ZoneNameTimestamp::from_epoch_seconds(1701493200),
/// );
///
/// // ... or by adding a local time
/// let time_zone_at_time = time_zone.at_date_time(DateTime {
///     date: Date::try_new_coptic(1996, 12, 2).unwrap(),
///     time: Time::start_of_day(),
/// });
/// ```
#[derive(Debug, PartialEq, Eq)]
#[allow(clippy::exhaustive_structs)] // these four fields fully cover the needs of UTS 35
pub struct TimeZoneInfo<Model: models::TimeZoneModel> {
    id: TimeZone,
    offset: Option<UtcOffset>,
    zone_name_timestamp: Model::ZoneNameTimestamp,
    variant: Model::TimeZoneVariant,
}

impl<Model: models::TimeZoneModel> Clone for TimeZoneInfo<Model> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Model: models::TimeZoneModel> Copy for TimeZoneInfo<Model> {}

impl<Model: models::TimeZoneModel> TimeZoneInfo<Model> {
    /// The BCP47 time-zone identifier.
    pub fn id(self) -> TimeZone {
        self.id
    }

    /// The UTC offset, if known.
    ///
    /// This field is not enforced to be consistent with the time zone id.
    pub fn offset(self) -> Option<UtcOffset> {
        self.offset
    }
}

impl<Model> TimeZoneInfo<Model>
where
    Model: models::TimeZoneModel<ZoneNameTimestamp = ZoneNameTimestamp>,
{
    /// The time at which to interpret the time zone.
    pub fn zone_name_timestamp(self) -> ZoneNameTimestamp {
        self.zone_name_timestamp
    }
}

impl<Model> TimeZoneInfo<Model>
where
    Model: models::TimeZoneModel<TimeZoneVariant = TimeZoneVariant>,
{
    /// The time variant e.g. daylight or standard, if known.
    ///
    /// This field is not enforced to be consistent with the time zone id and offset.
    pub fn variant(self) -> TimeZoneVariant {
        self.variant
    }
}

impl TimeZone {
    /// Associates this [`TimeZone`] with a UTC offset, returning a [`TimeZoneInfo`].
    pub const fn with_offset(self, mut offset: Option<UtcOffset>) -> TimeZoneInfo<models::Base> {
        let mut id = self;

        #[allow(clippy::identity_op, clippy::neg_multiply)]
        let correct_offset = match self.0.as_str().as_bytes() {
            b"utc" | b"gmt" => Some(UtcOffset::zero()),
            b"utce01" => Some(UtcOffset::from_seconds_unchecked(1 * 60 * 60)),
            b"utce02" => Some(UtcOffset::from_seconds_unchecked(2 * 60 * 60)),
            b"utce03" => Some(UtcOffset::from_seconds_unchecked(3 * 60 * 60)),
            b"utce04" => Some(UtcOffset::from_seconds_unchecked(4 * 60 * 60)),
            b"utce05" => Some(UtcOffset::from_seconds_unchecked(5 * 60 * 60)),
            b"utce06" => Some(UtcOffset::from_seconds_unchecked(6 * 60 * 60)),
            b"utce07" => Some(UtcOffset::from_seconds_unchecked(7 * 60 * 60)),
            b"utce08" => Some(UtcOffset::from_seconds_unchecked(8 * 60 * 60)),
            b"utce09" => Some(UtcOffset::from_seconds_unchecked(9 * 60 * 60)),
            b"utce10" => Some(UtcOffset::from_seconds_unchecked(10 * 60 * 60)),
            b"utce11" => Some(UtcOffset::from_seconds_unchecked(11 * 60 * 60)),
            b"utce12" => Some(UtcOffset::from_seconds_unchecked(12 * 60 * 60)),
            b"utce13" => Some(UtcOffset::from_seconds_unchecked(13 * 60 * 60)),
            b"utce14" => Some(UtcOffset::from_seconds_unchecked(14 * 60 * 60)),
            b"utcw01" => Some(UtcOffset::from_seconds_unchecked(-1 * 60 * 60)),
            b"utcw02" => Some(UtcOffset::from_seconds_unchecked(-2 * 60 * 60)),
            b"utcw03" => Some(UtcOffset::from_seconds_unchecked(-3 * 60 * 60)),
            b"utcw04" => Some(UtcOffset::from_seconds_unchecked(-4 * 60 * 60)),
            b"utcw05" => Some(UtcOffset::from_seconds_unchecked(-5 * 60 * 60)),
            b"utcw06" => Some(UtcOffset::from_seconds_unchecked(-6 * 60 * 60)),
            b"utcw07" => Some(UtcOffset::from_seconds_unchecked(-7 * 60 * 60)),
            b"utcw08" => Some(UtcOffset::from_seconds_unchecked(-8 * 60 * 60)),
            b"utcw09" => Some(UtcOffset::from_seconds_unchecked(-9 * 60 * 60)),
            b"utcw10" => Some(UtcOffset::from_seconds_unchecked(-10 * 60 * 60)),
            b"utcw11" => Some(UtcOffset::from_seconds_unchecked(-11 * 60 * 60)),
            b"utcw12" => Some(UtcOffset::from_seconds_unchecked(-12 * 60 * 60)),
            _ => None,
        };

        match (correct_offset, offset) {
            // The Etc/* zones have fixed defined offsets. By setting them here,
            // they won't format as UTC+?.
            (Some(c), None) => {
                offset = Some(c);

                // The Etc/GMT+X zones do not have display names, so they format
                // exactly like UNKNOWN with the same offset. For the sake of
                // equality, set the ID to UNKNOWN as well.
                if id.0.as_str().len() > 3 {
                    id = Self::UNKNOWN;
                }
            }
            // Garbage offset for a fixed zone, now we know nothing
            (Some(c), Some(o)) if c.to_seconds() != o.to_seconds() => {
                offset = None;
                id = Self::UNKNOWN;
            }
            _ => {}
        }

        TimeZoneInfo {
            id,
            offset,
            zone_name_timestamp: (),
            variant: (),
        }
    }

    /// Converts this [`TimeZone`] into a [`TimeZoneInfo`] without an offset.
    pub const fn without_offset(self) -> TimeZoneInfo<models::Base> {
        self.with_offset(None)
    }
}

impl TimeZoneInfo<models::Base> {
    /// Creates a time zone info with no information.
    pub const fn unknown() -> Self {
        Self {
            id: TimeZone::UNKNOWN,
            offset: None,
            zone_name_timestamp: (),
            variant: (),
        }
    }

    /// Creates a new [`TimeZoneInfo`] for the UTC time zone.
    pub const fn utc() -> Self {
        TimeZoneInfo {
            id: TimeZone(subtag!("utc")),
            offset: Some(UtcOffset::zero()),
            zone_name_timestamp: (),
            variant: (),
        }
    }

    /// Sets the [`ZoneNameTimestamp`] field.
    pub fn with_zone_name_timestamp(
        self,
        zone_name_timestamp: ZoneNameTimestamp,
    ) -> TimeZoneInfo<models::AtTime> {
        TimeZoneInfo {
            offset: self.offset,
            id: self.id,
            zone_name_timestamp,
            variant: (),
        }
    }

    /// Sets the [`ZoneNameTimestamp`] to the given datetime.
    ///
    /// If the offset is known, the datetime is interpreted as a local time,
    /// otherwise as UTC. This produces correct results for the vast majority
    /// of cases, however close to metazone changes (Eastern Time -> Central Time)
    /// it might be incorrect if the offset is not known.
    ///
    /// Also see [`Self::with_zone_name_timestamp`].
    pub fn at_date_time<C: AsCalendar>(
        self,
        date_time: DateTime<C>,
    ) -> TimeZoneInfo<models::AtTime> {
        self.at_rd_time(date_time.date.to_rata_die(), date_time.time)
    }

    /// Use [`Self::at_date_time`].
    #[deprecated(since = "2.2.0", note = "use `Self::at_date_time`")]
    pub fn at_date_time_iso(self, date_time: DateTime<Iso>) -> TimeZoneInfo<models::AtTime> {
        self.at_date_time(date_time)
    }

    pub(crate) fn at_rd_time(self, rd: RataDie, time: Time) -> TimeZoneInfo<models::AtTime> {
        self.with_zone_name_timestamp(ZoneNameTimestamp::from_rd_time_zone(
            rd,
            time,
            // If we don't have an offset, interpret as UTC. This is incorrect during O(a couple of
            // hours) since the UNIX epoch (a handful of transitions times the few hours this is too
            // early/late).
            self.offset.unwrap_or(UtcOffset::zero()),
        ))
    }
}

impl TimeZoneInfo<models::AtTime> {
    /// Sets a [`TimeZoneVariant`] on this time zone.
    #[deprecated(
        since = "2.1.0",
        note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore"
    )]
    #[allow(deprecated)]
    pub const fn with_variant(self, variant: TimeZoneVariant) -> TimeZoneInfo<models::Full> {
        TimeZoneInfo {
            offset: self.offset,
            id: self.id,
            zone_name_timestamp: self.zone_name_timestamp,
            variant,
        }
    }

    /// Sets the zone variant by calculating it using a [`VariantOffsetsCalculator`].
    ///
    /// If `offset()` is `None`, or if it doesn't match either of the
    /// timezone's standard or daylight offset around [`zone_name_timestamp`](Self::zone_name_timestamp),
    /// the variant will be set to [`TimeZoneVariant::Standard`] and the time zone
    /// to [`TimeZone::UNKNOWN`].
    ///
    /// # Example
    /// ```
    /// use icu::calendar::Date;
    /// use icu::time::zone::TimeZoneVariant;
    /// use icu::time::zone::UtcOffset;
    /// use icu::time::zone::VariantOffsetsCalculator;
    /// use icu::time::zone::ZoneNameTimestamp;
    /// use icu::time::DateTime;
    /// use icu::time::Time;
    /// use icu::time::TimeZone;
    ///
    /// // Chicago at UTC-6
    /// let info = TimeZone::from_iana_id("America/Chicago")
    ///     .with_offset(UtcOffset::try_from_seconds(-6 * 3600).ok())
    ///     .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
    ///         1701493200,
    ///     ))
    ///     .infer_variant(VariantOffsetsCalculator::new());
    ///
    /// assert_eq!(info.variant(), TimeZoneVariant::Standard);
    ///
    /// // Chicago at at UTC-5
    /// let info = TimeZone::from_iana_id("America/Chicago")
    ///     .with_offset(UtcOffset::try_from_seconds(-5 * 3600).ok())
    ///     .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
    ///         1685678400,
    ///     ))
    ///     .infer_variant(VariantOffsetsCalculator::new());
    ///
    /// assert_eq!(info.variant(), TimeZoneVariant::Daylight);
    ///
    /// // Chicago at UTC-7
    /// let info = TimeZone::from_iana_id("America/Chicago")
    ///     .with_offset(UtcOffset::try_from_seconds(-7 * 3600).ok())
    ///     .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
    ///         1701493200,
    ///     ))
    ///     .infer_variant(VariantOffsetsCalculator::new());
    ///
    /// // Whatever it is, it's not Chicago
    /// assert_eq!(info.id(), TimeZone::UNKNOWN);
    /// assert_eq!(info.variant(), TimeZoneVariant::Standard);
    /// ```
    #[deprecated(
        since = "2.1.0",
        note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore"
    )]
    #[allow(deprecated)]
    pub fn infer_variant(
        self,
        calculator: VariantOffsetsCalculatorBorrowed,
    ) -> TimeZoneInfo<models::Full> {
        let Some(offset) = self.offset else {
            return TimeZone::UNKNOWN
                .with_offset(self.offset)
                .with_zone_name_timestamp(self.zone_name_timestamp)
                .with_variant(TimeZoneVariant::Standard);
        };
        let Some(variant) = calculator
            .compute_offsets_from_time_zone_and_name_timestamp(self.id, self.zone_name_timestamp)
            .and_then(|os| {
                if os.standard == offset {
                    Some(TimeZoneVariant::Standard)
                } else if os.daylight == Some(offset) {
                    Some(TimeZoneVariant::Daylight)
                } else {
                    None
                }
            })
        else {
            return TimeZone::UNKNOWN
                .with_offset(self.offset)
                .with_zone_name_timestamp(self.zone_name_timestamp)
                .with_variant(TimeZoneVariant::Standard);
        };
        self.with_variant(variant)
    }
}

#[deprecated(
    since = "2.1.0",
    note = "TimeZoneVariants don't need to be constructed in user code"
)]
pub use crate::provider::TimeZoneVariant;

impl TimeZoneVariant {
    /// Creates a zone variant from a TZDB `isdst` flag, if it is known that the TZDB was built with
    /// `DATAFORM=rearguard`.
    ///
    /// If it is known that the database was *not* built with `rearguard`, a caller can try to adjust
    /// for the differences. This is a moving target, for example the known differences for 2025a are:
    ///
    /// * `Europe/Dublin` since 1968-10-27
    /// * `Africa/Windhoek` between 1994-03-20 and 2017-10-24
    /// * `Africa/Casablanca` and `Africa/El_Aaiun` since 2018-10-28
    ///
    /// If the TZDB build mode is unknown or variable, use [`TimeZoneInfo::infer_variant`].
    #[deprecated(
        since = "2.1.0",
        note = "TimeZoneVariants don't need to be constructed in user code"
    )]
    pub const fn from_rearguard_isdst(isdst: bool) -> Self {
        if isdst {
            TimeZoneVariant::Daylight
        } else {
            TimeZoneVariant::Standard
        }
    }
}

#[test]
fn test_zone_info_equality() {
    // offset inferred
    assert_eq!(
        TimeZone::from_iana_id("Etc/GMT-8").with_offset(None),
        TimeZone::UNKNOWN.with_offset(Some(UtcOffset::from_seconds_unchecked(8 * 60 * 60)))
    );
    assert_eq!(
        TimeZone::from_iana_id("Etc/UTC").with_offset(None),
        TimeZoneInfo::utc()
    );
    assert_eq!(
        TimeZone::from_iana_id("Etc/GMT").with_offset(None),
        IanaParser::new()
            .parse("Etc/GMT")
            .with_offset(Some(UtcOffset::zero()))
    );

    // bogus offset removed
    assert_eq!(
        IanaParser::new()
            .parse("Etc/GMT-8")
            .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
        TimeZoneInfo::unknown()
    );
    assert_eq!(
        IanaParser::new()
            .parse("Etc/UTC")
            .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
        TimeZoneInfo::unknown(),
    );
    assert_eq!(
        IanaParser::new()
            .parse("Etc/GMT")
            .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
        TimeZoneInfo::unknown()
    );
}