Debian Codegraph @

debian/rust-vendor/icu_time/src/zone/mod.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 //! Types for resolving and manipulating time zones.
6 //!
7 //! # Fields
8 //!
9 //! In ICU4X, a [`TimeZoneInfo`] consists of up to four different fields:
10 //!
11 //! 1. The time zone ID
12 //! 2. The offset from UTC
13 //! 3. A timestamp, as time zone names can change over time
14 //!
15 //! ## Time Zone
16 //!
17 //! The time zone ID corresponds to a time zone from the time zone database. The time zone ID
18 //! usually corresponds to the largest city in the time zone.
19 //!
20 //! There are two mostly-interchangeable standards for time zone IDs:
21 //!
22 //! 1. IANA time zone IDs, like `"America/Chicago"`
23 //! 2. BCP-47 time zone IDs, like `"uschi"`
24 //!
25 //! ICU4X uses BCP-47 time zone IDs for all of its APIs. To get a BCP-47 time zone from an
26 //! IANA time zone, use [`IanaParser`].
27 //!
28 //! ## UTC Offset
29 //!
30 //! The UTC offset precisely states the time difference between the time zone in question and
31 //! Coordinated Universal Time (UTC).
32 //!
33 //! In localized strings, it is often rendered as "UTC-6", meaning 6 hours less than UTC (some locales
34 //! use the term "GMT" instead of "UTC").
35 //!
36 //! ## Timestamp
37 //!
38 //! Some time zones change names over time, such as when changing "metazone". For example, Portugal changed from
39 //! "Western European Time" to "Central European Time" and back in the 1990s, without changing time zone ID
40 //! (`Europe/Lisbon`, `ptlis`). Therefore, a timestamp is needed to resolve such generic time zone names.
41 //!
42 //! It is not required to set the timestamp on [`TimeZoneInfo`]. If it is not set, some string
43 //! formats may be unsupported.
44 //!
45 //! # Obtaining time zone information
46 //!
47 //! 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)
48 //! are available for this purpose. See our [`example`](https://github.com/unicode-org/icu4x/blob/main/components/icu/examples/chrono_jiff.rs).
49
50 pub mod iana;
51 mod offset;
52 pub mod windows;
53 mod zone_name_timestamp;
54
55 use icu_calendar::AsCalendar;
56 use icu_calendar::types::RataDie;
57 #[cfg(feature = "compiled_data")]
58 use icu_locale_core::subtags::Region;
59 #[doc(inline)]
60 pub use offset::InvalidOffsetError;
61 pub use offset::UtcOffset;
62 pub use offset::VariantOffsets;
63 #[allow(deprecated)]
64 pub use offset::VariantOffsetsCalculator;
65 #[allow(deprecated)]
66 pub use offset::VariantOffsetsCalculatorBorrowed;
67
68 #[doc(no_inline)]
69 pub use iana::{IanaParser, IanaParserBorrowed};
70 #[doc(no_inline)]
71 pub use windows::{WindowsParser, WindowsParserBorrowed};
72
73 pub use zone_name_timestamp::ZoneNameTimestamp;
74
75 use crate::DateTime;
76 use crate::Time;
77 use crate::scaffold::IntoOption;
78 use core::fmt;
79 use core::ops::Deref;
80 use icu_calendar::Iso;
81 use icu_locale_core::subtags::{Subtag, subtag};
82 use icu_provider::prelude::yoke;
83 use zerovec::ule::{AsULE, ULE};
84
85 /// Time zone data model choices.
86 pub mod models {
87 use super::*;
88 mod private {
89 pub trait Sealed {}
90 }
91
92 /// Trait encoding a particular data model for time zones.
93 ///
94 /// <div class="stab unstable">
95 /// 🚫 This trait is sealed; it cannot be implemented by user code. If an API requests an item that implements this
96 /// trait, please consider using a type from the implementors listed below.
97 /// </div>
98 pub trait TimeZoneModel: private::Sealed {
99 /// The zone variant, if required for this time zone model.
100 type TimeZoneVariant: IntoOption<TimeZoneVariant> + fmt::Debug + Copy;
101 /// The local time, if required for this time zone model.
102 type ZoneNameTimestamp: IntoOption<ZoneNameTimestamp> + fmt::Debug + Copy;
103 }
104
105 /// A time zone containing a time zone ID and optional offset.
106 #[derive(Debug, PartialEq, Eq)]
107 #[non_exhaustive]
108 pub struct Base;
109
110 impl private::Sealed for Base {}
111 impl TimeZoneModel for Base {
112 type TimeZoneVariant = ();
113 type ZoneNameTimestamp = ();
114 }
115
116 /// A time zone containing a time zone ID, optional offset, and local time.
117 #[derive(Debug, PartialEq, Eq)]
118 #[non_exhaustive]
119 pub struct AtTime;
120
121 impl private::Sealed for AtTime {}
122 impl TimeZoneModel for AtTime {
123 type TimeZoneVariant = ();
124 type ZoneNameTimestamp = ZoneNameTimestamp;
125 }
126
127 /// A time zone containing a time zone ID, optional offset, local time, and zone variant.
128 #[derive(Debug, PartialEq, Eq)]
129 #[non_exhaustive]
130 #[deprecated(
131 since = "2.1.0",
132 note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore. use `TimeZoneInfo<AtTime>`"
133 )]
134 pub struct Full;
135
136 #[allow(deprecated)]
137 impl private::Sealed for Full {}
138 #[allow(deprecated)]
139 impl TimeZoneModel for Full {
140 type TimeZoneVariant = TimeZoneVariant;
141 type ZoneNameTimestamp = ZoneNameTimestamp;
142 }
143 }
144
145 /// A CLDR time zone identity.
146 ///
147 /// **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.**
148 ///
149 /// This can be created directly from BCP-47 strings, or it can be parsed from IANA IDs.
150 ///
151 /// CLDR uses difference equivalence classes than IANA. For example, `Europe/Oslo` is
152 /// an alias to `Europe/Berlin` in IANA (because they agree since 1970), but these are
153 /// different identities in CLDR, as we want to be able to say "Norway Time" and
154 /// "Germany Time". On the other hand `Europe/Belfast` and `Europe/London` are the same
155 /// CLDR identity ("UK Time").
156 ///
157 /// See the docs on [`zone`](crate::zone) for more information.
158 ///
159 /// ```
160 /// use icu::locale::subtags::subtag;
161 /// use icu::time::zone::{IanaParser, TimeZone};
162 ///
163 /// let parser = IanaParser::new();
164 /// assert_eq!(parser.parse("Europe/Oslo"), TimeZone(subtag!("noosl")));
165 /// assert_eq!(parser.parse("Europe/Berlin"), TimeZone(subtag!("deber")));
166 /// assert_eq!(parser.parse("Europe/Belfast"), TimeZone(subtag!("gblon")));
167 /// assert_eq!(parser.parse("Europe/London"), TimeZone(subtag!("gblon")));
168 /// ```
169 #[repr(transparent)]
170 #[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd, yoke::Yokeable, ULE, Hash)]
171 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
172 #[cfg_attr(feature = "datagen", databake(path = icu_time::provider))]
173 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
174 #[allow(clippy::exhaustive_structs)] // This is a stable newtype
175 pub struct TimeZone(pub Subtag);
176
177 impl TimeZone {
178 /// The synthetic `Etc/Unknown` time zone.
179 ///
180 /// This is the result of parsing unknown zones. It's important that such parsing does not
181 /// fail, as new zones are added all the time, and ICU4X might not be up to date.
182 pub const UNKNOWN: Self = Self(subtag!("unk"));
183
184 /// Whether this [`TimeZone`] equals [`TimeZone::UNKNOWN`].
185 pub const fn is_unknown(self) -> bool {
186 matches!(self, Self::UNKNOWN)
187 }
188
189 /// Construct a [`TimeZone`] from an IANA time zone ID.
190 ///
191 /// See [`IanaParser`].
192 ///
193 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
194 #[cfg(feature = "compiled_data")]
195 pub fn from_iana_id(iana_id: &str) -> Self {
196 IanaParser::new().parse(iana_id)
197 }
198
199 /// Construct a [`TimeZone`] from a Windows time zone ID and region.
200 ///
201 /// See [`WindowsParser`].
202 ///
203 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
204 #[cfg(feature = "compiled_data")]
205 pub fn from_windows_id(windows_id: &str, region: Option<Region>) -> Self {
206 WindowsParser::new()
207 .parse(windows_id, region)
208 .unwrap_or(Self::UNKNOWN)
209 }
210
211 /// Construct a [`TimeZone`] from the platform-specific ID.
212 ///
213 /// On Windows systems, this resolves to [`TimeZone::from_windows_id`], on
214 /// all other systems to [`TimeZone::from_iana_id`].
215 ///
216 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
217 #[cfg(feature = "compiled_data")]
218 pub fn from_system_id(id: &str, _region: Option<Region>) -> Self {
219 #[cfg(target_os = "windows")]
220 return Self::from_windows_id(id, _region);
221 #[cfg(not(target_os = "windows"))]
222 return Self::from_iana_id(id);
223 }
224 }
225
226 impl Deref for TimeZone {
227 type Target = Subtag;
228
229 fn deref(&self) -> &Self::Target {
230 &self.0
231 }
232 }
233
234 impl AsULE for TimeZone {
235 type ULE = Self;
236
237 #[inline]
238 fn to_unaligned(self) -> Self::ULE {
239 self
240 }
241
242 #[inline]
243 fn from_unaligned(unaligned: Self::ULE) -> Self {
244 unaligned
245 }
246 }
247
248 #[cfg(feature = "alloc")]
249 impl<'a> zerovec::maps::ZeroMapKV<'a> for TimeZone {
250 type Container = zerovec::ZeroVec<'a, TimeZone>;
251 type Slice = zerovec::ZeroSlice<TimeZone>;
252 type GetType = TimeZone;
253 type OwnedType = TimeZone;
254 }
255
256 /// A utility type that can hold time zone information.
257 ///
258 /// **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.**
259 ///
260 /// See the docs on [`zone`](self) for more information.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use icu::calendar::Date;
266 /// use icu::locale::subtags::subtag;
267 /// use icu::time::DateTime;
268 /// use icu::time::Time;
269 /// use icu::time::TimeZone;
270 /// use icu::time::zone::TimeZoneVariant;
271 /// use icu::time::zone::UtcOffset;
272 /// use icu::time::zone::ZoneNameTimestamp;
273 ///
274 /// // Parse the IANA ID
275 /// let id = TimeZone::from_iana_id("America/Chicago");
276 ///
277 /// // Alternatively, use the BCP47 ID directly
278 /// let id = TimeZone(subtag!("uschi"));
279 ///
280 /// // Create a TimeZoneInfo<Base> by associating the ID with an offset
281 /// let time_zone = id.with_offset(UtcOffset::try_from_seconds(-6 * 3600).ok());
282 ///
283 /// // Extend to a `TimeZoneInfo<AtTime>` by adding a timestamp ...
284 /// let time_zone_at_time = time_zone.with_zone_name_timestamp(
285 /// ZoneNameTimestamp::from_epoch_seconds(1701493200),
286 /// );
287 ///
288 /// // ... or by adding a local time
289 /// let time_zone_at_time = time_zone.at_date_time(DateTime {
290 /// date: Date::try_new_coptic(1996, 12, 2).unwrap(),
291 /// time: Time::start_of_day(),
292 /// });
293 /// ```
294 #[derive(Debug, PartialEq, Eq)]
295 #[allow(clippy::exhaustive_structs)] // these four fields fully cover the needs of UTS 35
296 pub struct TimeZoneInfo<Model: models::TimeZoneModel> {
297 id: TimeZone,
298 offset: Option<UtcOffset>,
299 zone_name_timestamp: Model::ZoneNameTimestamp,
300 variant: Model::TimeZoneVariant,
301 }
302
303 impl<Model: models::TimeZoneModel> Clone for TimeZoneInfo<Model> {
304 fn clone(&self) -> Self {
305 *self
306 }
307 }
308
309 impl<Model: models::TimeZoneModel> Copy for TimeZoneInfo<Model> {}
310
311 impl<Model: models::TimeZoneModel> TimeZoneInfo<Model> {
312 /// The BCP47 time-zone identifier.
313 pub fn id(self) -> TimeZone {
314 self.id
315 }
316
317 /// The UTC offset, if known.
318 ///
319 /// This field is not enforced to be consistent with the time zone id.
320 pub fn offset(self) -> Option<UtcOffset> {
321 self.offset
322 }
323 }
324
325 impl<Model> TimeZoneInfo<Model>
326 where
327 Model: models::TimeZoneModel<ZoneNameTimestamp = ZoneNameTimestamp>,
328 {
329 /// The time at which to interpret the time zone.
330 pub fn zone_name_timestamp(self) -> ZoneNameTimestamp {
331 self.zone_name_timestamp
332 }
333 }
334
335 impl<Model> TimeZoneInfo<Model>
336 where
337 Model: models::TimeZoneModel<TimeZoneVariant = TimeZoneVariant>,
338 {
339 /// The time variant e.g. daylight or standard, if known.
340 ///
341 /// This field is not enforced to be consistent with the time zone id and offset.
342 pub fn variant(self) -> TimeZoneVariant {
343 self.variant
344 }
345 }
346
347 impl TimeZone {
348 /// Associates this [`TimeZone`] with a UTC offset, returning a [`TimeZoneInfo`].
349 pub const fn with_offset(self, mut offset: Option<UtcOffset>) -> TimeZoneInfo<models::Base> {
350 let mut id = self;
351
352 #[allow(clippy::identity_op, clippy::neg_multiply)]
353 let correct_offset = match self.0.as_str().as_bytes() {
354 b"utc" | b"gmt" => Some(UtcOffset::zero()),
355 b"utce01" => Some(UtcOffset::from_seconds_unchecked(1 * 60 * 60)),
356 b"utce02" => Some(UtcOffset::from_seconds_unchecked(2 * 60 * 60)),
357 b"utce03" => Some(UtcOffset::from_seconds_unchecked(3 * 60 * 60)),
358 b"utce04" => Some(UtcOffset::from_seconds_unchecked(4 * 60 * 60)),
359 b"utce05" => Some(UtcOffset::from_seconds_unchecked(5 * 60 * 60)),
360 b"utce06" => Some(UtcOffset::from_seconds_unchecked(6 * 60 * 60)),
361 b"utce07" => Some(UtcOffset::from_seconds_unchecked(7 * 60 * 60)),
362 b"utce08" => Some(UtcOffset::from_seconds_unchecked(8 * 60 * 60)),
363 b"utce09" => Some(UtcOffset::from_seconds_unchecked(9 * 60 * 60)),
364 b"utce10" => Some(UtcOffset::from_seconds_unchecked(10 * 60 * 60)),
365 b"utce11" => Some(UtcOffset::from_seconds_unchecked(11 * 60 * 60)),
366 b"utce12" => Some(UtcOffset::from_seconds_unchecked(12 * 60 * 60)),
367 b"utce13" => Some(UtcOffset::from_seconds_unchecked(13 * 60 * 60)),
368 b"utce14" => Some(UtcOffset::from_seconds_unchecked(14 * 60 * 60)),
369 b"utcw01" => Some(UtcOffset::from_seconds_unchecked(-1 * 60 * 60)),
370 b"utcw02" => Some(UtcOffset::from_seconds_unchecked(-2 * 60 * 60)),
371 b"utcw03" => Some(UtcOffset::from_seconds_unchecked(-3 * 60 * 60)),
372 b"utcw04" => Some(UtcOffset::from_seconds_unchecked(-4 * 60 * 60)),
373 b"utcw05" => Some(UtcOffset::from_seconds_unchecked(-5 * 60 * 60)),
374 b"utcw06" => Some(UtcOffset::from_seconds_unchecked(-6 * 60 * 60)),
375 b"utcw07" => Some(UtcOffset::from_seconds_unchecked(-7 * 60 * 60)),
376 b"utcw08" => Some(UtcOffset::from_seconds_unchecked(-8 * 60 * 60)),
377 b"utcw09" => Some(UtcOffset::from_seconds_unchecked(-9 * 60 * 60)),
378 b"utcw10" => Some(UtcOffset::from_seconds_unchecked(-10 * 60 * 60)),
379 b"utcw11" => Some(UtcOffset::from_seconds_unchecked(-11 * 60 * 60)),
380 b"utcw12" => Some(UtcOffset::from_seconds_unchecked(-12 * 60 * 60)),
381 _ => None,
382 };
383
384 match (correct_offset, offset) {
385 // The Etc/* zones have fixed defined offsets. By setting them here,
386 // they won't format as UTC+?.
387 (Some(c), None) => {
388 offset = Some(c);
389
390 // The Etc/GMT+X zones do not have display names, so they format
391 // exactly like UNKNOWN with the same offset. For the sake of
392 // equality, set the ID to UNKNOWN as well.
393 if id.0.as_str().len() > 3 {
394 id = Self::UNKNOWN;
395 }
396 }
397 // Garbage offset for a fixed zone, now we know nothing
398 (Some(c), Some(o)) if c.to_seconds() != o.to_seconds() => {
399 offset = None;
400 id = Self::UNKNOWN;
401 }
402 _ => {}
403 }
404
405 TimeZoneInfo {
406 id,
407 offset,
408 zone_name_timestamp: (),
409 variant: (),
410 }
411 }
412
413 /// Converts this [`TimeZone`] into a [`TimeZoneInfo`] without an offset.
414 pub const fn without_offset(self) -> TimeZoneInfo<models::Base> {
415 self.with_offset(None)
416 }
417 }
418
419 impl TimeZoneInfo<models::Base> {
420 /// Creates a time zone info with no information.
421 pub const fn unknown() -> Self {
422 Self {
423 id: TimeZone::UNKNOWN,
424 offset: None,
425 zone_name_timestamp: (),
426 variant: (),
427 }
428 }
429
430 /// Creates a new [`TimeZoneInfo`] for the UTC time zone.
431 pub const fn utc() -> Self {
432 TimeZoneInfo {
433 id: TimeZone(subtag!("utc")),
434 offset: Some(UtcOffset::zero()),
435 zone_name_timestamp: (),
436 variant: (),
437 }
438 }
439
440 /// Sets the [`ZoneNameTimestamp`] field.
441 pub fn with_zone_name_timestamp(
442 self,
443 zone_name_timestamp: ZoneNameTimestamp,
444 ) -> TimeZoneInfo<models::AtTime> {
445 TimeZoneInfo {
446 offset: self.offset,
447 id: self.id,
448 zone_name_timestamp,
449 variant: (),
450 }
451 }
452
453 /// Sets the [`ZoneNameTimestamp`] to the given datetime.
454 ///
455 /// If the offset is known, the datetime is interpreted as a local time,
456 /// otherwise as UTC. This produces correct results for the vast majority
457 /// of cases, however close to metazone changes (Eastern Time -> Central Time)
458 /// it might be incorrect if the offset is not known.
459 ///
460 /// Also see [`Self::with_zone_name_timestamp`].
461 pub fn at_date_time<C: AsCalendar>(
462 self,
463 date_time: DateTime<C>,
464 ) -> TimeZoneInfo<models::AtTime> {
465 self.at_rd_time(date_time.date.to_rata_die(), date_time.time)
466 }
467
468 /// Use [`Self::at_date_time`].
469 #[deprecated(since = "2.2.0", note = "use `Self::at_date_time`")]
470 pub fn at_date_time_iso(self, date_time: DateTime<Iso>) -> TimeZoneInfo<models::AtTime> {
471 self.at_date_time(date_time)
472 }
473
474 pub(crate) fn at_rd_time(self, rd: RataDie, time: Time) -> TimeZoneInfo<models::AtTime> {
475 self.with_zone_name_timestamp(ZoneNameTimestamp::from_rd_time_zone(
476 rd,
477 time,
478 // If we don't have an offset, interpret as UTC. This is incorrect during O(a couple of
479 // hours) since the UNIX epoch (a handful of transitions times the few hours this is too
480 // early/late).
481 self.offset.unwrap_or(UtcOffset::zero()),
482 ))
483 }
484 }
485
486 impl TimeZoneInfo<models::AtTime> {
487 /// Sets a [`TimeZoneVariant`] on this time zone.
488 #[deprecated(
489 since = "2.1.0",
490 note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore"
491 )]
492 #[allow(deprecated)]
493 pub const fn with_variant(self, variant: TimeZoneVariant) -> TimeZoneInfo<models::Full> {
494 TimeZoneInfo {
495 offset: self.offset,
496 id: self.id,
497 zone_name_timestamp: self.zone_name_timestamp,
498 variant,
499 }
500 }
501
502 /// Sets the zone variant by calculating it using a [`VariantOffsetsCalculator`].
503 ///
504 /// If `offset()` is `None`, or if it doesn't match either of the
505 /// timezone's standard or daylight offset around [`zone_name_timestamp`](Self::zone_name_timestamp),
506 /// the variant will be set to [`TimeZoneVariant::Standard`] and the time zone
507 /// to [`TimeZone::UNKNOWN`].
508 ///
509 /// # Example
510 /// ```
511 /// use icu::calendar::Date;
512 /// use icu::time::DateTime;
513 /// use icu::time::Time;
514 /// use icu::time::TimeZone;
515 /// use icu::time::zone::TimeZoneVariant;
516 /// use icu::time::zone::UtcOffset;
517 /// use icu::time::zone::VariantOffsetsCalculator;
518 /// use icu::time::zone::ZoneNameTimestamp;
519 ///
520 /// // Chicago at UTC-6
521 /// let info = TimeZone::from_iana_id("America/Chicago")
522 /// .with_offset(UtcOffset::try_from_seconds(-6 * 3600).ok())
523 /// .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
524 /// 1701493200,
525 /// ))
526 /// .infer_variant(VariantOffsetsCalculator::new());
527 ///
528 /// assert_eq!(info.variant(), TimeZoneVariant::Standard);
529 ///
530 /// // Chicago at at UTC-5
531 /// let info = TimeZone::from_iana_id("America/Chicago")
532 /// .with_offset(UtcOffset::try_from_seconds(-5 * 3600).ok())
533 /// .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
534 /// 1685678400,
535 /// ))
536 /// .infer_variant(VariantOffsetsCalculator::new());
537 ///
538 /// assert_eq!(info.variant(), TimeZoneVariant::Daylight);
539 ///
540 /// // Chicago at UTC-7
541 /// let info = TimeZone::from_iana_id("America/Chicago")
542 /// .with_offset(UtcOffset::try_from_seconds(-7 * 3600).ok())
543 /// .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(
544 /// 1701493200,
545 /// ))
546 /// .infer_variant(VariantOffsetsCalculator::new());
547 ///
548 /// // Whatever it is, it's not Chicago
549 /// assert_eq!(info.id(), TimeZone::UNKNOWN);
550 /// assert_eq!(info.variant(), TimeZoneVariant::Standard);
551 /// ```
552 #[deprecated(
553 since = "2.1.0",
554 note = "creating a `TimeZoneInfo<Full>` is not required for formatting anymore"
555 )]
556 #[allow(deprecated)]
557 pub fn infer_variant(
558 self,
559 calculator: VariantOffsetsCalculatorBorrowed,
560 ) -> TimeZoneInfo<models::Full> {
561 let Some(offset) = self.offset else {
562 return TimeZone::UNKNOWN
563 .with_offset(self.offset)
564 .with_zone_name_timestamp(self.zone_name_timestamp)
565 .with_variant(TimeZoneVariant::Standard);
566 };
567 let Some(variant) = calculator
568 .compute_offsets_from_time_zone_and_name_timestamp(self.id, self.zone_name_timestamp)
569 .and_then(|os| {
570 if os.standard == offset {
571 Some(TimeZoneVariant::Standard)
572 } else if os.daylight == Some(offset) {
573 Some(TimeZoneVariant::Daylight)
574 } else {
575 None
576 }
577 })
578 else {
579 return TimeZone::UNKNOWN
580 .with_offset(self.offset)
581 .with_zone_name_timestamp(self.zone_name_timestamp)
582 .with_variant(TimeZoneVariant::Standard);
583 };
584 self.with_variant(variant)
585 }
586 }
587
588 #[deprecated(
589 since = "2.1.0",
590 note = "TimeZoneVariants don't need to be constructed in user code"
591 )]
592 pub use crate::provider::TimeZoneVariant;
593
594 impl TimeZoneVariant {
595 /// Creates a zone variant from a TZDB `isdst` flag, if it is known that the TZDB was built with
596 /// `DATAFORM=rearguard`.
597 ///
598 /// If it is known that the database was *not* built with `rearguard`, a caller can try to adjust
599 /// for the differences. This is a moving target, for example the known differences for 2025a are:
600 ///
601 /// * `Europe/Dublin` since 1968-10-27
602 /// * `Africa/Windhoek` between 1994-03-20 and 2017-10-24
603 /// * `Africa/Casablanca` and `Africa/El_Aaiun` since 2018-10-28
604 ///
605 /// If the TZDB build mode is unknown or variable, use [`TimeZoneInfo::infer_variant`].
606 #[deprecated(
607 since = "2.1.0",
608 note = "TimeZoneVariants don't need to be constructed in user code"
609 )]
610 pub const fn from_rearguard_isdst(isdst: bool) -> Self {
611 if isdst {
612 TimeZoneVariant::Daylight
613 } else {
614 TimeZoneVariant::Standard
615 }
616 }
617 }
618
619 #[test]
620 fn test_zone_info_equality() {
621 // offset inferred
622 assert_eq!(
623 TimeZone::from_iana_id("Etc/GMT-8").with_offset(None),
624 TimeZone::UNKNOWN.with_offset(Some(UtcOffset::from_seconds_unchecked(8 * 60 * 60)))
625 );
626 assert_eq!(
627 TimeZone::from_iana_id("Etc/UTC").with_offset(None),
628 TimeZoneInfo::utc()
629 );
630 assert_eq!(
631 TimeZone::from_iana_id("Etc/GMT").with_offset(None),
632 IanaParser::new()
633 .parse("Etc/GMT")
634 .with_offset(Some(UtcOffset::zero()))
635 );
636
637 // bogus offset removed
638 assert_eq!(
639 IanaParser::new()
640 .parse("Etc/GMT-8")
641 .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
642 TimeZoneInfo::unknown()
643 );
644 assert_eq!(
645 IanaParser::new()
646 .parse("Etc/UTC")
647 .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
648 TimeZoneInfo::unknown(),
649 );
650 assert_eq!(
651 IanaParser::new()
652 .parse("Etc/GMT")
653 .with_offset(Some(UtcOffset::from_seconds_unchecked(123))),
654 TimeZoneInfo::unknown()
655 );
656 }