jiff/tz/timezone.rs
1use jcore::tz::{posix, tzif};
2
3use crate::{
4 Timestamp, ZonedDateTime,
5 civil::DateTime,
6 error::{Error, tz::timezone::Error as E},
7 tz::{
8 ambiguous::{
9 AmbiguousOffset, AmbiguousTimestamp, AmbiguousZonedDateTime,
10 },
11 db::{TimeZoneLocation, find_primary_iana_name, find_tz_location},
12 offset::{Dst, Offset},
13 },
14 util::sync::Arc,
15};
16
17use self::repr::Repr;
18
19/// A representation of a [time zone].
20///
21/// A time zone is a set of rules for determining the civil time, via an offset
22/// from UTC, in a particular geographic region. In many cases, the offset
23/// in a particular time zone can vary over the course of a year through
24/// transitions into and out of [daylight saving time].
25///
26/// A `TimeZone` can be one of three possible representations:
27///
28/// * An identifier from the [IANA Time Zone Database] and the rules associated
29/// with that identifier.
30/// * A fixed offset where there are never any time zone transitions.
31/// * A [POSIX TZ] string that specifies a standard offset and an optional
32/// daylight saving time offset along with a rule for when DST is in effect.
33/// The rule applies for every year. Since POSIX TZ strings cannot capture the
34/// full complexity of time zone rules, they generally should not be used.
35///
36/// The most practical and useful representation is an IANA time zone. Namely,
37/// it enjoys broad support and its database is regularly updated to reflect
38/// real changes in time zone rules throughout the world. On Unix systems,
39/// the time zone database is typically found at `/usr/share/zoneinfo`. For
40/// more information on how Jiff interacts with The Time Zone Database, see
41/// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase).
42///
43/// In typical usage, users of Jiff shouldn't need to reference a `TimeZone`
44/// directly. Instead, there are convenience APIs on datetime types that accept
45/// IANA time zone identifiers and do automatic database lookups for you. For
46/// example, to convert a timestamp to a zone aware datetime:
47///
48/// ```
49/// use jiff::Timestamp;
50///
51/// let ts = Timestamp::from_second(1_456_789_123)?;
52/// let zdt = ts.in_tz("America/New_York")?;
53/// assert_eq!(zdt.to_string(), "2016-02-29T18:38:43-05:00[America/New_York]");
54///
55/// # Ok::<(), Box<dyn std::error::Error>>(())
56/// ```
57///
58/// Or to convert a civil datetime to a zoned datetime corresponding to a
59/// precise instant in time:
60///
61/// ```
62/// use jiff::civil::date;
63///
64/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
65/// let zdt = dt.in_tz("America/New_York")?;
66/// assert_eq!(zdt.to_string(), "2024-07-15T21:27:00-04:00[America/New_York]");
67///
68/// # Ok::<(), Box<dyn std::error::Error>>(())
69/// ```
70///
71/// Or even converted a zoned datetime from one time zone to another:
72///
73/// ```
74/// use jiff::civil::date;
75///
76/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
77/// let zdt1 = dt.in_tz("America/New_York")?;
78/// let zdt2 = zdt1.in_tz("Asia/Jerusalem")?;
79/// assert_eq!(zdt2.to_string(), "2024-07-16T04:27:00+03:00[Asia/Jerusalem]");
80///
81/// # Ok::<(), Box<dyn std::error::Error>>(())
82/// ```
83///
84/// # The system time zone
85///
86/// The system time zone can be retrieved via [`TimeZone::system`]. If it
87/// couldn't be detected or if the `tz-system` crate feature is not enabled,
88/// then [`TimeZone::unknown`] is returned. `TimeZone::system` is what's used
89/// internally for retrieving the current zoned datetime via
90/// [`ZonedDateTime::now`].
91///
92/// While there is no platform independent way to detect your system's
93/// "default" time zone, Jiff employs best-effort heuristics to determine it.
94/// (For example, by examining `/etc/localtime` on Unix systems or the `TZ`
95/// environment variable.) When the heuristics fail, Jiff will emit a `WARN`
96/// level log. It can be viewed by installing a `log` compatible logger, such
97/// as [`env_logger`].
98///
99/// # Custom time zones
100///
101/// At present, Jiff doesn't provide any APIs for manually constructing a
102/// custom time zone. However, [`TimeZone::tzif`] is provided for reading
103/// any valid TZif formatted data, as specified by [RFC 8536]. This provides
104/// an interoperable way of utilizing custom time zone rules.
105///
106/// # A `TimeZone` is immutable
107///
108/// Once a `TimeZone` is created, it is immutable. That is, its underlying
109/// time zone transition rules will never change. This is true for system time
110/// zones or even if the IANA Time Zone Database it was loaded from changes on
111/// disk. The only way such changes can be observed is by re-requesting the
112/// `TimeZone` from a `TimeZoneDatabase`. (Or, in the case of the system time
113/// zone, by calling `TimeZone::system`.)
114///
115/// # A `TimeZone` is cheap to clone
116///
117/// A `TimeZone` can be cheaply cloned. It uses automatic reference counting
118/// internally. When `alloc` is disabled, cloning a `TimeZone` is still cheap
119/// because POSIX time zones and TZif time zones are unsupported. Therefore,
120/// cloning a time zone does a deep copy (since automatic reference counting is
121/// not available), but the data being copied is small.
122///
123/// # Time zone equality
124///
125/// `TimeZone` provides an imperfect notion of equality. That is, when two time
126/// zones are equal, then it is guaranteed for them to have the same rules.
127/// However, two time zones may compare unequal and yet still have the same
128/// rules.
129///
130/// The equality semantics are as follows:
131///
132/// * Two fixed offset time zones are equal when their offsets are equal.
133/// * Two POSIX time zones are equal when their rule strings parse to identical
134/// rules in memory.
135/// * Two IANA time zones are equal when their primary identifiers are equal
136/// and their underlying checksums of the TZif data are equivalent. If a
137/// primary identifier is unavailable, then the time zone's IANA identifier
138/// is used instead.
139/// * Two TZif time zones whose `iana_name()` is `None` are equivalent only
140/// when their underlying checksums of the TZif data are equivalent.
141/// * In all other cases, time zones are unequal.
142///
143/// Time zone equality is, for example, used in APIs like
144/// [`ZonedDateTime::since`] when asking for spans with calendar units. Namely,
145/// since days can be of different lengths in different time zones,
146/// `ZonedDateTime::since` will return an error when the two zoned datetimes
147/// are in different time zones and when the caller requests units greater than
148/// hours.
149///
150/// # Dealing with ambiguity
151///
152/// The principal job of a `TimeZone` is to provide two different
153/// transformations:
154///
155/// * A conversion from a [`Timestamp`] to a civil time (also known as local,
156/// naive or plain time). This conversion is always unambiguous. That is,
157/// there is always precisely one representation of civil time for any
158/// particular instant in time for a particular time zone.
159/// * A conversion from a [`civil::DateTime`](crate::civil::DateTime) to an
160/// instant in time. This conversion is sometimes ambiguous in that a civil
161/// time might have either never appear on the clocks in a particular
162/// time zone (a gap), or in that the civil time may have been repeated on the
163/// clocks in a particular time zone (a fold). Typically, a transition to
164/// daylight saving time is a gap, while a transition out of daylight saving
165/// time is a fold.
166///
167/// The timestamp-to-civil time conversion is done via
168/// [`TimeZone::to_datetime`], or its lower level counterpart,
169/// [`TimeZone::to_offset`]. The civil time-to-timestamp conversion is done
170/// via one of the following routines:
171///
172/// * [`TimeZone::to_zoned_datetime`] conveniently returns a [`ZonedDateTime`]
173/// and automatically uses the
174/// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
175/// strategy if the given civil datetime is ambiguous in the time zone.
176/// * [`TimeZone::to_ambiguous_zoned_datetime`] returns a potentially
177/// ambiguous zoned datetime, [`AmbiguousZonedDateTime`], and provides
178/// fine-grained control over how to resolve ambiguity, if it occurs.
179/// * [`TimeZone::to_timestamp`] is like `TimeZone::to_zoned_datetime`, but
180/// returns a [`Timestamp`] instead.
181/// * [`TimeZone::to_ambiguous_timestamp`] is like
182/// `TimeZone::to_ambiguous_zoned_datetime`, but returns an
183/// [`AmbiguousTimestamp`] instead.
184///
185/// Here is an example where we explore the different disambiguation strategies
186/// for a fold in time, where in this case, the 1 o'clock hour is repeated:
187///
188/// ```
189/// use jiff::{civil::date, tz::TimeZone};
190///
191/// let tz = TimeZone::get("America/New_York")?;
192/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
193/// // It's ambiguous, so asking for an unambiguous instant presents an error!
194/// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
195/// // Gives you the earlier time in a fold, i.e., before DST ends:
196/// assert_eq!(
197/// tz.to_ambiguous_zoned_datetime(dt).earlier()?.to_string(),
198/// "2024-11-03T01:30:00-04:00[America/New_York]",
199/// );
200/// // Gives you the later time in a fold, i.e., after DST ends.
201/// // Notice the offset change from the previous example!
202/// assert_eq!(
203/// tz.to_ambiguous_zoned_datetime(dt).later()?.to_string(),
204/// "2024-11-03T01:30:00-05:00[America/New_York]",
205/// );
206/// // "Just give me something reasonable"
207/// assert_eq!(
208/// tz.to_ambiguous_zoned_datetime(dt).compatible()?.to_string(),
209/// "2024-11-03T01:30:00-04:00[America/New_York]",
210/// );
211///
212/// # Ok::<(), Box<dyn std::error::Error>>(())
213/// ```
214///
215/// # Serde integration
216///
217/// At present, a `TimeZone` does not implement Serde's `Serialize` or
218/// `Deserialize` traits directly. Nor does it implement `std::fmt::Display`
219/// or `std::str::FromStr`. The reason for this is that it's not totally
220/// clear if there is one single obvious behavior. Moreover, some `TimeZone`
221/// values do not have an obvious succinct serialized representation. (For
222/// example, when `/etc/localtime` on a Unix system is your system's time zone,
223/// and it isn't a symlink to a TZif file in `/usr/share/zoneinfo`. In which
224/// case, an IANA time zone identifier cannot easily be deduced by Jiff.)
225///
226/// Instead, Jiff offers helpers for use with Serde's [`with` attribute] via
227/// the [`fmt::serde`](crate::fmt::serde) module:
228///
229/// ```
230/// use jiff::tz::TimeZone;
231///
232/// #[derive(Debug, serde::Deserialize, serde::Serialize)]
233/// struct Record {
234/// #[serde(with = "jiff::fmt::serde::tz::optional")]
235/// tz: Option<TimeZone>,
236/// }
237///
238/// let json = r#"{"tz":"America/Nuuk"}"#;
239/// let got: Record = serde_json::from_str(&json)?;
240/// assert_eq!(got.tz, Some(TimeZone::get("America/Nuuk")?));
241/// assert_eq!(serde_json::to_string(&got)?, json);
242///
243/// # Ok::<(), Box<dyn std::error::Error>>(())
244/// ```
245///
246/// Alternatively, you may use the
247/// [`fmt::temporal::DateTimeParser::parse_time_zone`](crate::fmt::temporal::DateTimeParser::parse_time_zone)
248/// or
249/// [`fmt::temporal::DateTimePrinter::print_time_zone`](crate::fmt::temporal::DateTimePrinter::print_time_zone)
250/// routines to parse or print `TimeZone` values without using Serde.
251///
252/// [time zone]: https://en.wikipedia.org/wiki/Time_zone
253/// [daylight saving time]: https://en.wikipedia.org/wiki/Daylight_saving_time
254/// [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
255/// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
256/// [`env_logger`]: https://docs.rs/env_logger
257/// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
258/// [`with` attribute]: https://serde.rs/field-attrs.html#with
259#[derive(Clone, Eq, PartialEq)]
260pub struct TimeZone {
261 repr: Repr,
262}
263
264impl TimeZone {
265 /// The UTC time zone.
266 ///
267 /// The offset of this time is `0` and never has any transitions.
268 pub const UTC: TimeZone = TimeZone { repr: Repr::utc() };
269
270 /// Returns the system configured time zone, if available.
271 ///
272 /// Detection of a system's default time zone is generally heuristic
273 /// based and platform specific.
274 ///
275 /// If callers need to know whether discovery of the system time zone
276 /// failed, then use [`TimeZone::try_system`].
277 ///
278 /// # Fallback behavior
279 ///
280 /// If the system's default time zone could not be determined, or if
281 /// the `tz-system` crate feature is not enabled, then this returns
282 /// [`TimeZone::unknown`]. A `WARN` level log will also be emitted with
283 /// a message explaining why time zone detection failed. The fallback to
284 /// an unknown time zone is a practical trade-off, is what most other
285 /// systems tend to do and is also recommended by [relevant standards such
286 /// as freedesktop.org][freedesktop-org-localtime].
287 ///
288 /// An unknown time zone _behaves_ like [`TimeZone::UTC`], but will
289 /// print as `Etc/Unknown` when converting a `ZonedDateTime` to a string.
290 ///
291 /// If you would like to fall back to UTC instead of
292 /// the special "unknown" time zone, then you can do
293 /// `TimeZone::try_system().unwrap_or(TimeZone::UTC)`.
294 ///
295 /// # Platform behavior
296 ///
297 /// This section is a "best effort" explanation of how the time zone is
298 /// detected on supported platforms. The behavior is subject to change.
299 ///
300 /// On all platforms, the `TZ` environment variable overrides any other
301 /// heuristic, and provides a way for end users to set the time zone for
302 /// specific use cases. In general, Jiff respects the [POSIX TZ] rules.
303 /// Here are some examples:
304 ///
305 /// * `TZ=America/New_York` for setting a time zone via an IANA Time Zone
306 /// Database Identifier.
307 /// * `TZ=/usr/share/zoneinfo/America/New_York` for setting a time zone
308 /// by providing a file path to a TZif file directly.
309 /// * `TZ=EST5EDT,M3.2.0,M11.1.0` for setting a time zone via a daylight
310 /// saving time transition rule.
311 ///
312 /// When `TZ` is set to an invalid value, Jiff uses the fallback behavior
313 /// described above.
314 ///
315 /// Otherwise, when `TZ` isn't set, then:
316 ///
317 /// On Unix non-Android systems, this inspects `/etc/localtime`. If it's
318 /// a symbolic link to an entry in `/usr/share/zoneinfo`, then the suffix
319 /// is considered an IANA Time Zone Database identifier. Otherwise,
320 /// `/etc/localtime` is read as a TZif file directly.
321 ///
322 /// On Android systems, this inspects the `persist.sys.timezone` property.
323 ///
324 /// On Windows, the system time zone is determined via
325 /// [`GetDynamicTimeZoneInformation`]. The result is then mapped to an
326 /// IANA Time Zone Database identifier via Unicode's
327 /// [CLDR XML data].
328 ///
329 /// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
330 /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
331 /// [`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
332 /// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
333 #[inline]
334 pub fn system() -> TimeZone {
335 match TimeZone::try_system() {
336 Ok(tz) => tz,
337 Err(_err) => {
338 warn!(
339 "failed to get system time zone, \
340 falling back to `Etc/Unknown` \
341 (which behaves like UTC): {_err}",
342 );
343 TimeZone::unknown()
344 }
345 }
346 }
347
348 /// Returns the system configured time zone, if available.
349 ///
350 /// Detection of a system's default time zone is generally heuristic
351 /// based and platform specific.
352 ///
353 /// Note that callers should generally prefer using [`TimeZone::system`].
354 /// If a system time zone could not be found, then it falls
355 /// back to [`TimeZone::UTC`] automatically. This is often
356 /// what is recommended by [relevant standards such as
357 /// freedesktop.org][freedesktop-org-localtime]. Conversely, this routine
358 /// is useful if detection of a system's default time zone is critical.
359 ///
360 /// # Errors
361 ///
362 /// If the system's default time zone could not be determined, or if the
363 /// `tz-system` crate feature is not enabled, then this returns an error.
364 ///
365 /// # Platform behavior
366 ///
367 /// This section is a "best effort" explanation of how the time zone is
368 /// detected on supported platforms. The behavior is subject to change.
369 ///
370 /// On all platforms, the `TZ` environment variable overrides any other
371 /// heuristic, and provides a way for end users to set the time zone for
372 /// specific use cases. In general, Jiff respects the [POSIX TZ] rules.
373 /// Here are some examples:
374 ///
375 /// * `TZ=America/New_York` for setting a time zone via an IANA Time Zone
376 /// Database Identifier.
377 /// * `TZ=/usr/share/zoneinfo/America/New_York` for setting a time zone
378 /// by providing a file path to a TZif file directly.
379 /// * `TZ=EST5EDT,M3.2.0,M11.1.0` for setting a time zone via a daylight
380 /// saving time transition rule.
381 ///
382 /// When `TZ` is set to an invalid value, then this routine returns an
383 /// error.
384 ///
385 /// Otherwise, when `TZ` isn't set, then:
386 ///
387 /// On Unix systems, this inspects `/etc/localtime`. If it's a symbolic
388 /// link to an entry in `/usr/share/zoneinfo`, then the suffix is
389 /// considered an IANA Time Zone Database identifier. Otherwise,
390 /// `/etc/localtime` is read as a TZif file directly.
391 ///
392 /// On Windows, the system time zone is determined via
393 /// [`GetDynamicTimeZoneInformation`]. The result is then mapped to an
394 /// IANA Time Zone Database identifier via Unicode's
395 /// [CLDR XML data].
396 ///
397 /// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
398 /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
399 /// [`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
400 /// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
401 #[inline]
402 pub fn try_system() -> Result<TimeZone, Error> {
403 #[cfg(not(feature = "tz-system"))]
404 {
405 Err(Error::from(crate::error::CrateFeatureError::TzSystem)
406 .context(E::FailedSystem))
407 }
408 #[cfg(feature = "tz-system")]
409 {
410 crate::tz::system::get(crate::tz::db(), None)
411 }
412 }
413
414 /// This is like [`TimeZone::try_system`], except instead of reading the
415 /// `TZ` environment variable, this will use the provided value instead.
416 ///
417 /// The custom environment variable value is an `Option` so that callers
418 /// can simulate what happens when no `TZ` environment variable is set.
419 ///
420 /// The provided value is expected to be in an ASCII-compatible
421 /// encoding. It is supported and encouraged for callers to use
422 /// `OsStr::as_encoded_bytes` if you have an `OsStr`.
423 ///
424 /// # Errors
425 ///
426 /// If the system's default time zone could not be determined, or if the
427 /// `tz-system` crate feature is not enabled, then this returns an error.
428 ///
429 /// # Platform behavior
430 ///
431 /// The platform specific documentation for [`TimeZone::try_system`]
432 /// applies here too, with one change: instead of reading the `TZ`
433 /// environment variable, the provided value is used instead and no
434 /// environment variables are consulted.
435 ///
436 /// Similarly, if `None` is provided, then this routine behaves like
437 /// `TimeZone::try_system` when the `TZ` environment variable is not set.
438 ///
439 /// # Example
440 ///
441 /// ```
442 /// use jiff::tz::TimeZone;
443 ///
444 /// let tz = TimeZone::try_system_with_tz_env(
445 /// Some(b"America/New_York"),
446 /// )?;
447 /// assert_eq!(tz.iana_name(), Some("America/New_York"));
448 ///
449 /// // It's also OK to pass POSIX time zone rules:
450 /// let tz = TimeZone::try_system_with_tz_env(
451 /// Some(b"PST8PDT,M3.2.0,M11.1.0"),
452 /// )?;
453 /// assert_eq!(tz.iana_name(), None);
454 ///
455 /// # Ok::<(), Box<dyn std::error::Error>>(())
456 /// ```
457 #[inline]
458 pub fn try_system_with_tz_env(
459 tz_env_value: Option<&[u8]>,
460 ) -> Result<TimeZone, Error> {
461 #[cfg(not(feature = "tz-system"))]
462 {
463 Err(Error::from(crate::error::CrateFeatureError::TzSystem)
464 .context(E::FailedSystem))
465 }
466 #[cfg(feature = "tz-system")]
467 {
468 crate::tz::system::get(crate::tz::db(), Some(tz_env_value))
469 }
470 }
471
472 /// A convenience function for performing a time zone database lookup for
473 /// the given time zone identifier. It uses the default global time zone
474 /// database via [`tz::db()`](crate::tz::db()).
475 ///
476 /// It is guaranteed that if the given time zone name is case insensitively
477 /// equivalent to `UTC`, then the time zone returned will be equivalent to
478 /// `TimeZone::UTC`. Similarly for `Etc/Unknown` and `TimeZone::unknown()`.
479 ///
480 /// # Errors
481 ///
482 /// This returns an error if the given time zone identifier could not be
483 /// found in the default [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase).
484 ///
485 /// # Example
486 ///
487 /// ```
488 /// use jiff::{tz::TimeZone, Timestamp};
489 ///
490 /// let tz = TimeZone::get("Asia/Tokyo")?;
491 /// assert_eq!(
492 /// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
493 /// "1970-01-01T09:00:00",
494 /// );
495 ///
496 /// # Ok::<(), Box<dyn std::error::Error>>(())
497 /// ```
498 #[inline]
499 pub fn get(time_zone_name: &str) -> Result<TimeZone, Error> {
500 crate::tz::db().get(time_zone_name)
501 }
502
503 /// Returns a time zone with a fixed offset.
504 ///
505 /// A fixed offset will never have any transitions and won't follow any
506 /// particular time zone rules. In general, one should avoid using fixed
507 /// offset time zones unless you have a specific need for them. Otherwise,
508 /// IANA time zones via [`TimeZone::get`] should be preferred, as they
509 /// more accurately model the actual time zone transitions rules used in
510 /// practice.
511 ///
512 /// # Example
513 ///
514 /// ```
515 /// use jiff::{tz::{self, TimeZone}, Timestamp};
516 ///
517 /// let tz = TimeZone::fixed(tz::offset(10));
518 /// assert_eq!(
519 /// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
520 /// "1970-01-01T10:00:00",
521 /// );
522 ///
523 /// # Ok::<(), Box<dyn std::error::Error>>(())
524 /// ```
525 #[inline]
526 pub const fn fixed(offset: Offset) -> TimeZone {
527 // Not doing `offset == Offset::UTC` because of `const`.
528 if offset.seconds() == 0 {
529 return TimeZone::UTC;
530 }
531 let repr = Repr::fixed(offset);
532 TimeZone { repr }
533 }
534
535 /// Creates a time zone from a [POSIX TZ] rule string.
536 ///
537 /// A POSIX time zone provides a way to tersely define a single daylight
538 /// saving time transition rule (or none at all) that applies for all
539 /// years.
540 ///
541 /// Users should avoid using this kind of time zone unless there is a
542 /// specific need for it. Namely, POSIX time zones cannot capture the full
543 /// complexity of time zone transition rules in the real world. (See the
544 /// example below.)
545 ///
546 /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
547 ///
548 /// # Errors
549 ///
550 /// This returns an error if the given POSIX time zone string is invalid.
551 ///
552 /// # Example
553 ///
554 /// This example demonstrates how a POSIX time zone may be historically
555 /// inaccurate:
556 ///
557 /// ```
558 /// use jiff::{civil::date, tz::TimeZone};
559 ///
560 /// // The tzdb entry for America/New_York.
561 /// let iana = TimeZone::get("America/New_York")?;
562 /// // The POSIX TZ string for New York DST that went into effect in 2007.
563 /// let posix = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0")?;
564 ///
565 /// // New York entered DST on April 2, 2006 at 2am:
566 /// let dt = date(2006, 4, 2).at(2, 0, 0, 0);
567 /// // The IANA tzdb entry correctly reports it as ambiguous:
568 /// assert!(iana.to_ambiguous_timestamp(dt).is_ambiguous());
569 /// // But the POSIX time zone does not:
570 /// assert!(!posix.to_ambiguous_timestamp(dt).is_ambiguous());
571 ///
572 /// # Ok::<(), Box<dyn std::error::Error>>(())
573 /// ```
574 #[cfg(feature = "alloc")]
575 pub fn posix(posix_tz_string: &str) -> Result<TimeZone, Error> {
576 let posix_tz = posix::TimeZone::parse(posix_tz_string)
577 .map_err(Error::jcore_posix_parse)?;
578 Ok(TimeZone::from_posix_tz(posix_tz))
579 }
580
581 /// Creates a time zone from a POSIX tz. Expose so that other parts of Jiff
582 /// can create a `TimeZone` from a POSIX tz. (Kinda sloppy to be honest.)
583 #[cfg(feature = "alloc")]
584 pub(crate) fn from_posix_tz(posix: posix::TimeZone) -> TimeZone {
585 let repr = Repr::arc_posix(Arc::new(posix));
586 TimeZone { repr }
587 }
588
589 /// Creates a time zone from TZif binary data, whose format is specified
590 /// in [RFC 8536]. All versions of TZif (up through version 4) are
591 /// supported.
592 ///
593 /// This constructor is typically not used, and instead, one should rely
594 /// on time zone lookups via time zone identifiers with routines like
595 /// [`TimeZone::get`]. However, this constructor does provide one way
596 /// of using custom time zones with Jiff.
597 ///
598 /// The name given should be a IANA time zone database identifier.
599 ///
600 /// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
601 ///
602 /// # Errors
603 ///
604 /// This returns an error if the given data was not recognized as valid
605 /// TZif.
606 #[cfg(feature = "alloc")]
607 pub fn tzif(name: &str, data: &[u8]) -> Result<TimeZone, Error> {
608 let name = jcore::tz::TimeZoneId::new_or_heap(name);
609 let tzif = tzif::TimeZone::parse(data)
610 .map_err(Error::jcore_tzif_parse)?
611 .into_named(name);
612 let repr = Repr::arc_tzif(Arc::new(tzif));
613 Ok(TimeZone { repr })
614 }
615
616 /// Returns a `TimeZone` that is specifically marked as "unknown."
617 ///
618 /// This corresponds to the Unicode CLDR identifier `Etc/Unknown`, which
619 /// is guaranteed to never be a valid IANA time zone identifier (as of
620 /// the `2025a` release of tzdb).
621 ///
622 /// This type of `TimeZone` is used in circumstances where one wants to
623 /// signal that discovering a time zone failed for some reason, but that
624 /// execution can reasonably continue. For example, [`TimeZone::system`]
625 /// returns this type of time zone when the system time zone could not be
626 /// discovered.
627 ///
628 /// # Example
629 ///
630 /// Jiff permits an "unknown" time zone to losslessly be transmitted
631 /// through serialization:
632 ///
633 /// ```
634 /// use jiff::{civil::date, tz::TimeZone, ZonedDateTime};
635 ///
636 /// let tz = TimeZone::unknown();
637 /// let zdt = date(2025, 2, 1).at(17, 0, 0, 0).to_zoned_datetime(tz)?;
638 /// assert_eq!(zdt.to_string(), "2025-02-01T17:00:00Z[Etc/Unknown]");
639 /// let got: ZonedDateTime = "2025-02-01T17:00:00Z[Etc/Unknown]".parse()?;
640 /// assert_eq!(got, zdt);
641 ///
642 /// # Ok::<(), Box<dyn std::error::Error>>(())
643 /// ```
644 ///
645 /// Note that not all systems support this. Some systems will reject
646 /// `Etc/Unknown` because it is not a valid IANA time zone identifier and
647 /// does not have an entry in the IANA time zone database. However, Jiff
648 /// takes this approach because it surfaces an error condition in detecting
649 /// the end user's time zone. Callers not wanting an "unknown" time zone
650 /// can use `TimeZone::try_system().unwrap_or(TimeZone::UTC)` instead of
651 /// `TimeZone::system`. (Where the latter falls back to the "unknown" time
652 /// zone when a system configured time zone could not be found.)
653 pub const fn unknown() -> TimeZone {
654 let repr = Repr::unknown();
655 TimeZone { repr }
656 }
657
658 /// This creates an unnamed TZif-backed `TimeZone`.
659 ///
660 /// At present, the only way for an unnamed TZif-backed `TimeZone` to be
661 /// created is when the system time zone has no identifiable name. For
662 /// example, when `/etc/localtime` is hard-linked to a TZif file instead
663 /// of being symlinked. In this case, there is no cheap and unambiguous
664 /// way to determine the time zone name. So we just let it be unnamed.
665 /// Since this is the only such case, and hopefully will only ever be the
666 /// only such case, we consider such unnamed TZif-back `TimeZone` values
667 /// as being the "system" time zone.
668 ///
669 /// When this is used to construct a `TimeZone`, the `TimeZone::name`
670 /// method will be "Local". This is... pretty unfortunate. I'm not sure
671 /// what else to do other than to make `TimeZone::name` return an
672 /// `Option<&str>`. But... we use it in a bunch of places and it just
673 /// seems bad for a time zone to not have a name.
674 ///
675 /// OK, because of the above, I renamed `TimeZone::name` to
676 /// `TimeZone::diagnostic_name`. This should make it clearer that you can't
677 /// really use the name to do anything interesting. This also makes more
678 /// sense for POSIX TZ strings too.
679 ///
680 /// In any case, this routine stays unexported because I don't want TZif
681 /// backed `TimeZone` values to proliferate. If you have a legitimate use
682 /// case otherwise, please file an issue. It will require API design.
683 ///
684 /// # Errors
685 ///
686 /// This returns an error if the given TZif data is invalid.
687 #[cfg(feature = "tz-system")]
688 pub(crate) fn tzif_system(data: &[u8]) -> Result<TimeZone, Error> {
689 let tzif = tzif::TimeZone::parse(data)
690 .map_err(Error::jcore_tzif_parse)?
691 .into_maybe_named(None);
692 let repr = Repr::arc_tzif(Arc::new(tzif));
693 Ok(TimeZone { repr })
694 }
695
696 #[inline]
697 pub(crate) fn diagnostic_name(&self) -> DiagnosticName<'_> {
698 DiagnosticName(self)
699 }
700
701 /// Returns true if and only if this `TimeZone` can be succinctly
702 /// serialized.
703 ///
704 /// Basically, this is only `false` when this `TimeZone` was created from
705 /// a `/etc/localtime` for which a valid IANA time zone identifier could
706 /// not be extracted.
707 #[cfg(feature = "serde")]
708 #[inline]
709 pub(crate) fn has_succinct_serialization(&self) -> bool {
710 repr::each! {
711 &self.repr,
712 UTC => true,
713 UNKNOWN => true,
714 FIXED(_offset) => true,
715 STATIC_TZIF(tzif) => tzif.name().is_some(),
716 ARC_TZIF(tzif) => tzif.name().is_some(),
717 ARC_POSIX(_posix) => true,
718 }
719 }
720
721 /// When this time zone was loaded from an IANA time zone database entry,
722 /// then this returns the canonicalized name for that time zone.
723 ///
724 /// # Example
725 ///
726 /// ```
727 /// use jiff::tz::TimeZone;
728 ///
729 /// let tz = TimeZone::get("america/NEW_YORK")?;
730 /// assert_eq!(tz.iana_name(), Some("America/New_York"));
731 ///
732 /// # Ok::<(), Box<dyn std::error::Error>>(())
733 /// ```
734 #[inline]
735 pub fn iana_name(&self) -> Option<&str> {
736 repr::each! {
737 &self.repr,
738 UTC => Some("UTC"),
739 // Note that while `Etc/Unknown` looks like an IANA time zone
740 // identifier, it is specifically and explicitly NOT an IANA time
741 // zone identifier. So we do not return it here if we have an
742 // unknown time zone identifier.
743 UNKNOWN => None,
744 FIXED(_offset) => None,
745 STATIC_TZIF(tzif) => tzif.name(),
746 ARC_TZIF(tzif) => tzif.name(),
747 ARC_POSIX(_posix) => None,
748 }
749 }
750
751 /// When this time zone was loaded from an IANA time zone database entry,
752 /// then this returns the primary name for that time zone.
753 ///
754 /// This follows the same [rules as ECMAScript][rules]. In effect, there is
755 /// at least one primary time zone identifier for each ISO 3166 country
756 /// code.
757 ///
758 /// [rules]: https://tc39.es/ecma402/#sup-availablenamedtimezoneidentifiers
759 ///
760 /// # Example
761 ///
762 /// ```
763 /// use jiff::tz::TimeZone;
764 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
765 ///
766 /// let tz = TimeZone::get("Asia/Calcutta")?;
767 /// assert_eq!(tz.primary_iana_name(), Some("Asia/Kolkata"));
768 ///
769 /// let tz = TimeZone::get("Europe/Prague")?;
770 /// assert_eq!(tz.primary_iana_name(), Some("Europe/Prague"));
771 ///
772 /// let tz = TimeZone::get("Asia/Kolkata")?;
773 /// assert_eq!(tz.primary_iana_name(), Some("Asia/Kolkata"));
774 ///
775 /// let tz = TimeZone::get("Atlantic/Jan_Mayen")?;
776 /// assert_eq!(tz.primary_iana_name(), Some("Arctic/Longyearbyen"));
777 ///
778 /// # Ok::<(), Box<dyn std::error::Error>>(())
779 /// ```
780 #[inline]
781 pub fn primary_iana_name(&self) -> Option<&str> {
782 repr::each! {
783 &self.repr,
784 UTC => Some("UTC"),
785 UNKNOWN => None,
786 FIXED(_offset) => None,
787 STATIC_TZIF(tzif) => tzif.name().and_then(find_primary_iana_name),
788 ARC_TZIF(tzif) => tzif.name().and_then(find_primary_iana_name),
789 ARC_POSIX(_posix) => None,
790 }
791 }
792
793 /// Returns true when this time zone is "primary."
794 ///
795 /// A time zone is primary when it is the preferred identifier according
796 /// to the [ECMAScript rules][rules]. Specifically, a time zone is
797 /// primary precisely when its IANA time zone identifier is equivalent to
798 /// its primary IANA time zone identifier.
799 ///
800 /// [rules]: https://tc39.es/ecma402/#sup-availablenamedtimezoneidentifiers
801 ///
802 /// # Example
803 ///
804 /// ```
805 /// use jiff::tz::TimeZone;
806 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
807 ///
808 /// let tz = TimeZone::get("Asia/Calcutta")?;
809 /// assert!(!tz.is_primary());
810 /// let tz = TimeZone::get("Asia/Kolkata")?;
811 /// assert!(tz.is_primary());
812 ///
813 /// let tz = TimeZone::get("Europe/Berlin")?;
814 /// assert!(tz.is_primary());
815 /// let tz = TimeZone::get("Europe/Copenhagen")?;
816 /// assert!(tz.is_primary());
817 ///
818 /// let tz1 = TimeZone::get("Asia/Calcutta")?;
819 /// let tz2 = TimeZone::get("Asia/Kolkata")?;
820 /// assert_eq!(tz1, tz2);
821 ///
822 /// # Ok::<(), Box<dyn std::error::Error>>(())
823 /// ```
824 #[inline]
825 pub fn is_primary(&self) -> bool {
826 self.iana_name()
827 .and_then(|name| Some((name, self.primary_iana_name()?)))
828 .map(|(name, primary)| name == primary)
829 .unwrap_or(false)
830 }
831
832 /// Returns geographical location information corresponding to this
833 /// time zone's primary time zone identifier.
834 ///
835 /// # Example
836 ///
837 /// ```
838 /// use jiff::tz::TimeZone;
839 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
840 ///
841 /// let tz = TimeZone::get("Europe/Copenhagen")?;
842 /// let loc = tz.location().unwrap();
843 /// assert_eq!(loc.country(), "DK");
844 ///
845 /// let tz = TimeZone::get("EuRoPe/BeRlIn")?;
846 /// let loc = tz.location().unwrap();
847 /// assert_eq!(loc.country(), "DE");
848 ///
849 /// let tz = TimeZone::get("asia/calcutta")?;
850 /// let loc = tz.location().unwrap();
851 /// assert_eq!(loc.country(), "IN");
852 ///
853 /// # Ok::<(), Box<dyn std::error::Error>>(())
854 /// ```
855 #[inline]
856 pub fn location(&self) -> Option<TimeZoneLocation> {
857 repr::each! {
858 &self.repr,
859 UTC => None,
860 UNKNOWN => None,
861 FIXED(_offset) => None,
862 STATIC_TZIF(tzif) => tzif.name().and_then(find_tz_location),
863 ARC_TZIF(tzif) => tzif.name().and_then(find_tz_location),
864 ARC_POSIX(_posix) => None,
865 }
866 }
867
868 /// Returns true if and only if this time zone is unknown.
869 ///
870 /// This has the special internal identifier of `Etc/Unknown`, and this
871 /// is what will be used when converting a `ZonedDateTime` to a string.
872 ///
873 /// Note that while `Etc/Unknown` looks like an IANA time zone identifier,
874 /// it is specifically and explicitly not one. It is reserved and is
875 /// guaranteed to never be an IANA time zone identifier.
876 ///
877 /// An unknown time zone can be created via [`TimeZone::unknown`]. It is
878 /// also returned by [`TimeZone::system`] when a system configured time
879 /// zone could not be found.
880 ///
881 /// # Example
882 ///
883 /// ```
884 /// use jiff::tz::TimeZone;
885 ///
886 /// let tz = TimeZone::unknown();
887 /// assert_eq!(tz.iana_name(), None);
888 /// assert!(tz.is_unknown());
889 /// ```
890 #[inline]
891 pub fn is_unknown(&self) -> bool {
892 self.repr.is_unknown()
893 }
894
895 /// When this time zone is a POSIX time zone, return it.
896 ///
897 /// This doesn't attempt to convert other time zones that are representable
898 /// as POSIX time zones to POSIX time zones (e.g., fixed offset time
899 /// zones). Instead, this only returns something when the actual
900 /// representation of the time zone is a POSIX time zone.
901 #[inline]
902 pub(crate) fn posix_tz(&self) -> Option<&posix::TimeZone> {
903 repr::each! {
904 &self.repr,
905 UTC => None,
906 UNKNOWN => None,
907 FIXED(_offset) => None,
908 STATIC_TZIF(_tzif) => None,
909 ARC_TZIF(_tzif) => None,
910 ARC_POSIX(posix) => Some(posix),
911 }
912 }
913
914 /// Returns the civil datetime corresponding to the given timestamp in this
915 /// time zone.
916 ///
917 /// This operation is always unambiguous. That is, for any instant in time
918 /// supported by Jiff (that is, a `Timestamp`), there is always precisely
919 /// one civil datetime corresponding to that instant.
920 ///
921 /// Note that this is considered a lower level routine. Consider working
922 /// with zoned datetimes instead, and use [`ZonedDateTime::datetime`] to
923 /// get its civil time if necessary.
924 ///
925 /// # Example
926 ///
927 /// ```
928 /// use jiff::{tz::TimeZone, Timestamp};
929 ///
930 /// let tz = TimeZone::get("Europe/Rome")?;
931 /// assert_eq!(
932 /// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
933 /// "1970-01-01T01:00:00",
934 /// );
935 ///
936 /// # Ok::<(), Box<dyn std::error::Error>>(())
937 /// ```
938 ///
939 /// As mentioned above, consider using `ZonedDateTime` instead:
940 ///
941 /// ```
942 /// use jiff::Timestamp;
943 ///
944 /// let zdt = Timestamp::UNIX_EPOCH.in_tz("Europe/Rome")?;
945 /// assert_eq!(zdt.datetime().to_string(), "1970-01-01T01:00:00");
946 ///
947 /// # Ok::<(), Box<dyn std::error::Error>>(())
948 /// ```
949 #[inline]
950 pub fn to_datetime(&self, timestamp: Timestamp) -> DateTime {
951 self.to_offset(timestamp).to_datetime(timestamp)
952 }
953
954 /// Returns the offset corresponding to the given timestamp in this time
955 /// zone.
956 ///
957 /// This operation is always unambiguous. That is, for any instant in time
958 /// supported by Jiff (that is, a `Timestamp`), there is always precisely
959 /// one offset corresponding to that instant.
960 ///
961 /// Given an offset, one can use APIs like [`Offset::to_datetime`] to
962 /// create a civil datetime from a timestamp.
963 ///
964 /// This also returns whether this timestamp is considered to be in
965 /// "daylight saving time," as well as the abbreviation for the time zone
966 /// at this time.
967 ///
968 /// # Example
969 ///
970 /// ```
971 /// use jiff::{tz::{self, TimeZone}, Timestamp};
972 ///
973 /// let tz = TimeZone::get("America/New_York")?;
974 ///
975 /// // A timestamp in DST in New York.
976 /// let ts = Timestamp::from_second(1_720_493_204)?;
977 /// let offset = tz.to_offset(ts);
978 /// assert_eq!(offset, tz::offset(-4));
979 /// assert_eq!(offset.to_datetime(ts).to_string(), "2024-07-08T22:46:44");
980 ///
981 /// // A timestamp *not* in DST in New York.
982 /// let ts = Timestamp::from_second(1_704_941_204)?;
983 /// let offset = tz.to_offset(ts);
984 /// assert_eq!(offset, tz::offset(-5));
985 /// assert_eq!(offset.to_datetime(ts).to_string(), "2024-01-10T21:46:44");
986 ///
987 /// # Ok::<(), Box<dyn std::error::Error>>(())
988 /// ```
989 #[inline]
990 pub fn to_offset(&self, timestamp: Timestamp) -> Offset {
991 repr::each! {
992 &self.repr,
993 UTC => Offset::UTC,
994 UNKNOWN => Offset::UTC,
995 FIXED(offset) => offset,
996 STATIC_TZIF(tzif) => Offset::from_jcore(
997 tzif.tz().to_offset(timestamp.to_jcore()),
998 ),
999 ARC_TZIF(tzif) => Offset::from_jcore(
1000 tzif.tz().to_offset(timestamp.to_jcore()),
1001 ),
1002 ARC_POSIX(posix) => Offset::from_jcore(
1003 posix.to_offset(timestamp.to_jcore()),
1004 ),
1005 }
1006 }
1007
1008 /// Returns the offset information corresponding to the given timestamp in
1009 /// this time zone. This includes the offset along with daylight saving
1010 /// time status and a time zone abbreviation.
1011 ///
1012 /// This is like [`TimeZone::to_offset`], but returns the aforementioned
1013 /// extra data in addition to the offset. This data may, in some cases, be
1014 /// more expensive to compute.
1015 ///
1016 /// # Example
1017 ///
1018 /// ```
1019 /// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
1020 ///
1021 /// let tz = TimeZone::get("America/New_York")?;
1022 ///
1023 /// // A timestamp in DST in New York.
1024 /// let ts = Timestamp::from_second(1_720_493_204)?;
1025 /// let info = tz.to_offset_info(ts);
1026 /// assert_eq!(info.offset(), tz::offset(-4));
1027 /// assert_eq!(info.dst(), Dst::Yes);
1028 /// assert_eq!(info.abbreviation(), "EDT");
1029 /// assert_eq!(
1030 /// info.offset().to_datetime(ts).to_string(),
1031 /// "2024-07-08T22:46:44",
1032 /// );
1033 ///
1034 /// // A timestamp *not* in DST in New York.
1035 /// let ts = Timestamp::from_second(1_704_941_204)?;
1036 /// let info = tz.to_offset_info(ts);
1037 /// assert_eq!(info.offset(), tz::offset(-5));
1038 /// assert_eq!(info.dst(), Dst::No);
1039 /// assert_eq!(info.abbreviation(), "EST");
1040 /// assert_eq!(
1041 /// info.offset().to_datetime(ts).to_string(),
1042 /// "2024-01-10T21:46:44",
1043 /// );
1044 ///
1045 /// # Ok::<(), Box<dyn std::error::Error>>(())
1046 /// ```
1047 #[inline]
1048 pub fn to_offset_info<'t>(
1049 &'t self,
1050 timestamp: Timestamp,
1051 ) -> TimeZoneOffsetInfo<'t> {
1052 static UTC: jcore::tz::Abbreviation =
1053 jcore::tz::Abbreviation::array("UTC");
1054 repr::each! {
1055 &self.repr,
1056 UTC => TimeZoneOffsetInfo {
1057 offset: Offset::UTC,
1058 dst: Dst::No,
1059 abbreviation: UTC.clone(),
1060 vestigial_lifetime: core::marker::PhantomData,
1061 },
1062 UNKNOWN => TimeZoneOffsetInfo {
1063 offset: Offset::UTC,
1064 dst: Dst::No,
1065 // It'd be kinda nice if this were just `ERR` to
1066 // indicate an error, but I can't find any precedent
1067 // for that. And CLDR says `Etc/Unknown` should behave
1068 // like UTC, so... I guess we use UTC here.
1069 abbreviation: UTC.clone(),
1070 vestigial_lifetime: core::marker::PhantomData,
1071 },
1072 FIXED(offset) => {
1073 let abbreviation =
1074 offset.to_abbreviation();
1075 TimeZoneOffsetInfo {
1076 offset,
1077 dst: Dst::No,
1078 abbreviation,
1079 vestigial_lifetime: core::marker::PhantomData,
1080 }
1081 },
1082 STATIC_TZIF(tzif) => TimeZoneOffsetInfo::from_jcore(
1083 tzif.tz().to_offset_info(timestamp.to_jcore()),
1084 ),
1085 ARC_TZIF(tzif) => TimeZoneOffsetInfo::from_jcore(
1086 tzif.tz().to_offset_info(timestamp.to_jcore()),
1087 ),
1088 ARC_POSIX(posix) => TimeZoneOffsetInfo::from_jcore(
1089 posix.to_offset_info(timestamp.to_jcore()),
1090 ),
1091 }
1092 }
1093
1094 /// If this time zone is a fixed offset, then this returns the offset.
1095 /// If this time zone is not a fixed offset, then an error is returned.
1096 ///
1097 /// If you just need an offset for a given timestamp, then you can use
1098 /// [`TimeZone::to_offset`]. Or, if you need an offset for a civil
1099 /// datetime, then you can use [`TimeZone::to_ambiguous_timestamp`] or
1100 /// [`TimeZone::to_ambiguous_zoned_datetime`], although the result may be
1101 /// ambiguous.
1102 ///
1103 /// Generally, this routine is useful when you need to know whether the
1104 /// time zone is fixed, and you want to get the offset without having to
1105 /// specify a timestamp. This is sometimes required for interoperating with
1106 /// other datetime systems that need to distinguish between time zones that
1107 /// are fixed and time zones that are based on rules such as those found in
1108 /// the IANA time zone database.
1109 ///
1110 /// # Example
1111 ///
1112 /// ```
1113 /// use jiff::tz::{Offset, TimeZone};
1114 ///
1115 /// let tz = TimeZone::get("America/New_York")?;
1116 /// // A named time zone is not a fixed offset
1117 /// // and so cannot be converted to an offset
1118 /// // without a timestamp or civil datetime.
1119 /// assert_eq!(
1120 /// tz.to_fixed_offset().unwrap_err().to_string(),
1121 /// "cannot convert non-fixed IANA time zone \
1122 /// to offset without a timestamp or civil datetime",
1123 /// );
1124 ///
1125 /// let tz = TimeZone::UTC;
1126 /// // UTC is a fixed offset and so can be converted
1127 /// // without a timestamp.
1128 /// assert_eq!(tz.to_fixed_offset()?, Offset::UTC);
1129 ///
1130 /// // And of course, creating a time zone from a
1131 /// // fixed offset results in a fixed offset time
1132 /// // zone too:
1133 /// let tz = TimeZone::fixed(jiff::tz::offset(-10));
1134 /// assert_eq!(tz.to_fixed_offset()?, jiff::tz::offset(-10));
1135 ///
1136 /// # Ok::<(), Box<dyn std::error::Error>>(())
1137 /// ```
1138 #[inline]
1139 pub fn to_fixed_offset(&self) -> Result<Offset, Error> {
1140 let mkerr = || {
1141 Error::from(E::ConvertNonFixed { kind: self.kind_description() })
1142 };
1143 repr::each! {
1144 &self.repr,
1145 UTC => Ok(Offset::UTC),
1146 UNKNOWN => Ok(Offset::UTC),
1147 FIXED(offset) => Ok(offset),
1148 STATIC_TZIF(_tzif) => Err(mkerr()),
1149 ARC_TZIF(_tzif) => Err(mkerr()),
1150 ARC_POSIX(_posix) => Err(mkerr()),
1151 }
1152 }
1153
1154 /// Converts a civil datetime to a [`ZonedDateTime`] in this time zone.
1155 ///
1156 /// The given civil datetime may be ambiguous in this time zone. A civil
1157 /// datetime is ambiguous when either of the following occurs:
1158 ///
1159 /// * When the civil datetime falls into a "gap." That is, when there is a
1160 /// jump forward in time where a span of time does not appear on the clocks
1161 /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1162 /// into daylight saving time.
1163 /// * When the civil datetime falls into a "fold." That is, when there is
1164 /// a jump backward in time where a span of time is _repeated_ on the
1165 /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1166 /// backward out of daylight saving time.
1167 ///
1168 /// This routine automatically resolves both of the above ambiguities via
1169 /// the
1170 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1171 /// strategy. That in, the case of a gap, the time after the gap is used.
1172 /// In the case of a fold, the first repetition of the clock time is used.
1173 ///
1174 /// # Example
1175 ///
1176 /// This example shows how disambiguation works:
1177 ///
1178 /// ```
1179 /// use jiff::{civil::date, tz::TimeZone};
1180 ///
1181 /// let tz = TimeZone::get("America/New_York")?;
1182 ///
1183 /// // This demonstrates disambiguation behavior for a gap.
1184 /// let zdt = tz.to_zoned_datetime(date(2024, 3, 10).at(2, 30, 0, 0))?;
1185 /// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
1186 /// // This demonstrates disambiguation behavior for a fold.
1187 /// // Notice the offset: the -04 corresponds to the time while
1188 /// // still in DST. The second repetition of the 1 o'clock hour
1189 /// // occurs outside of DST, in "standard" time, with the offset -5.
1190 /// let zdt = tz.to_zoned_datetime(date(2024, 11, 3).at(1, 30, 0, 0))?;
1191 /// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
1192 ///
1193 /// # Ok::<(), Box<dyn std::error::Error>>(())
1194 /// ```
1195 #[inline]
1196 pub fn to_zoned_datetime(
1197 &self,
1198 dt: DateTime,
1199 ) -> Result<ZonedDateTime, Error> {
1200 self.to_ambiguous_zoned_datetime(dt).compatible()
1201 }
1202
1203 /// Converts a civil datetime to a possibly ambiguous zoned datetime in
1204 /// this time zone.
1205 ///
1206 /// The given civil datetime may be ambiguous in this time zone. A civil
1207 /// datetime is ambiguous when either of the following occurs:
1208 ///
1209 /// * When the civil datetime falls into a "gap." That is, when there is a
1210 /// jump forward in time where a span of time does not appear on the clocks
1211 /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1212 /// into daylight saving time.
1213 /// * When the civil datetime falls into a "fold." That is, when there is
1214 /// a jump backward in time where a span of time is _repeated_ on the
1215 /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1216 /// backward out of daylight saving time.
1217 ///
1218 /// Unlike [`TimeZone::to_zoned_datetime`], this method does not do any
1219 /// automatic disambiguation. Instead, callers are expected to use the
1220 /// methods on [`AmbiguousZonedDateTime`] to resolve any ambiguity, if it
1221 /// occurs.
1222 ///
1223 /// # Example
1224 ///
1225 /// This example shows how to return an error when the civil datetime given
1226 /// is ambiguous:
1227 ///
1228 /// ```
1229 /// use jiff::{civil::date, tz::TimeZone};
1230 ///
1231 /// let tz = TimeZone::get("America/New_York")?;
1232 ///
1233 /// // This is not ambiguous:
1234 /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1235 /// assert_eq!(
1236 /// tz.to_ambiguous_zoned_datetime(dt).unambiguous()?.to_string(),
1237 /// "2024-03-10T01:00:00-05:00[America/New_York]",
1238 /// );
1239 /// // But this is a gap, and thus ambiguous! So an error is returned.
1240 /// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
1241 /// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
1242 /// // And so is this, because it's a fold.
1243 /// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
1244 /// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
1245 ///
1246 /// # Ok::<(), Box<dyn std::error::Error>>(())
1247 /// ```
1248 #[inline]
1249 pub fn to_ambiguous_zoned_datetime(
1250 &self,
1251 dt: DateTime,
1252 ) -> AmbiguousZonedDateTime {
1253 self.clone().into_ambiguous_zoned_datetime(dt)
1254 }
1255
1256 /// Converts a civil datetime to a possibly ambiguous zoned datetime in
1257 /// this time zone, and does so by assuming ownership of this `TimeZone`.
1258 ///
1259 /// This is identical to [`TimeZone::to_ambiguous_zoned_datetime`], but it
1260 /// avoids a `TimeZone::clone()` call. (Which are cheap, but not completely
1261 /// free.)
1262 ///
1263 /// # Example
1264 ///
1265 /// This example shows how to create a `ZonedDateTime` value from a
1266 /// `TimeZone` and a `DateTime` without cloning the `TimeZone`:
1267 ///
1268 /// ```
1269 /// use jiff::{civil::date, tz::TimeZone};
1270 ///
1271 /// let tz = TimeZone::get("America/New_York")?;
1272 /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1273 /// assert_eq!(
1274 /// tz.into_ambiguous_zoned_datetime(dt).unambiguous()?.to_string(),
1275 /// "2024-03-10T01:00:00-05:00[America/New_York]",
1276 /// );
1277 ///
1278 /// # Ok::<(), Box<dyn std::error::Error>>(())
1279 /// ```
1280 #[inline]
1281 pub fn into_ambiguous_zoned_datetime(
1282 self,
1283 dt: DateTime,
1284 ) -> AmbiguousZonedDateTime {
1285 self.to_ambiguous_timestamp(dt).into_ambiguous_zoned_datetime(self)
1286 }
1287
1288 /// Converts a civil datetime to a [`Timestamp`] in this time zone.
1289 ///
1290 /// The given civil datetime may be ambiguous in this time zone. A civil
1291 /// datetime is ambiguous when either of the following occurs:
1292 ///
1293 /// * When the civil datetime falls into a "gap." That is, when there is a
1294 /// jump forward in time where a span of time does not appear on the clocks
1295 /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1296 /// into daylight saving time.
1297 /// * When the civil datetime falls into a "fold." That is, when there is
1298 /// a jump backward in time where a span of time is _repeated_ on the
1299 /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1300 /// backward out of daylight saving time.
1301 ///
1302 /// This routine automatically resolves both of the above ambiguities via
1303 /// the
1304 /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1305 /// strategy. That in, the case of a gap, the time after the gap is used.
1306 /// In the case of a fold, the first repetition of the clock time is used.
1307 ///
1308 /// This routine is identical to [`TimeZone::to_zoned_datetime`], except
1309 /// it returns a `Timestamp` instead of a zoned datetime. The benefit of
1310 /// this method is that it never requires cloning or consuming ownership of
1311 /// a `TimeZone`, and it doesn't require construction of `ZonedDateTime`
1312 /// which has a small but non-zero cost. (This is partially because a
1313 /// `ZonedDateTime` value contains a `TimeZone`, but of course, a
1314 /// `Timestamp` does not.)
1315 ///
1316 /// # Example
1317 ///
1318 /// This example shows how disambiguation works:
1319 ///
1320 /// ```
1321 /// use jiff::{civil::date, tz::TimeZone};
1322 ///
1323 /// let tz = TimeZone::get("America/New_York")?;
1324 ///
1325 /// // This demonstrates disambiguation behavior for a gap.
1326 /// let ts = tz.to_timestamp(date(2024, 3, 10).at(2, 30, 0, 0))?;
1327 /// assert_eq!(ts.to_string(), "2024-03-10T07:30:00Z");
1328 /// // This demonstrates disambiguation behavior for a fold.
1329 /// // Notice the offset: the -04 corresponds to the time while
1330 /// // still in DST. The second repetition of the 1 o'clock hour
1331 /// // occurs outside of DST, in "standard" time, with the offset -5.
1332 /// let ts = tz.to_timestamp(date(2024, 11, 3).at(1, 30, 0, 0))?;
1333 /// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
1334 ///
1335 /// # Ok::<(), Box<dyn std::error::Error>>(())
1336 /// ```
1337 #[inline]
1338 pub fn to_timestamp(&self, dt: DateTime) -> Result<Timestamp, Error> {
1339 self.to_ambiguous_timestamp(dt).compatible()
1340 }
1341
1342 /// Converts a civil datetime to a possibly ambiguous timestamp in
1343 /// this time zone.
1344 ///
1345 /// The given civil datetime may be ambiguous in this time zone. A civil
1346 /// datetime is ambiguous when either of the following occurs:
1347 ///
1348 /// * When the civil datetime falls into a "gap." That is, when there is a
1349 /// jump forward in time where a span of time does not appear on the clocks
1350 /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1351 /// into daylight saving time.
1352 /// * When the civil datetime falls into a "fold." That is, when there is
1353 /// a jump backward in time where a span of time is _repeated_ on the
1354 /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1355 /// backward out of daylight saving time.
1356 ///
1357 /// Unlike [`TimeZone::to_timestamp`], this method does not do any
1358 /// automatic disambiguation. Instead, callers are expected to use the
1359 /// methods on [`AmbiguousTimestamp`] to resolve any ambiguity, if it
1360 /// occurs.
1361 ///
1362 /// This routine is identical to
1363 /// [`TimeZone::to_ambiguous_zoned_datetime`], except it returns an
1364 /// `AmbiguousTimestamp` instead of a `AmbiguousZonedDateTime`. The benefit
1365 /// of this method is that it never requires cloning or consuming ownership
1366 /// of a `TimeZone`, and it doesn't require construction of `ZonedDateTime`
1367 /// which has a small but non-zero cost. (This is partially because a
1368 /// `ZonedDateTime` value contains a `TimeZone`, but of course, a
1369 /// `Timestamp` does not.)
1370 ///
1371 /// # Example
1372 ///
1373 /// This example shows how to return an error when the civil datetime given
1374 /// is ambiguous:
1375 ///
1376 /// ```
1377 /// use jiff::{civil::date, tz::TimeZone};
1378 ///
1379 /// let tz = TimeZone::get("America/New_York")?;
1380 ///
1381 /// // This is not ambiguous:
1382 /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1383 /// assert_eq!(
1384 /// tz.to_ambiguous_timestamp(dt).unambiguous()?.to_string(),
1385 /// "2024-03-10T06:00:00Z",
1386 /// );
1387 /// // But this is a gap, and thus ambiguous! So an error is returned.
1388 /// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
1389 /// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
1390 /// // And so is this, because it's a fold.
1391 /// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
1392 /// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
1393 ///
1394 /// # Ok::<(), Box<dyn std::error::Error>>(())
1395 /// ```
1396 #[inline]
1397 pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
1398 let ambiguous_kind = repr::each! {
1399 &self.repr,
1400 UTC => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
1401 UNKNOWN => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
1402 FIXED(offset) => AmbiguousOffset::Unambiguous { offset },
1403 STATIC_TZIF(tzif) => AmbiguousOffset::from_jcore(
1404 tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset(),
1405 ),
1406 ARC_TZIF(tzif) => AmbiguousOffset::from_jcore(
1407 tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset()
1408 ),
1409 ARC_POSIX(posix) => AmbiguousOffset::from_jcore(
1410 posix.to_ambiguous_timestamp(dt.to_jcore()).offset(),
1411 ),
1412 };
1413 AmbiguousTimestamp::new(dt, ambiguous_kind)
1414 }
1415
1416 /// Returns an iterator of time zone transitions preceding the given
1417 /// timestamp. The iterator returned yields [`TimeZoneTransition`]
1418 /// elements.
1419 ///
1420 /// The order of the iterator returned moves backward through time. If
1421 /// there is a previous transition, then the timestamp of that transition
1422 /// is guaranteed to be strictly less than the timestamp given.
1423 ///
1424 /// This is a low level API that you generally shouldn't need. It's
1425 /// useful in cases where you need to know something about the specific
1426 /// instants at which time zone transitions occur. For example, an embedded
1427 /// device might need to be explicitly programmed with daylight saving
1428 /// time transitions. APIs like this enable callers to explore those
1429 /// transitions.
1430 ///
1431 /// A time zone transition refers to a specific point in time when the
1432 /// offset from UTC for a particular geographical region changes. This
1433 /// is usually a result of daylight saving time, but it can also occur
1434 /// when a geographic region changes its permanent offset from UTC.
1435 ///
1436 /// The iterator returned is not guaranteed to yield any elements. For
1437 /// example, this occurs with a fixed offset time zone. Logically, it
1438 /// would also be possible for the iterator to be infinite, except that
1439 /// eventually the timestamp would overflow Jiff's minimum timestamp
1440 /// value, at which point, iteration stops.
1441 ///
1442 /// # Example: time since the previous transition
1443 ///
1444 /// This example shows how much time has passed since the previous time
1445 /// zone transition:
1446 ///
1447 /// ```
1448 /// use jiff::{Unit, ZonedDateTime};
1449 ///
1450 /// let now: ZonedDateTime =
1451 /// "2024-12-31 18:25-05[America/New_York]".parse()?;
1452 /// let trans = now.time_zone().preceding(now.timestamp()).next().unwrap();
1453 /// let prev_at =
1454 /// trans.timestamp().to_zoned_datetime(now.time_zone().clone());
1455 /// let span = now.since((Unit::Year, &prev_at))?;
1456 /// assert_eq!(format!("{span:#}"), "1mo 27d 17h 25m");
1457 ///
1458 /// # Ok::<(), Box<dyn std::error::Error>>(())
1459 /// ```
1460 ///
1461 /// # Example: show the 5 previous time zone transitions
1462 ///
1463 /// This shows how to find the 5 preceding time zone transitions (from a
1464 /// particular datetime) for a particular time zone:
1465 ///
1466 /// ```
1467 /// use jiff::{ZonedDateTime, tz::offset};
1468 ///
1469 /// let now: ZonedDateTime =
1470 /// "2024-12-31 18:25-05[America/New_York]".parse()?;
1471 /// let transitions = now
1472 /// .time_zone()
1473 /// .preceding(now.timestamp())
1474 /// .take(5)
1475 /// .map(|t| {
1476 /// (
1477 /// t.timestamp().to_zoned_datetime(now.time_zone().clone()),
1478 /// t.offset(),
1479 /// t.abbreviation().to_string(),
1480 /// )
1481 /// })
1482 /// .collect::<Vec<_>>();
1483 /// assert_eq!(transitions, vec![
1484 /// (
1485 /// "2024-11-03 01:00-05[America/New_York]".parse()?,
1486 /// offset(-5),
1487 /// "EST".to_string(),
1488 /// ),
1489 /// (
1490 /// "2024-03-10 03:00-04[America/New_York]".parse()?,
1491 /// offset(-4),
1492 /// "EDT".to_string(),
1493 /// ),
1494 /// (
1495 /// "2023-11-05 01:00-05[America/New_York]".parse()?,
1496 /// offset(-5),
1497 /// "EST".to_string(),
1498 /// ),
1499 /// (
1500 /// "2023-03-12 03:00-04[America/New_York]".parse()?,
1501 /// offset(-4),
1502 /// "EDT".to_string(),
1503 /// ),
1504 /// (
1505 /// "2022-11-06 01:00-05[America/New_York]".parse()?,
1506 /// offset(-5),
1507 /// "EST".to_string(),
1508 /// ),
1509 /// ]);
1510 ///
1511 /// # Ok::<(), Box<dyn std::error::Error>>(())
1512 /// ```
1513 #[inline]
1514 pub fn preceding<'t>(
1515 &'t self,
1516 timestamp: Timestamp,
1517 ) -> TimeZonePrecedingTransitions<'t> {
1518 TimeZonePrecedingTransitions { tz: self, cur: timestamp }
1519 }
1520
1521 /// Returns an iterator of time zone transitions following the given
1522 /// timestamp. The iterator returned yields [`TimeZoneTransition`]
1523 /// elements.
1524 ///
1525 /// The order of the iterator returned moves forward through time. If
1526 /// there is a following transition, then the timestamp of that transition
1527 /// is guaranteed to be strictly greater than the timestamp given.
1528 ///
1529 /// This is a low level API that you generally shouldn't need. It's
1530 /// useful in cases where you need to know something about the specific
1531 /// instants at which time zone transitions occur. For example, an embedded
1532 /// device might need to be explicitly programmed with daylight saving
1533 /// time transitions. APIs like this enable callers to explore those
1534 /// transitions.
1535 ///
1536 /// A time zone transition refers to a specific point in time when the
1537 /// offset from UTC for a particular geographical region changes. This
1538 /// is usually a result of daylight saving time, but it can also occur
1539 /// when a geographic region changes its permanent offset from UTC.
1540 ///
1541 /// The iterator returned is not guaranteed to yield any elements. For
1542 /// example, this occurs with a fixed offset time zone. Logically, it
1543 /// would also be possible for the iterator to be infinite, except that
1544 /// eventually the timestamp would overflow Jiff's maximum timestamp
1545 /// value, at which point, iteration stops.
1546 ///
1547 /// # Example: time until the next transition
1548 ///
1549 /// This example shows how much time is left until the next time zone
1550 /// transition:
1551 ///
1552 /// ```
1553 /// use jiff::{Unit, ZonedDateTime};
1554 ///
1555 /// let now: ZonedDateTime =
1556 /// "2024-12-31 18:25-05[America/New_York]".parse()?;
1557 /// let trans = now.time_zone().following(now.timestamp()).next().unwrap();
1558 /// let next_at =
1559 /// trans.timestamp().to_zoned_datetime(now.time_zone().clone());
1560 /// let span = now.until((Unit::Year, &next_at))?;
1561 /// assert_eq!(format!("{span:#}"), "2mo 8d 7h 35m");
1562 ///
1563 /// # Ok::<(), Box<dyn std::error::Error>>(())
1564 /// ```
1565 ///
1566 /// # Example: show the 5 next time zone transitions
1567 ///
1568 /// This shows how to find the 5 following time zone transitions (from a
1569 /// particular datetime) for a particular time zone:
1570 ///
1571 /// ```
1572 /// use jiff::{ZonedDateTime, tz::offset};
1573 ///
1574 /// let now: ZonedDateTime =
1575 /// "2024-12-31 18:25-05[America/New_York]".parse()?;
1576 /// let transitions = now
1577 /// .time_zone()
1578 /// .following(now.timestamp())
1579 /// .take(5)
1580 /// .map(|t| {
1581 /// (
1582 /// t.timestamp().to_zoned_datetime(now.time_zone().clone()),
1583 /// t.offset(),
1584 /// t.abbreviation().to_string(),
1585 /// )
1586 /// })
1587 /// .collect::<Vec<_>>();
1588 /// assert_eq!(transitions, vec![
1589 /// (
1590 /// "2025-03-09 03:00-04[America/New_York]".parse()?,
1591 /// offset(-4),
1592 /// "EDT".to_string(),
1593 /// ),
1594 /// (
1595 /// "2025-11-02 01:00-05[America/New_York]".parse()?,
1596 /// offset(-5),
1597 /// "EST".to_string(),
1598 /// ),
1599 /// (
1600 /// "2026-03-08 03:00-04[America/New_York]".parse()?,
1601 /// offset(-4),
1602 /// "EDT".to_string(),
1603 /// ),
1604 /// (
1605 /// "2026-11-01 01:00-05[America/New_York]".parse()?,
1606 /// offset(-5),
1607 /// "EST".to_string(),
1608 /// ),
1609 /// (
1610 /// "2027-03-14 03:00-04[America/New_York]".parse()?,
1611 /// offset(-4),
1612 /// "EDT".to_string(),
1613 /// ),
1614 /// ]);
1615 ///
1616 /// # Ok::<(), Box<dyn std::error::Error>>(())
1617 /// ```
1618 #[inline]
1619 pub fn following<'t>(
1620 &'t self,
1621 timestamp: Timestamp,
1622 ) -> TimeZoneFollowingTransitions<'t> {
1623 TimeZoneFollowingTransitions { tz: self, cur: timestamp }
1624 }
1625
1626 /// Used by the "preceding transitions" iterator.
1627 #[inline]
1628 fn previous_transition<'t>(
1629 &'t self,
1630 timestamp: Timestamp,
1631 ) -> Option<TimeZoneTransition<'t>> {
1632 repr::each! {
1633 &self.repr,
1634 UTC => None,
1635 UNKNOWN => None,
1636 FIXED(_offset) => None,
1637 STATIC_TZIF(tzif) => {
1638 tzif.tz()
1639 .previous_transition(timestamp.to_jcore())
1640 .map(TimeZoneTransition::from_jcore)
1641 },
1642 ARC_TZIF(tzif) => {
1643 tzif.tz()
1644 .previous_transition(timestamp.to_jcore())
1645 .map(TimeZoneTransition::from_jcore)
1646 },
1647 ARC_POSIX(posix) => {
1648 posix.previous_transition(timestamp.to_jcore())
1649 .map(TimeZoneTransition::from_jcore)
1650 },
1651 }
1652 }
1653
1654 /// Used by the "following transitions" iterator.
1655 #[inline]
1656 fn next_transition<'t>(
1657 &'t self,
1658 timestamp: Timestamp,
1659 ) -> Option<TimeZoneTransition<'t>> {
1660 repr::each! {
1661 &self.repr,
1662 UTC => None,
1663 UNKNOWN => None,
1664 FIXED(_offset) => None,
1665 STATIC_TZIF(tzif) => {
1666 tzif.tz()
1667 .next_transition(timestamp.to_jcore())
1668 .map(TimeZoneTransition::from_jcore)
1669 },
1670 ARC_TZIF(tzif) => {
1671 tzif.tz()
1672 .next_transition(timestamp.to_jcore())
1673 .map(TimeZoneTransition::from_jcore)
1674 },
1675 ARC_POSIX(posix) => {
1676 posix.next_transition(timestamp.to_jcore())
1677 .map(TimeZoneTransition::from_jcore)
1678 },
1679 }
1680 }
1681
1682 /// Returns a short description about the kind of this time zone.
1683 ///
1684 /// This is useful in error messages.
1685 fn kind_description(&self) -> &'static str {
1686 repr::each! {
1687 &self.repr,
1688 UTC => "UTC",
1689 UNKNOWN => "Etc/Unknown",
1690 FIXED(_offset) => "fixed",
1691 STATIC_TZIF(_tzif) => "IANA",
1692 ARC_TZIF(_tzif) => "IANA",
1693 ARC_POSIX(_posix) => "POSIX",
1694 }
1695 }
1696
1697 /// Returns the heap memory usage, in bytes, of this timezone.
1698 ///
1699 /// This does **not** include the stack size used up by this timezone.
1700 /// To compute that, use `std::mem::size_of::<TimeZone>()`.
1701 pub fn memory_usage(&self) -> usize {
1702 repr::each! {
1703 &self.repr,
1704 UTC => 0,
1705 UNKNOWN => 0,
1706 FIXED(_offset) => 0,
1707 STATIC_TZIF(_tzif) => 0,
1708 ARC_TZIF(_tzif) => {
1709 core::mem::size_of::<tzif::MaybeNamedTimeZone>() +
1710 (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1711 },
1712 ARC_POSIX(_posix) => {
1713 core::mem::size_of::<posix::TimeZone>() +
1714 (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1715 },
1716 }
1717 }
1718}
1719
1720// Exposed APIs for Jiff's time zone proc macro.
1721//
1722// These are NOT part of Jiff's public API. There are *zero* semver guarantees
1723// for them.
1724#[doc(hidden)]
1725impl TimeZone {
1726 /// Constructs a `TimeZone` from a static TZif time zone from jcore.
1727 pub const fn __internal_from_tzif(
1728 tzif: &'static tzif::MaybeNamedTimeZone,
1729 ) -> TimeZone {
1730 let repr = Repr::static_tzif(tzif);
1731 TimeZone { repr }
1732 }
1733
1734 /// Returns a dumb copy of this `TimeZone`.
1735 ///
1736 /// # Safety
1737 ///
1738 /// Callers must ensure that this time zone is UTC, unknown, a fixed
1739 /// offset or created with `TimeZone::__internal_from_tzif`.
1740 ///
1741 /// Namely, this specifically does not increment the ref count for
1742 /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
1743 /// This means that incorrect usage of this routine can lead to
1744 /// use-after-free.
1745 #[inline]
1746 pub const unsafe fn copy(&self) -> TimeZone {
1747 // SAFETY: Requirements are forwarded to the caller.
1748 unsafe { TimeZone { repr: self.repr.copy() } }
1749 }
1750}
1751
1752impl core::fmt::Debug for TimeZone {
1753 #[inline]
1754 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1755 f.debug_tuple("TimeZone").field(&self.repr).finish()
1756 }
1757}
1758
1759#[cfg(feature = "defmt")]
1760impl defmt::Format for TimeZone {
1761 fn format(&self, f: defmt::Formatter) {
1762 defmt::write!(f, "TimeZone({})", self.repr);
1763 }
1764}
1765
1766#[cfg(feature = "arbitrary")]
1767impl<'a> arbitrary::Arbitrary<'a> for TimeZone {
1768 fn arbitrary(
1769 u: &mut arbitrary::Unstructured<'a>,
1770 ) -> arbitrary::Result<TimeZone> {
1771 #[cfg(feature = "alloc")]
1772 {
1773 if bool::arbitrary(u)? {
1774 let names: alloc::vec::Vec<_> =
1775 crate::tz::db().available().collect();
1776 if let Ok(name) = u.choose(&names) {
1777 if let Ok(tz) = crate::tz::db().get(name.as_str()) {
1778 return Ok(tz);
1779 }
1780 }
1781 }
1782 }
1783 Ok(TimeZone::fixed(Offset::arbitrary(u)?))
1784 }
1785
1786 fn size_hint(depth: usize) -> (usize, Option<usize>) {
1787 arbitrary::size_hint::and(
1788 <bool as arbitrary::Arbitrary>::size_hint(depth),
1789 <Offset as arbitrary::Arbitrary>::size_hint(depth),
1790 )
1791 }
1792}
1793
1794/// A representation a single time zone transition.
1795///
1796/// A time zone transition is an instant in time the marks the beginning of
1797/// a change in the offset from UTC that civil time is computed from in a
1798/// particular time zone. For example, when daylight saving time comes into
1799/// effect (or goes away). Another example is when a geographic region changes
1800/// its permanent offset from UTC.
1801///
1802/// This is a low level type that you generally shouldn't need. It's useful in
1803/// cases where you need to know something about the specific instants at which
1804/// time zone transitions occur. For example, an embedded device might need to
1805/// be explicitly programmed with daylight saving time transitions. APIs like
1806/// this enable callers to explore those transitions.
1807///
1808/// This type is yielded by the iterators
1809/// [`TimeZonePrecedingTransitions`] and
1810/// [`TimeZoneFollowingTransitions`]. The iterators are created by
1811/// [`TimeZone::preceding`] and [`TimeZone::following`], respectively.
1812///
1813/// # Example
1814///
1815/// This shows a somewhat silly example that finds all of the unique civil
1816/// (or "clock" or "local") times at which a time zone transition has occurred
1817/// in a particular time zone:
1818///
1819/// ```
1820/// use jiff::{civil, tz::TimeZone};
1821/// use std::collections::BTreeSet;
1822///
1823/// let tz = TimeZone::get("America/New_York")?;
1824/// let now = civil::date(2024, 12, 31)
1825/// .at(18, 25, 0, 0)
1826/// .to_zoned_datetime(tz.clone())?;
1827/// let mut set = BTreeSet::new();
1828/// for trans in tz.preceding(now.timestamp()) {
1829/// let time = tz.to_datetime(trans.timestamp()).time();
1830/// set.insert(time);
1831/// }
1832/// assert_eq!(Vec::from_iter(set), vec![
1833/// civil::time(1, 0, 0, 0), // typical transition out of DST
1834/// civil::time(3, 0, 0, 0), // typical transition into DST
1835/// civil::time(12, 0, 0, 0), // from when IANA starts keeping track
1836/// civil::time(19, 0, 0, 0), // from World War 2
1837/// ]);
1838///
1839/// # Ok::<(), Box<dyn std::error::Error>>(())
1840/// ```
1841#[derive(Clone, Debug)]
1842pub struct TimeZoneTransition<'t> {
1843 // We don't currently do anything smart to make iterating over
1844 // transitions faster. We could if we pushed the iterator impl down into
1845 // the respective modules (`posix` and `tzif`), but it's not clear such
1846 // optimization is really worth it. However, this API should permit that
1847 // kind of optimization in the future.
1848 pub(crate) timestamp: Timestamp,
1849 pub(crate) offset: Offset,
1850 pub(crate) abbreviation: jcore::tz::Abbreviation,
1851 pub(crate) dst: Dst,
1852 pub(crate) vestigial_lifetime: core::marker::PhantomData<&'t ()>,
1853}
1854
1855impl<'t> TimeZoneTransition<'t> {
1856 /// Returns the timestamp at which this transition began.
1857 ///
1858 /// # Example
1859 ///
1860 /// ```
1861 /// use jiff::{civil, tz::TimeZone};
1862 ///
1863 /// let tz = TimeZone::get("America/New_York")?;
1864 /// // Look for the first time zone transition in `America/New_York`
1865 /// // following 2023-03-09 00:00:00.
1866 /// let start = civil::date(2024, 3, 9)
1867 /// .to_zoned_datetime(tz.clone())?
1868 /// .timestamp();
1869 /// let next = tz.following(start).next().unwrap();
1870 /// assert_eq!(
1871 /// next.timestamp().to_zoned_datetime(tz.clone()).to_string(),
1872 /// "2024-03-10T03:00:00-04:00[America/New_York]",
1873 /// );
1874 ///
1875 /// # Ok::<(), Box<dyn std::error::Error>>(())
1876 /// ```
1877 #[inline]
1878 pub fn timestamp(&self) -> Timestamp {
1879 self.timestamp
1880 }
1881
1882 /// Returns the offset corresponding to this time zone transition. All
1883 /// instants at and following this transition's timestamp (and before the
1884 /// next transition's timestamp) need to apply this offset from UTC to get
1885 /// the civil or "local" time in the corresponding time zone.
1886 ///
1887 /// # Example
1888 ///
1889 /// ```
1890 /// use jiff::{civil, tz::{TimeZone, offset}};
1891 ///
1892 /// let tz = TimeZone::get("America/New_York")?;
1893 /// // Get the offset of the next transition after
1894 /// // 2023-03-09 00:00:00.
1895 /// let start = civil::date(2024, 3, 9)
1896 /// .to_zoned_datetime(tz.clone())?
1897 /// .timestamp();
1898 /// let next = tz.following(start).next().unwrap();
1899 /// assert_eq!(next.offset(), offset(-4));
1900 /// // Or go backwards to find the previous transition.
1901 /// let prev = tz.preceding(start).next().unwrap();
1902 /// assert_eq!(prev.offset(), offset(-5));
1903 ///
1904 /// # Ok::<(), Box<dyn std::error::Error>>(())
1905 /// ```
1906 #[inline]
1907 pub fn offset(&self) -> Offset {
1908 self.offset
1909 }
1910
1911 /// Returns the time zone abbreviation corresponding to this time
1912 /// zone transition. All instants at and following this transition's
1913 /// timestamp (and before the next transition's timestamp) may use this
1914 /// abbreviation when creating a human readable string. For example,
1915 /// this is the abbreviation used with the `%Z` specifier with Jiff's
1916 /// [`fmt::strtime`](crate::fmt::strtime) module.
1917 ///
1918 /// Note that abbreviations can to be ambiguous. For example, the
1919 /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
1920 /// `America/Chicago` and `America/Havana`.
1921 ///
1922 /// The lifetime of the string returned is tied to this
1923 /// `TimeZoneTransition`, which may be shorter than `'t` (the lifetime of
1924 /// the time zone this transition was created from).
1925 ///
1926 /// # Example
1927 ///
1928 /// ```
1929 /// use jiff::{civil, tz::TimeZone};
1930 ///
1931 /// let tz = TimeZone::get("America/New_York")?;
1932 /// // Get the abbreviation of the next transition after
1933 /// // 2023-03-09 00:00:00.
1934 /// let start = civil::date(2024, 3, 9)
1935 /// .to_zoned_datetime(tz.clone())?
1936 /// .timestamp();
1937 /// let next = tz.following(start).next().unwrap();
1938 /// assert_eq!(next.abbreviation(), "EDT");
1939 /// // Or go backwards to find the previous transition.
1940 /// let prev = tz.preceding(start).next().unwrap();
1941 /// assert_eq!(prev.abbreviation(), "EST");
1942 ///
1943 /// # Ok::<(), Box<dyn std::error::Error>>(())
1944 /// ```
1945 #[inline]
1946 pub fn abbreviation<'a>(&'a self) -> &'a str {
1947 self.abbreviation.as_str()
1948 }
1949
1950 /// Returns whether daylight saving time is enabled for this time zone
1951 /// transition.
1952 ///
1953 /// Callers should generally treat this as informational only. In
1954 /// particular, not all time zone transitions are related to daylight
1955 /// saving time. For example, some transitions are a result of a region
1956 /// permanently changing their offset from UTC.
1957 ///
1958 /// # Example
1959 ///
1960 /// ```
1961 /// use jiff::{civil, tz::{Dst, TimeZone}};
1962 ///
1963 /// let tz = TimeZone::get("America/New_York")?;
1964 /// // Get the DST status of the next transition after
1965 /// // 2023-03-09 00:00:00.
1966 /// let start = civil::date(2024, 3, 9)
1967 /// .to_zoned_datetime(tz.clone())?
1968 /// .timestamp();
1969 /// let next = tz.following(start).next().unwrap();
1970 /// assert_eq!(next.dst(), Dst::Yes);
1971 /// // Or go backwards to find the previous transition.
1972 /// let prev = tz.preceding(start).next().unwrap();
1973 /// assert_eq!(prev.dst(), Dst::No);
1974 ///
1975 /// # Ok::<(), Box<dyn std::error::Error>>(())
1976 /// ```
1977 #[inline]
1978 pub fn dst(&self) -> Dst {
1979 self.dst
1980 }
1981
1982 pub(crate) fn from_jcore(
1983 trans: jcore::tz::Transition,
1984 ) -> TimeZoneTransition<'static> {
1985 let timestamp = Timestamp::from_jcore(trans.timestamp());
1986 let offset = Offset::from_jcore(trans.offset());
1987 let dst = Dst::from_jcore(trans.dst());
1988 let abbreviation = trans.into_offset_info().into_abbreviation();
1989 let vestigial_lifetime = core::marker::PhantomData;
1990 TimeZoneTransition {
1991 timestamp,
1992 offset,
1993 dst,
1994 abbreviation,
1995 vestigial_lifetime,
1996 }
1997 }
1998}
1999
2000/// An offset along with DST status and a time zone abbreviation.
2001///
2002/// This information can be computed from a [`TimeZone`] given a [`Timestamp`]
2003/// via [`TimeZone::to_offset_info`].
2004///
2005/// Generally, the extra information associated with the offset is not commonly
2006/// needed. And indeed, inspecting the daylight saving time status of a
2007/// particular instant in a time zone _usually_ leads to bugs. For example, not
2008/// all time zone transitions are the result of daylight saving time. Some are
2009/// the result of permanent changes to the standard UTC offset of a region.
2010///
2011/// This information is available via an API distinct from
2012/// [`TimeZone::to_offset`] because it is not commonly needed and because it
2013/// can sometimes be more expensive to compute.
2014///
2015/// The main use case for daylight saving time status or time zone
2016/// abbreviations is for formatting datetimes in an end user's locale. If you
2017/// want this, consider using the [`icu`] crate via [`jiff-icu`].
2018///
2019/// The lifetime parameter `'t` corresponds to the lifetime of the `TimeZone`
2020/// that this info was extracted from.
2021///
2022/// # Example
2023///
2024/// ```
2025/// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
2026///
2027/// let tz = TimeZone::get("America/New_York")?;
2028///
2029/// // A timestamp in DST in New York.
2030/// let ts = Timestamp::from_second(1_720_493_204)?;
2031/// let info = tz.to_offset_info(ts);
2032/// assert_eq!(info.offset(), tz::offset(-4));
2033/// assert_eq!(info.dst(), Dst::Yes);
2034/// assert_eq!(info.abbreviation(), "EDT");
2035/// assert_eq!(
2036/// info.offset().to_datetime(ts).to_string(),
2037/// "2024-07-08T22:46:44",
2038/// );
2039///
2040/// // A timestamp *not* in DST in New York.
2041/// let ts = Timestamp::from_second(1_704_941_204)?;
2042/// let info = tz.to_offset_info(ts);
2043/// assert_eq!(info.offset(), tz::offset(-5));
2044/// assert_eq!(info.dst(), Dst::No);
2045/// assert_eq!(info.abbreviation(), "EST");
2046/// assert_eq!(
2047/// info.offset().to_datetime(ts).to_string(),
2048/// "2024-01-10T21:46:44",
2049/// );
2050///
2051/// # Ok::<(), Box<dyn std::error::Error>>(())
2052/// ```
2053///
2054/// [`icu`]: https://docs.rs/icu
2055/// [`jiff-icu`]: https://docs.rs/jiff-icu
2056#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2057pub struct TimeZoneOffsetInfo<'t> {
2058 pub(crate) offset: Offset,
2059 pub(crate) dst: Dst,
2060 pub(crate) abbreviation: jcore::tz::Abbreviation,
2061 pub(crate) vestigial_lifetime: core::marker::PhantomData<&'t ()>,
2062}
2063
2064impl<'t> TimeZoneOffsetInfo<'t> {
2065 /// Returns the offset.
2066 ///
2067 /// The offset is duration, from UTC, that should be used to offset the
2068 /// civil time in a particular location.
2069 ///
2070 /// # Example
2071 ///
2072 /// ```
2073 /// use jiff::{civil, tz::{TimeZone, offset}};
2074 ///
2075 /// let tz = TimeZone::get("America/New_York")?;
2076 /// // Get the offset for 2023-03-10 00:00:00.
2077 /// let start = civil::date(2024, 3, 10)
2078 /// .to_zoned_datetime(tz.clone())?
2079 /// .timestamp();
2080 /// let info = tz.to_offset_info(start);
2081 /// assert_eq!(info.offset(), offset(-5));
2082 /// // Go forward a day and notice the offset changes due to DST!
2083 /// let start = civil::date(2024, 3, 11)
2084 /// .to_zoned_datetime(tz.clone())?
2085 /// .timestamp();
2086 /// let info = tz.to_offset_info(start);
2087 /// assert_eq!(info.offset(), offset(-4));
2088 ///
2089 /// # Ok::<(), Box<dyn std::error::Error>>(())
2090 /// ```
2091 #[inline]
2092 pub fn offset(&self) -> Offset {
2093 self.offset
2094 }
2095
2096 /// Returns the time zone abbreviation corresponding to this offset info.
2097 ///
2098 /// Note that abbreviations can to be ambiguous. For example, the
2099 /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
2100 /// `America/Chicago` and `America/Havana`.
2101 ///
2102 /// The lifetime of the string returned is tied to this
2103 /// `TimeZoneOffsetInfo`, which may be shorter than `'t` (the lifetime of
2104 /// the time zone this transition was created from).
2105 ///
2106 /// # Example
2107 ///
2108 /// ```
2109 /// use jiff::{civil, tz::TimeZone};
2110 ///
2111 /// let tz = TimeZone::get("America/New_York")?;
2112 /// // Get the time zone abbreviation for 2023-03-10 00:00:00.
2113 /// let start = civil::date(2024, 3, 10)
2114 /// .to_zoned_datetime(tz.clone())?
2115 /// .timestamp();
2116 /// let info = tz.to_offset_info(start);
2117 /// assert_eq!(info.abbreviation(), "EST");
2118 /// // Go forward a day and notice the abbreviation changes due to DST!
2119 /// let start = civil::date(2024, 3, 11)
2120 /// .to_zoned_datetime(tz.clone())?
2121 /// .timestamp();
2122 /// let info = tz.to_offset_info(start);
2123 /// assert_eq!(info.abbreviation(), "EDT");
2124 ///
2125 /// # Ok::<(), Box<dyn std::error::Error>>(())
2126 /// ```
2127 #[inline]
2128 pub fn abbreviation(&self) -> &str {
2129 self.abbreviation.as_str()
2130 }
2131
2132 /// Returns whether daylight saving time is enabled for this offset
2133 /// info.
2134 ///
2135 /// Callers should generally treat this as informational only. In
2136 /// particular, not all time zone transitions are related to daylight
2137 /// saving time. For example, some transitions are a result of a region
2138 /// permanently changing their offset from UTC.
2139 ///
2140 /// # Example
2141 ///
2142 /// ```
2143 /// use jiff::{civil, tz::{Dst, TimeZone}};
2144 ///
2145 /// let tz = TimeZone::get("America/New_York")?;
2146 /// // Get the DST status of 2023-03-11 00:00:00.
2147 /// let start = civil::date(2024, 3, 11)
2148 /// .to_zoned_datetime(tz.clone())?
2149 /// .timestamp();
2150 /// let info = tz.to_offset_info(start);
2151 /// assert_eq!(info.dst(), Dst::Yes);
2152 ///
2153 /// # Ok::<(), Box<dyn std::error::Error>>(())
2154 /// ```
2155 #[inline]
2156 pub fn dst(&self) -> Dst {
2157 self.dst
2158 }
2159
2160 pub(crate) fn from_jcore(
2161 info: jcore::tz::OffsetInfo,
2162 ) -> TimeZoneOffsetInfo<'static> {
2163 let offset = Offset::from_jcore(info.offset());
2164 let dst = Dst::from_jcore(info.dst());
2165 let abbreviation = info.into_abbreviation();
2166 let vestigial_lifetime = core::marker::PhantomData;
2167 TimeZoneOffsetInfo { offset, dst, abbreviation, vestigial_lifetime }
2168 }
2169}
2170
2171/// An iterator over time zone transitions going backward in time.
2172///
2173/// This iterator is created by [`TimeZone::preceding`].
2174///
2175/// # Example: show the 5 previous time zone transitions
2176///
2177/// This shows how to find the 5 preceding time zone transitions (from a
2178/// particular datetime) for a particular time zone:
2179///
2180/// ```
2181/// use jiff::{tz::offset, ZonedDateTime};
2182///
2183/// let now: ZonedDateTime = "2024-12-31 18:25-05[America/New_York]".parse()?;
2184/// let transitions = now
2185/// .time_zone()
2186/// .preceding(now.timestamp())
2187/// .take(5)
2188/// .map(|t| (
2189/// t.timestamp().to_zoned_datetime(now.time_zone().clone()),
2190/// t.offset(),
2191/// t.abbreviation().to_string(),
2192/// ))
2193/// .collect::<Vec<_>>();
2194/// assert_eq!(transitions, vec![
2195/// (
2196/// "2024-11-03 01:00-05[America/New_York]".parse()?,
2197/// offset(-5),
2198/// "EST".to_string(),
2199/// ),
2200/// (
2201/// "2024-03-10 03:00-04[America/New_York]".parse()?,
2202/// offset(-4),
2203/// "EDT".to_string(),
2204/// ),
2205/// (
2206/// "2023-11-05 01:00-05[America/New_York]".parse()?,
2207/// offset(-5),
2208/// "EST".to_string(),
2209/// ),
2210/// (
2211/// "2023-03-12 03:00-04[America/New_York]".parse()?,
2212/// offset(-4),
2213/// "EDT".to_string(),
2214/// ),
2215/// (
2216/// "2022-11-06 01:00-05[America/New_York]".parse()?,
2217/// offset(-5),
2218/// "EST".to_string(),
2219/// ),
2220/// ]);
2221///
2222/// # Ok::<(), Box<dyn std::error::Error>>(())
2223/// ```
2224#[derive(Clone, Debug)]
2225pub struct TimeZonePrecedingTransitions<'t> {
2226 tz: &'t TimeZone,
2227 cur: Timestamp,
2228}
2229
2230impl<'t> Iterator for TimeZonePrecedingTransitions<'t> {
2231 type Item = TimeZoneTransition<'t>;
2232
2233 fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
2234 let trans = self.tz.previous_transition(self.cur)?;
2235 self.cur = trans.timestamp();
2236 Some(trans)
2237 }
2238}
2239
2240impl<'t> core::iter::FusedIterator for TimeZonePrecedingTransitions<'t> {}
2241
2242/// An iterator over time zone transitions going forward in time.
2243///
2244/// This iterator is created by [`TimeZone::following`].
2245///
2246/// # Example: show the 5 next time zone transitions
2247///
2248/// This shows how to find the 5 following time zone transitions (from a
2249/// particular datetime) for a particular time zone:
2250///
2251/// ```
2252/// use jiff::{tz::offset, ZonedDateTime};
2253///
2254/// let now: ZonedDateTime = "2024-12-31 18:25-05[America/New_York]".parse()?;
2255/// let transitions = now
2256/// .time_zone()
2257/// .following(now.timestamp())
2258/// .take(5)
2259/// .map(|t| (
2260/// t.timestamp().to_zoned_datetime(now.time_zone().clone()),
2261/// t.offset(),
2262/// t.abbreviation().to_string(),
2263/// ))
2264/// .collect::<Vec<_>>();
2265/// assert_eq!(transitions, vec![
2266/// (
2267/// "2025-03-09 03:00-04[America/New_York]".parse()?,
2268/// offset(-4),
2269/// "EDT".to_string(),
2270/// ),
2271/// (
2272/// "2025-11-02 01:00-05[America/New_York]".parse()?,
2273/// offset(-5),
2274/// "EST".to_string(),
2275/// ),
2276/// (
2277/// "2026-03-08 03:00-04[America/New_York]".parse()?,
2278/// offset(-4),
2279/// "EDT".to_string(),
2280/// ),
2281/// (
2282/// "2026-11-01 01:00-05[America/New_York]".parse()?,
2283/// offset(-5),
2284/// "EST".to_string(),
2285/// ),
2286/// (
2287/// "2027-03-14 03:00-04[America/New_York]".parse()?,
2288/// offset(-4),
2289/// "EDT".to_string(),
2290/// ),
2291/// ]);
2292///
2293/// # Ok::<(), Box<dyn std::error::Error>>(())
2294/// ```
2295#[derive(Clone, Debug)]
2296pub struct TimeZoneFollowingTransitions<'t> {
2297 tz: &'t TimeZone,
2298 cur: Timestamp,
2299}
2300
2301impl<'t> Iterator for TimeZoneFollowingTransitions<'t> {
2302 type Item = TimeZoneTransition<'t>;
2303
2304 fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
2305 let trans = self.tz.next_transition(self.cur)?;
2306 self.cur = trans.timestamp();
2307 Some(trans)
2308 }
2309}
2310
2311impl<'t> core::iter::FusedIterator for TimeZoneFollowingTransitions<'t> {}
2312
2313/// A helper type for converting a `TimeZone` to a succinct human readable
2314/// description.
2315///
2316/// This is principally used in error messages in various places.
2317///
2318/// A previous iteration of this was just an `as_str() -> &str` method on
2319/// `TimeZone`, but that's difficult to do without relying on dynamic memory
2320/// allocation (or chunky arrays).
2321pub(crate) struct DiagnosticName<'a>(&'a TimeZone);
2322
2323impl<'a> core::fmt::Display for DiagnosticName<'a> {
2324 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2325 repr::each! {
2326 &self.0.repr,
2327 UTC => f.write_str("UTC"),
2328 UNKNOWN => f.write_str("Etc/Unknown"),
2329 FIXED(offset) => offset.fmt(f),
2330 STATIC_TZIF(tzif) => f.write_str(
2331 tzif.name().unwrap_or("Local"),
2332 ),
2333 ARC_TZIF(tzif) => f.write_str(
2334 tzif.name().unwrap_or("Local"),
2335 ),
2336 ARC_POSIX(posix) => crate::tz::posix::TimeZoneFormatter(posix).fmt(f),
2337 }
2338 }
2339}
2340
2341/// This module defines the internal representation of a `TimeZone`.
2342///
2343/// This module exists to _encapsulate_ the representation rigorously and
2344/// expose a safe and sound API.
2345mod repr {
2346 use core::{mem::ManuallyDrop, ptr::without_provenance};
2347
2348 use jcore::tz::{posix, tzif};
2349
2350 use crate::util::constant::unwrap;
2351 #[cfg(feature = "alloc")]
2352 use crate::util::sync::Arc;
2353
2354 use super::Offset;
2355
2356 /// A macro for "matching" over the time zone representation variants.
2357 ///
2358 /// This macro is safe to use.
2359 ///
2360 /// Note that the `ARC_TZIF` and `ARC_POSIX` branches are automatically
2361 /// removed when `alloc` isn't enabled. Users of this macro needn't handle
2362 /// the `cfg` themselves.
2363 macro_rules! each {
2364 (
2365 $repr:expr,
2366 UTC => $utc:expr,
2367 UNKNOWN => $unknown:expr,
2368 FIXED($offset:ident) => $fixed:expr,
2369 STATIC_TZIF($static_tzif:ident) => $static_tzif_block:expr,
2370 ARC_TZIF($arc_tzif:ident) => $arc_tzif_block:expr,
2371 ARC_POSIX($arc_posix:ident) => $arc_posix_block:expr,
2372 ) => {{
2373 let repr = $repr;
2374 match repr.tag() {
2375 Repr::UTC => $utc,
2376 Repr::UNKNOWN => $unknown,
2377 Repr::FIXED => {
2378 // SAFETY: We've ensured our pointer tag is correct.
2379 let $offset = unsafe { repr.get_fixed() };
2380 $fixed
2381 }
2382 Repr::STATIC_TZIF => {
2383 // SAFETY: We've ensured our pointer tag is correct.
2384 let $static_tzif = unsafe { repr.get_static_tzif() };
2385 $static_tzif_block
2386 }
2387 #[cfg(feature = "alloc")]
2388 Repr::ARC_TZIF => {
2389 // SAFETY: We've ensured our pointer tag is correct.
2390 let $arc_tzif = unsafe { repr.get_arc_tzif() };
2391 $arc_tzif_block
2392 }
2393 #[cfg(feature = "alloc")]
2394 Repr::ARC_POSIX => {
2395 // SAFETY: We've ensured our pointer tag is correct.
2396 let $arc_posix = unsafe { repr.get_arc_posix() };
2397 $arc_posix_block
2398 }
2399 _ => {
2400 debug_assert!(false, "each: invalid time zone repr tag!");
2401 // SAFETY: The constructors for `Repr` guarantee that the
2402 // tag is always one of the values matched above.
2403 unsafe {
2404 core::hint::unreachable_unchecked();
2405 }
2406 }
2407 }
2408 }};
2409 }
2410 pub(super) use each;
2411
2412 /// The internal representation of a `TimeZone`.
2413 ///
2414 /// It has 6 different possible variants: `UTC`, `Etc/Unknown`, fixed
2415 /// offset, `static` TZif, `Arc` TZif or `Arc` POSIX time zone.
2416 ///
2417 /// This design uses pointer tagging so that:
2418 ///
2419 /// * The size of a `TimeZone` stays no bigger than a single word.
2420 /// * In core-only environments, a `TimeZone` can be created from
2421 /// compile-time TZif data without allocating.
2422 /// * UTC, unknown and fixed offset time zone does not require allocating.
2423 /// * We can still alloc for TZif and POSIX time zones created at runtime.
2424 /// (Allocating for TZif at runtime is the intended common case, and
2425 /// corresponds to reading `/usr/share/zoneinfo` entries.)
2426 ///
2427 /// We achieve this through pointer tagging and careful use of strict
2428 /// provenance. We use the lower 4 bits of a pointer to indicate which
2429 /// variant we have. This is sound because we require all types that we
2430 /// allocate for to have a minimum alignment of 8 bytes.
2431 pub(super) struct Repr {
2432 ptr: *const u8,
2433 }
2434
2435 impl Repr {
2436 const BITS: usize = 0b111;
2437 pub(super) const UTC: usize = 1;
2438 pub(super) const UNKNOWN: usize = 2;
2439 pub(super) const FIXED: usize = 3;
2440 pub(super) const STATIC_TZIF: usize = 0;
2441 pub(super) const ARC_TZIF: usize = 4;
2442 pub(super) const ARC_POSIX: usize = 5;
2443
2444 // The minimum alignment required for any heap allocated time zone
2445 // variants. This is related to the number of tags. We have 6 distinct
2446 // values above, which means we need an alignment of at least 6. Since
2447 // alignment must be a power of 2, the smallest possible alignment
2448 // is 8.
2449 const ALIGN: usize = 8;
2450
2451 /// Creates a representation for a `UTC` time zone.
2452 #[inline]
2453 pub(super) const fn utc() -> Repr {
2454 let ptr = without_provenance(Repr::UTC);
2455 Repr { ptr }
2456 }
2457
2458 /// Creates a representation for a `Etc/Unknown` time zone.
2459 #[inline]
2460 pub(super) const fn unknown() -> Repr {
2461 let ptr = without_provenance(Repr::UNKNOWN);
2462 Repr { ptr }
2463 }
2464
2465 /// Creates a representation for a fixed offset time zone.
2466 #[inline]
2467 pub(super) const fn fixed(offset: Offset) -> Repr {
2468 let seconds = offset.seconds();
2469 // OK because offset is in -93599..=93599.
2470 let shifted = unwrap!(
2471 seconds.checked_shl(4),
2472 "offset small enough for left shift by 4 bits",
2473 );
2474 assert!(usize::MAX >= 4_294_967_295);
2475 // usize cast is okay because Jiff requires 32-bit.
2476 let ptr = without_provenance((shifted as usize) | Repr::FIXED);
2477 Repr { ptr }
2478 }
2479
2480 /// Creates a representation for a created-at-compile-time TZif time
2481 /// zone.
2482 ///
2483 /// This can only be correctly called by the `jiff-static` proc macro.
2484 #[inline]
2485 pub(super) const fn static_tzif(
2486 tzif: &'static tzif::MaybeNamedTimeZone,
2487 ) -> Repr {
2488 assert!(
2489 core::mem::align_of::<tzif::MaybeNamedTimeZone>()
2490 >= Repr::ALIGN
2491 );
2492 let tzif = (tzif as *const tzif::MaybeNamedTimeZone).cast::<u8>();
2493 // We very specifically do no materialize the pointer address here
2494 // because 1) it's UB and 2) the compiler generally prevents. This
2495 // is because in a const context, the specific pointer address
2496 // cannot be relied upon. Yet, we still want to do pointer tagging.
2497 //
2498 // Thankfully, this is the only variant that is a pointer that
2499 // we want to create in a const context. So we just make this
2500 // variant's tag `0`, and thus, no explicit pointer tagging is
2501 // required. (Because we ensure the alignment is at least 4, and
2502 // thus the least significant 3 bits are 0.)
2503 //
2504 // If this ends up not working out or if we need to support
2505 // another `static` variant, then we could perhaps to pointer
2506 // tagging with pointer arithmetic (like what the `tagged-pointer`
2507 // crate does). I haven't tried it though and I'm unclear if it
2508 // work.
2509 Repr { ptr: tzif }
2510 }
2511
2512 /// Creates a representation for a TZif time zone.
2513 #[cfg(feature = "alloc")]
2514 #[inline]
2515 pub(super) fn arc_tzif(tzif: Arc<tzif::MaybeNamedTimeZone>) -> Repr {
2516 assert!(
2517 core::mem::align_of::<tzif::MaybeNamedTimeZone>()
2518 >= Repr::ALIGN
2519 );
2520 let tzif = Arc::into_raw(tzif).cast::<u8>();
2521 assert!(tzif.addr() % 4 == 0);
2522 let ptr = tzif.map_addr(|addr| addr | Repr::ARC_TZIF);
2523 Repr { ptr }
2524 }
2525
2526 /// Creates a representation for a POSIX time zone.
2527 #[cfg(feature = "alloc")]
2528 #[inline]
2529 pub(super) fn arc_posix(posix_tz: Arc<posix::TimeZone>) -> Repr {
2530 assert!(core::mem::align_of::<posix::TimeZone>() >= Repr::ALIGN);
2531 let posix_tz = Arc::into_raw(posix_tz).cast::<u8>();
2532 assert!(posix_tz.addr() % 4 == 0);
2533 let ptr = posix_tz.map_addr(|addr| addr | Repr::ARC_POSIX);
2534 Repr { ptr }
2535 }
2536
2537 /// Gets the offset representation.
2538 ///
2539 /// # Safety
2540 ///
2541 /// Callers must ensure that the pointer tag is `FIXED`.
2542 #[inline]
2543 pub(super) unsafe fn get_fixed(&self) -> Offset {
2544 #[allow(unstable_name_collisions)]
2545 let addr = self.ptr.addr();
2546 // NOTE: Because of sign extension, we need to cast to `i32`
2547 // before shifting.
2548 Offset::from_seconds_unchecked((addr as i32) >> 4)
2549 }
2550
2551 /// Returns true if and only if this representation corresponds to the
2552 /// `Etc/Unknown` time zone.
2553 #[inline]
2554 pub(super) fn is_unknown(&self) -> bool {
2555 self.tag() == Repr::UNKNOWN
2556 }
2557
2558 /// Gets the static TZif representation.
2559 ///
2560 /// # Safety
2561 ///
2562 /// Callers must ensure that the pointer tag is `STATIC_TZIF`.
2563 #[inline]
2564 pub(super) unsafe fn get_static_tzif(
2565 &self,
2566 ) -> &'static tzif::MaybeNamedTimeZone {
2567 #[allow(unstable_name_collisions)]
2568 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2569 // SAFETY: Getting a `STATIC_TZIF` tag is only possible when
2570 // `self.ptr` was constructed from a valid and aligned (to at least
2571 // 4 bytes) `&TzifStatic` borrow. Which must be guaranteed by the
2572 // caller. We've also removed the tag bits above, so we must now
2573 // have the original pointer.
2574 unsafe { &*ptr.cast::<tzif::MaybeNamedTimeZone>() }
2575 }
2576
2577 /// Gets the `Arc` TZif representation.
2578 ///
2579 /// # Safety
2580 ///
2581 /// Callers must ensure that the pointer tag is `ARC_TZIF`.
2582 #[cfg(feature = "alloc")]
2583 #[inline]
2584 pub(super) unsafe fn get_arc_tzif<'a>(
2585 &'a self,
2586 ) -> &'a tzif::MaybeNamedTimeZone {
2587 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2588 // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2589 // `self.ptr` was constructed from a valid and aligned (to at least
2590 // 4 bytes) `Arc<tzif::MaybeNamedTimeZone>`. We've removed the tag
2591 // bits above, so we must now have the original pointer.
2592 let arc = ManuallyDrop::new(unsafe {
2593 Arc::from_raw(ptr.cast::<tzif::MaybeNamedTimeZone>())
2594 });
2595 // SAFETY: The lifetime of the pointer returned is always
2596 // valid as long as the strong count on `arc` is at least
2597 // 1. Since the lifetime is no longer than `Repr` itself,
2598 // and a `Repr` being alive implies there is at least 1
2599 // for the strong `Arc` count, it follows that the lifetime
2600 // returned here is correct.
2601 unsafe { &*Arc::as_ptr(&arc) }
2602 }
2603
2604 /// Gets the `Arc` POSIX time zone representation.
2605 ///
2606 /// # Safety
2607 ///
2608 /// Callers must ensure that the pointer tag is `ARC_POSIX`.
2609 #[cfg(feature = "alloc")]
2610 #[inline]
2611 pub(super) unsafe fn get_arc_posix<'a>(
2612 &'a self,
2613 ) -> &'a posix::TimeZone {
2614 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2615 // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2616 // `self.ptr` was constructed from a valid and aligned (to at least
2617 // 4 bytes) `Arc<jcore::tz::posix::TimeZone>`. We've removed the
2618 // tag bits above, so we must now have the original pointer.
2619 let arc = ManuallyDrop::new(unsafe {
2620 Arc::from_raw(ptr.cast::<posix::TimeZone>())
2621 });
2622 // SAFETY: The lifetime of the pointer returned is always
2623 // valid as long as the strong count on `arc` is at least
2624 // 1. Since the lifetime is no longer than `Repr` itself,
2625 // and a `Repr` being alive implies there is at least 1
2626 // for the strong `Arc` count, it follows that the lifetime
2627 // returned here is correct.
2628 unsafe { &*Arc::as_ptr(&arc) }
2629 }
2630
2631 /// Returns the tag on the representation's pointer.
2632 ///
2633 /// The value is guaranteed to be one of the constant tag values.
2634 #[inline]
2635 pub(super) fn tag(&self) -> usize {
2636 #[allow(unstable_name_collisions)]
2637 {
2638 self.ptr.addr() & Repr::BITS
2639 }
2640 }
2641
2642 /// Returns a dumb copy of this representation.
2643 ///
2644 /// # Safety
2645 ///
2646 /// Callers must ensure that this representation's tag is UTC,
2647 /// UNKNOWN, FIXED or STATIC_TZIF.
2648 ///
2649 /// Namely, this specifically does not increment the ref count for
2650 /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
2651 /// This means that incorrect usage of this routine can lead to
2652 /// use-after-free.
2653 ///
2654 /// NOTE: It would be nice if we could make this `copy` routine safe,
2655 /// or at least panic if it's misused. But to do that, you need to know
2656 /// the time zone variant. And to know the time zone variant, you need
2657 /// to "look" at the tag in the pointer. And looking at the address of
2658 /// a pointer in a `const` context is precarious.
2659 #[inline]
2660 pub(super) const unsafe fn copy(&self) -> Repr {
2661 Repr { ptr: self.ptr }
2662 }
2663 }
2664
2665 // SAFETY: We use automatic reference counting.
2666 unsafe impl Send for Repr {}
2667 // SAFETY: We don't use an interior mutability and otherwise don't permit
2668 // any kind of mutation (other than for an `Arc` managing its ref counts)
2669 // of a `Repr`.
2670 unsafe impl Sync for Repr {}
2671
2672 impl core::fmt::Debug for Repr {
2673 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2674 each! {
2675 self,
2676 UTC => f.write_str("UTC"),
2677 UNKNOWN => f.write_str("Etc/Unknown"),
2678 FIXED(offset) => core::fmt::Debug::fmt(&offset, f),
2679 STATIC_TZIF(tzif) => {
2680 // The full debug output is a bit much, so constrain it.
2681 let field = tzif.name().unwrap_or("Local");
2682 f.debug_tuple("TZif").field(&field).finish()
2683 },
2684 ARC_TZIF(tzif) => {
2685 // The full debug output is a bit much, so constrain it.
2686 let field = tzif.name().unwrap_or("Local");
2687 f.debug_tuple("TZif").field(&field).finish()
2688 },
2689 ARC_POSIX(posix) => {
2690 f.write_str("Posix(")?;
2691 core::fmt::Display::fmt(
2692 &crate::tz::posix::TimeZoneFormatter(posix),
2693 f,
2694 )?;
2695 f.write_str(")")
2696 },
2697 }
2698 }
2699 }
2700
2701 impl Clone for Repr {
2702 #[inline]
2703 fn clone(&self) -> Repr {
2704 // This `match` is written in an exhaustive fashion so that if
2705 // a new tag is added, it should be explicitly considered here.
2706 match self.tag() {
2707 // These are all `Copy` and can just be memcpy'd as-is.
2708 Repr::UTC
2709 | Repr::UNKNOWN
2710 | Repr::FIXED
2711 | Repr::STATIC_TZIF => Repr { ptr: self.ptr },
2712 #[cfg(feature = "alloc")]
2713 Repr::ARC_TZIF => {
2714 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2715 // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2716 // `self.ptr` was constructed from a valid and aligned (to
2717 // at least 4 bytes) `Arc<tzif::MaybeNamedTimeZone>`. We've
2718 // removed the tag bits above, so we must now have the
2719 // original pointer.
2720 unsafe {
2721 Arc::increment_strong_count(
2722 ptr.cast::<tzif::MaybeNamedTimeZone>(),
2723 );
2724 }
2725 Repr { ptr: self.ptr }
2726 }
2727 #[cfg(feature = "alloc")]
2728 Repr::ARC_POSIX => {
2729 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2730 // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2731 // `self.ptr` was constructed from a valid and aligned (to
2732 // at least 4 bytes) `Arc<jcore::tz::posix::TimeZone>`.
2733 // We've removed the tag bits above, so we must now have
2734 // the original pointer.
2735 unsafe {
2736 Arc::increment_strong_count(
2737 ptr.cast::<posix::TimeZone>(),
2738 );
2739 }
2740 Repr { ptr: self.ptr }
2741 }
2742 _ => {
2743 debug_assert!(false, "clone: invalid time zone repr tag!");
2744 // SAFETY: The constructors for `Repr` guarantee that the
2745 // tag is always one of the values matched above.
2746 unsafe {
2747 core::hint::unreachable_unchecked();
2748 }
2749 }
2750 }
2751 }
2752 }
2753
2754 impl Drop for Repr {
2755 #[inline]
2756 fn drop(&mut self) {
2757 // This `match` is written in an exhaustive fashion so that if
2758 // a new tag is added, it should be explicitly considered here.
2759 match self.tag() {
2760 // These are all `Copy` and have no destructor.
2761 Repr::UTC
2762 | Repr::UNKNOWN
2763 | Repr::FIXED
2764 | Repr::STATIC_TZIF => {}
2765 #[cfg(feature = "alloc")]
2766 Repr::ARC_TZIF => {
2767 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2768 // SAFETY: Getting a `ARC_TZIF` tag is only
2769 // possible when `self.ptr` was constructed from
2770 // a valid and aligned (to at least 4 bytes)
2771 // `Arc<tzif::MaybeNamedTimeZone>`. We've removed the tag
2772 // bits above, so we must now have the original
2773 // pointer.
2774 unsafe {
2775 Arc::decrement_strong_count(
2776 ptr.cast::<tzif::MaybeNamedTimeZone>(),
2777 );
2778 }
2779 }
2780 #[cfg(feature = "alloc")]
2781 Repr::ARC_POSIX => {
2782 let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2783 // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2784 // `self.ptr` was constructed from a valid and aligned (to
2785 // at least 4 bytes) `Arc<jcore::tz::posix::TimeZone>`.
2786 // We've removed the tag bits above, so we must now have
2787 // the original pointer.
2788 unsafe {
2789 Arc::decrement_strong_count(
2790 ptr.cast::<posix::TimeZone>(),
2791 );
2792 }
2793 }
2794 _ => {
2795 debug_assert!(false, "drop: invalid time zone repr tag!");
2796 // SAFETY: The constructors for `Repr` guarantee that the
2797 // tag is always one of the values matched above.
2798 unsafe {
2799 core::hint::unreachable_unchecked();
2800 }
2801 }
2802 }
2803 }
2804 }
2805
2806 impl Eq for Repr {}
2807
2808 impl PartialEq for Repr {
2809 fn eq(&self, other: &Repr) -> bool {
2810 fn is_tzif_eq(
2811 tzif1: &tzif::MaybeNamedTimeZone,
2812 tzif2: &tzif::MaybeNamedTimeZone,
2813 ) -> bool {
2814 // We check the underlying TZ itself (which is
2815 // just done via a checksum) to catch cases where
2816 // two different TimeZone values with the same
2817 // name came from different databases. This is
2818 // also important for cases when neither time
2819 // zone has an IANA name, in which case, we just
2820 // rely on the checksum.
2821 if tzif1.tz() != tzif2.tz() {
2822 return false;
2823 }
2824 primary_name_fallback(tzif1) == primary_name_fallback(tzif2)
2825 }
2826
2827 fn primary_name_fallback(
2828 tzif: &tzif::MaybeNamedTimeZone,
2829 ) -> Option<&str> {
2830 super::find_primary_iana_name(tzif.name()?)
2831 .or_else(|| tzif.name())
2832 }
2833
2834 if self.tag() != other.tag() {
2835 return false;
2836 }
2837 each! {
2838 self,
2839 UTC => true,
2840 UNKNOWN => true,
2841 // SAFETY: OK, because we know the tags are equivalent and
2842 // `self` has a `FIXED` tag.
2843 FIXED(offset) => offset == unsafe { other.get_fixed() },
2844 STATIC_TZIF(tzif1) => {
2845 // SAFETY: OK, because we know the tags are equivalent and
2846 // `self` has a `STATIC_TZIF` tag.
2847 let tzif2 = unsafe { other.get_static_tzif() };
2848 is_tzif_eq(tzif1, tzif2)
2849 },
2850 ARC_TZIF(tzif1) => {
2851 // SAFETY: OK, because we know the tags are equivalent and
2852 // `self` has an `ARC_TZIF` tag.
2853 let tzif2 = unsafe { other.get_arc_tzif() };
2854 is_tzif_eq(tzif1, tzif2)
2855 },
2856 // SAFETY: OK, because we know the tags are equivalent and
2857 // `self` has an `ARC_POSIX` tag.
2858 ARC_POSIX(posix) => posix == unsafe { other.get_arc_posix() },
2859 }
2860 }
2861 }
2862
2863 #[cfg(feature = "defmt")]
2864 impl defmt::Format for Repr {
2865 fn format(&self, f: defmt::Formatter) {
2866 each! {
2867 self,
2868 UTC => defmt::write!(f, "UTC"),
2869 UNKNOWN => defmt::write!(f, "Etc/Unknown"),
2870 FIXED(offset) => defmt::write!(f, "{}", offset),
2871 STATIC_TZIF(tzif) => {
2872 // The full debug output is a bit much, so constrain it.
2873 let field = tzif.name().unwrap_or("Local");
2874 defmt::write!(f, "TZif({=str})", field)
2875 },
2876 ARC_TZIF(tzif) => {
2877 // The full debug output is a bit much, so constrain it.
2878 let field = tzif.name().unwrap_or("Local");
2879 defmt::write!(f, "TZif({=str})", field)
2880 },
2881 ARC_POSIX(posix) => {
2882 defmt::write!(
2883 f,
2884 "Posix({})",
2885 crate::tz::posix::TimeZoneFormatter(&posix),
2886 )
2887 },
2888 }
2889 }
2890 }
2891}
2892
2893#[cfg(test)]
2894mod tests {
2895 #[cfg(feature = "alloc")]
2896 use crate::tz::testdata::TzifTestFile;
2897 use crate::{civil::date, tz::offset};
2898
2899 use super::*;
2900
2901 fn unambiguous(offset_hours: i8) -> AmbiguousOffset {
2902 let offset = offset(offset_hours);
2903 o_unambiguous(offset)
2904 }
2905
2906 fn gap(
2907 earlier_offset_hours: i8,
2908 later_offset_hours: i8,
2909 ) -> AmbiguousOffset {
2910 let earlier = offset(earlier_offset_hours);
2911 let later = offset(later_offset_hours);
2912 o_gap(earlier, later)
2913 }
2914
2915 fn fold(
2916 earlier_offset_hours: i8,
2917 later_offset_hours: i8,
2918 ) -> AmbiguousOffset {
2919 let earlier = offset(earlier_offset_hours);
2920 let later = offset(later_offset_hours);
2921 o_fold(earlier, later)
2922 }
2923
2924 fn o_unambiguous(offset: Offset) -> AmbiguousOffset {
2925 AmbiguousOffset::Unambiguous { offset }
2926 }
2927
2928 fn o_gap(earlier: Offset, later: Offset) -> AmbiguousOffset {
2929 AmbiguousOffset::Gap { before: earlier, after: later }
2930 }
2931
2932 fn o_fold(earlier: Offset, later: Offset) -> AmbiguousOffset {
2933 AmbiguousOffset::Fold { before: earlier, after: later }
2934 }
2935
2936 #[cfg(feature = "alloc")]
2937 #[test]
2938 fn time_zone_tzif_to_ambiguous_timestamp() {
2939 let tests: &[(&str, &[_])] = &[
2940 (
2941 "America/New_York",
2942 &[
2943 ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
2944 ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
2945 ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
2946 ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
2947 ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
2948 ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
2949 ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
2950 ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
2951 ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
2952 ],
2953 ),
2954 (
2955 "Europe/Dublin",
2956 &[
2957 ((1970, 1, 1, 0, 0, 0, 0), unambiguous(1)),
2958 ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2959 ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
2960 ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
2961 ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
2962 ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
2963 ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
2964 ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
2965 ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
2966 ],
2967 ),
2968 (
2969 "Australia/Tasmania",
2970 &[
2971 ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
2972 ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
2973 ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
2974 ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
2975 ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
2976 ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
2977 ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
2978 ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
2979 ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
2980 ],
2981 ),
2982 (
2983 "Antarctica/Troll",
2984 &[
2985 ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
2986 // test the gap
2987 ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2988 ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
2989 ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
2990 // still in the gap!
2991 ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
2992 ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
2993 // finally out
2994 ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
2995 // test the fold
2996 ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
2997 ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
2998 ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
2999 // still in the fold!
3000 ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
3001 ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
3002 // finally out
3003 ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
3004 ],
3005 ),
3006 (
3007 "America/St_Johns",
3008 &[
3009 (
3010 (1969, 12, 31, 20, 30, 0, 0),
3011 o_unambiguous(-Offset::hms(3, 30, 0)),
3012 ),
3013 (
3014 (2024, 3, 10, 1, 59, 59, 999_999_999),
3015 o_unambiguous(-Offset::hms(3, 30, 0)),
3016 ),
3017 (
3018 (2024, 3, 10, 2, 0, 0, 0),
3019 o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3020 ),
3021 (
3022 (2024, 3, 10, 2, 59, 59, 999_999_999),
3023 o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3024 ),
3025 (
3026 (2024, 3, 10, 3, 0, 0, 0),
3027 o_unambiguous(-Offset::hms(2, 30, 0)),
3028 ),
3029 (
3030 (2024, 11, 3, 0, 59, 59, 999_999_999),
3031 o_unambiguous(-Offset::hms(2, 30, 0)),
3032 ),
3033 (
3034 (2024, 11, 3, 1, 0, 0, 0),
3035 o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3036 ),
3037 (
3038 (2024, 11, 3, 1, 59, 59, 999_999_999),
3039 o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3040 ),
3041 (
3042 (2024, 11, 3, 2, 0, 0, 0),
3043 o_unambiguous(-Offset::hms(3, 30, 0)),
3044 ),
3045 ],
3046 ),
3047 // This time zone has an interesting transition where it jumps
3048 // backwards a full day at 1867-10-19T15:30:00.
3049 (
3050 "America/Sitka",
3051 &[
3052 ((1969, 12, 31, 16, 0, 0, 0), unambiguous(-8)),
3053 (
3054 (-9999, 1, 2, 16, 58, 46, 0),
3055 o_unambiguous(Offset::hms(14, 58, 47)),
3056 ),
3057 (
3058 (1867, 10, 18, 15, 29, 59, 0),
3059 o_unambiguous(Offset::hms(14, 58, 47)),
3060 ),
3061 (
3062 (1867, 10, 18, 15, 30, 0, 0),
3063 // A fold of 24 hours!!!
3064 o_fold(
3065 Offset::hms(14, 58, 47),
3066 -Offset::hms(9, 1, 13),
3067 ),
3068 ),
3069 (
3070 (1867, 10, 19, 15, 29, 59, 999_999_999),
3071 // Still in the fold...
3072 o_fold(
3073 Offset::hms(14, 58, 47),
3074 -Offset::hms(9, 1, 13),
3075 ),
3076 ),
3077 (
3078 (1867, 10, 19, 15, 30, 0, 0),
3079 // Finally out.
3080 o_unambiguous(-Offset::hms(9, 1, 13)),
3081 ),
3082 ],
3083 ),
3084 // As with to_datetime, we test every possible transition
3085 // point here since this time zone has a small number of them.
3086 (
3087 "Pacific/Honolulu",
3088 &[
3089 (
3090 (1896, 1, 13, 11, 59, 59, 0),
3091 o_unambiguous(-Offset::hms(10, 31, 26)),
3092 ),
3093 (
3094 (1896, 1, 13, 12, 0, 0, 0),
3095 o_gap(
3096 -Offset::hms(10, 31, 26),
3097 -Offset::hms(10, 30, 0),
3098 ),
3099 ),
3100 (
3101 (1896, 1, 13, 12, 1, 25, 0),
3102 o_gap(
3103 -Offset::hms(10, 31, 26),
3104 -Offset::hms(10, 30, 0),
3105 ),
3106 ),
3107 (
3108 (1896, 1, 13, 12, 1, 26, 0),
3109 o_unambiguous(-Offset::hms(10, 30, 0)),
3110 ),
3111 (
3112 (1933, 4, 30, 1, 59, 59, 0),
3113 o_unambiguous(-Offset::hms(10, 30, 0)),
3114 ),
3115 (
3116 (1933, 4, 30, 2, 0, 0, 0),
3117 o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3118 ),
3119 (
3120 (1933, 4, 30, 2, 59, 59, 0),
3121 o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3122 ),
3123 (
3124 (1933, 4, 30, 3, 0, 0, 0),
3125 o_unambiguous(-Offset::hms(9, 30, 0)),
3126 ),
3127 (
3128 (1933, 5, 21, 10, 59, 59, 0),
3129 o_unambiguous(-Offset::hms(9, 30, 0)),
3130 ),
3131 (
3132 (1933, 5, 21, 11, 0, 0, 0),
3133 o_fold(
3134 -Offset::hms(9, 30, 0),
3135 -Offset::hms(10, 30, 0),
3136 ),
3137 ),
3138 (
3139 (1933, 5, 21, 11, 59, 59, 0),
3140 o_fold(
3141 -Offset::hms(9, 30, 0),
3142 -Offset::hms(10, 30, 0),
3143 ),
3144 ),
3145 (
3146 (1933, 5, 21, 12, 0, 0, 0),
3147 o_unambiguous(-Offset::hms(10, 30, 0)),
3148 ),
3149 (
3150 (1942, 2, 9, 1, 59, 59, 0),
3151 o_unambiguous(-Offset::hms(10, 30, 0)),
3152 ),
3153 (
3154 (1942, 2, 9, 2, 0, 0, 0),
3155 o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3156 ),
3157 (
3158 (1942, 2, 9, 2, 59, 59, 0),
3159 o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3160 ),
3161 (
3162 (1942, 2, 9, 3, 0, 0, 0),
3163 o_unambiguous(-Offset::hms(9, 30, 0)),
3164 ),
3165 (
3166 (1945, 8, 14, 13, 29, 59, 0),
3167 o_unambiguous(-Offset::hms(9, 30, 0)),
3168 ),
3169 (
3170 (1945, 8, 14, 13, 30, 0, 0),
3171 o_unambiguous(-Offset::hms(9, 30, 0)),
3172 ),
3173 (
3174 (1945, 8, 14, 13, 30, 1, 0),
3175 o_unambiguous(-Offset::hms(9, 30, 0)),
3176 ),
3177 (
3178 (1945, 9, 30, 0, 59, 59, 0),
3179 o_unambiguous(-Offset::hms(9, 30, 0)),
3180 ),
3181 (
3182 (1945, 9, 30, 1, 0, 0, 0),
3183 o_fold(
3184 -Offset::hms(9, 30, 0),
3185 -Offset::hms(10, 30, 0),
3186 ),
3187 ),
3188 (
3189 (1945, 9, 30, 1, 59, 59, 0),
3190 o_fold(
3191 -Offset::hms(9, 30, 0),
3192 -Offset::hms(10, 30, 0),
3193 ),
3194 ),
3195 (
3196 (1945, 9, 30, 2, 0, 0, 0),
3197 o_unambiguous(-Offset::hms(10, 30, 0)),
3198 ),
3199 (
3200 (1947, 6, 8, 1, 59, 59, 0),
3201 o_unambiguous(-Offset::hms(10, 30, 0)),
3202 ),
3203 (
3204 (1947, 6, 8, 2, 0, 0, 0),
3205 o_gap(-Offset::hms(10, 30, 0), -offset(10)),
3206 ),
3207 (
3208 (1947, 6, 8, 2, 29, 59, 0),
3209 o_gap(-Offset::hms(10, 30, 0), -offset(10)),
3210 ),
3211 ((1947, 6, 8, 2, 30, 0, 0), unambiguous(-10)),
3212 ],
3213 ),
3214 ];
3215 for &(tzname, datetimes_to_ambiguous) in tests {
3216 let test_file = TzifTestFile::get(tzname);
3217 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3218 for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
3219 let (year, month, day, hour, min, sec, nano) = datetime;
3220 let dt = date(year, month, day).at(hour, min, sec, nano);
3221 let got = tz.to_ambiguous_zoned_datetime(dt);
3222 assert_eq!(
3223 got.offset(),
3224 ambiguous_kind,
3225 "\nTZ: {tzname}\ndatetime: \
3226 {year:04}-{month:02}-{day:02}T\
3227 {hour:02}:{min:02}:{sec:02}.{nano:09}",
3228 );
3229 }
3230 }
3231 }
3232
3233 #[cfg(feature = "alloc")]
3234 #[test]
3235 fn time_zone_tzif_to_datetime() {
3236 let o = |hours| offset(hours);
3237 let tests: &[(&str, &[_])] = &[
3238 (
3239 "America/New_York",
3240 &[
3241 ((0, 0), o(-5), "EST", (1969, 12, 31, 19, 0, 0, 0)),
3242 (
3243 (1710052200, 0),
3244 o(-5),
3245 "EST",
3246 (2024, 3, 10, 1, 30, 0, 0),
3247 ),
3248 (
3249 (1710053999, 999_999_999),
3250 o(-5),
3251 "EST",
3252 (2024, 3, 10, 1, 59, 59, 999_999_999),
3253 ),
3254 ((1710054000, 0), o(-4), "EDT", (2024, 3, 10, 3, 0, 0, 0)),
3255 (
3256 (1710055800, 0),
3257 o(-4),
3258 "EDT",
3259 (2024, 3, 10, 3, 30, 0, 0),
3260 ),
3261 ((1730610000, 0), o(-4), "EDT", (2024, 11, 3, 1, 0, 0, 0)),
3262 (
3263 (1730611800, 0),
3264 o(-4),
3265 "EDT",
3266 (2024, 11, 3, 1, 30, 0, 0),
3267 ),
3268 (
3269 (1730613599, 999_999_999),
3270 o(-4),
3271 "EDT",
3272 (2024, 11, 3, 1, 59, 59, 999_999_999),
3273 ),
3274 ((1730613600, 0), o(-5), "EST", (2024, 11, 3, 1, 0, 0, 0)),
3275 (
3276 (1730615400, 0),
3277 o(-5),
3278 "EST",
3279 (2024, 11, 3, 1, 30, 0, 0),
3280 ),
3281 ],
3282 ),
3283 (
3284 "Australia/Tasmania",
3285 &[
3286 ((0, 0), o(11), "AEDT", (1970, 1, 1, 11, 0, 0, 0)),
3287 (
3288 (1728142200, 0),
3289 o(10),
3290 "AEST",
3291 (2024, 10, 6, 1, 30, 0, 0),
3292 ),
3293 (
3294 (1728143999, 999_999_999),
3295 o(10),
3296 "AEST",
3297 (2024, 10, 6, 1, 59, 59, 999_999_999),
3298 ),
3299 (
3300 (1728144000, 0),
3301 o(11),
3302 "AEDT",
3303 (2024, 10, 6, 3, 0, 0, 0),
3304 ),
3305 (
3306 (1728145800, 0),
3307 o(11),
3308 "AEDT",
3309 (2024, 10, 6, 3, 30, 0, 0),
3310 ),
3311 ((1712415600, 0), o(11), "AEDT", (2024, 4, 7, 2, 0, 0, 0)),
3312 (
3313 (1712417400, 0),
3314 o(11),
3315 "AEDT",
3316 (2024, 4, 7, 2, 30, 0, 0),
3317 ),
3318 (
3319 (1712419199, 999_999_999),
3320 o(11),
3321 "AEDT",
3322 (2024, 4, 7, 2, 59, 59, 999_999_999),
3323 ),
3324 ((1712419200, 0), o(10), "AEST", (2024, 4, 7, 2, 0, 0, 0)),
3325 (
3326 (1712421000, 0),
3327 o(10),
3328 "AEST",
3329 (2024, 4, 7, 2, 30, 0, 0),
3330 ),
3331 ],
3332 ),
3333 // Pacific/Honolulu is small eough that we just test every
3334 // possible instant before, at and after each transition.
3335 (
3336 "Pacific/Honolulu",
3337 &[
3338 (
3339 (-2334101315, 0),
3340 -Offset::hms(10, 31, 26),
3341 "LMT",
3342 (1896, 1, 13, 11, 59, 59, 0),
3343 ),
3344 (
3345 (-2334101314, 0),
3346 -Offset::hms(10, 30, 0),
3347 "HST",
3348 (1896, 1, 13, 12, 1, 26, 0),
3349 ),
3350 (
3351 (-2334101313, 0),
3352 -Offset::hms(10, 30, 0),
3353 "HST",
3354 (1896, 1, 13, 12, 1, 27, 0),
3355 ),
3356 (
3357 (-1157283001, 0),
3358 -Offset::hms(10, 30, 0),
3359 "HST",
3360 (1933, 4, 30, 1, 59, 59, 0),
3361 ),
3362 (
3363 (-1157283000, 0),
3364 -Offset::hms(9, 30, 0),
3365 "HDT",
3366 (1933, 4, 30, 3, 0, 0, 0),
3367 ),
3368 (
3369 (-1157282999, 0),
3370 -Offset::hms(9, 30, 0),
3371 "HDT",
3372 (1933, 4, 30, 3, 0, 1, 0),
3373 ),
3374 (
3375 (-1155436201, 0),
3376 -Offset::hms(9, 30, 0),
3377 "HDT",
3378 (1933, 5, 21, 11, 59, 59, 0),
3379 ),
3380 (
3381 (-1155436200, 0),
3382 -Offset::hms(10, 30, 0),
3383 "HST",
3384 (1933, 5, 21, 11, 0, 0, 0),
3385 ),
3386 (
3387 (-1155436199, 0),
3388 -Offset::hms(10, 30, 0),
3389 "HST",
3390 (1933, 5, 21, 11, 0, 1, 0),
3391 ),
3392 (
3393 (-880198201, 0),
3394 -Offset::hms(10, 30, 0),
3395 "HST",
3396 (1942, 2, 9, 1, 59, 59, 0),
3397 ),
3398 (
3399 (-880198200, 0),
3400 -Offset::hms(9, 30, 0),
3401 "HWT",
3402 (1942, 2, 9, 3, 0, 0, 0),
3403 ),
3404 (
3405 (-880198199, 0),
3406 -Offset::hms(9, 30, 0),
3407 "HWT",
3408 (1942, 2, 9, 3, 0, 1, 0),
3409 ),
3410 (
3411 (-769395601, 0),
3412 -Offset::hms(9, 30, 0),
3413 "HWT",
3414 (1945, 8, 14, 13, 29, 59, 0),
3415 ),
3416 (
3417 (-769395600, 0),
3418 -Offset::hms(9, 30, 0),
3419 "HPT",
3420 (1945, 8, 14, 13, 30, 0, 0),
3421 ),
3422 (
3423 (-769395599, 0),
3424 -Offset::hms(9, 30, 0),
3425 "HPT",
3426 (1945, 8, 14, 13, 30, 1, 0),
3427 ),
3428 (
3429 (-765376201, 0),
3430 -Offset::hms(9, 30, 0),
3431 "HPT",
3432 (1945, 9, 30, 1, 59, 59, 0),
3433 ),
3434 (
3435 (-765376200, 0),
3436 -Offset::hms(10, 30, 0),
3437 "HST",
3438 (1945, 9, 30, 1, 0, 0, 0),
3439 ),
3440 (
3441 (-765376199, 0),
3442 -Offset::hms(10, 30, 0),
3443 "HST",
3444 (1945, 9, 30, 1, 0, 1, 0),
3445 ),
3446 (
3447 (-712150201, 0),
3448 -Offset::hms(10, 30, 0),
3449 "HST",
3450 (1947, 6, 8, 1, 59, 59, 0),
3451 ),
3452 // At this point, we hit the last transition and the POSIX
3453 // TZ string takes over.
3454 (
3455 (-712150200, 0),
3456 -Offset::hms(10, 0, 0),
3457 "HST",
3458 (1947, 6, 8, 2, 30, 0, 0),
3459 ),
3460 (
3461 (-712150199, 0),
3462 -Offset::hms(10, 0, 0),
3463 "HST",
3464 (1947, 6, 8, 2, 30, 1, 0),
3465 ),
3466 ],
3467 ),
3468 // This time zone has an interesting transition where it jumps
3469 // backwards a full day at 1867-10-19T15:30:00.
3470 (
3471 "America/Sitka",
3472 &[
3473 ((0, 0), o(-8), "PST", (1969, 12, 31, 16, 0, 0, 0)),
3474 (
3475 (-377705023201, 0),
3476 Offset::hms(14, 58, 47),
3477 "LMT",
3478 (-9999, 1, 2, 16, 58, 46, 0),
3479 ),
3480 (
3481 (-3225223728, 0),
3482 Offset::hms(14, 58, 47),
3483 "LMT",
3484 (1867, 10, 19, 15, 29, 59, 0),
3485 ),
3486 // Notice the 24 hour time jump backwards a whole day!
3487 (
3488 (-3225223727, 0),
3489 -Offset::hms(9, 1, 13),
3490 "LMT",
3491 (1867, 10, 18, 15, 30, 0, 0),
3492 ),
3493 (
3494 (-3225223726, 0),
3495 -Offset::hms(9, 1, 13),
3496 "LMT",
3497 (1867, 10, 18, 15, 30, 1, 0),
3498 ),
3499 ],
3500 ),
3501 ];
3502 for &(tzname, timestamps_to_datetimes) in tests {
3503 let test_file = TzifTestFile::get(tzname);
3504 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3505 for &((unix_sec, unix_nano), offset, abbrev, datetime) in
3506 timestamps_to_datetimes
3507 {
3508 let (year, month, day, hour, min, sec, nano) = datetime;
3509 let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3510 let info = tz.to_offset_info(timestamp);
3511 assert_eq!(
3512 info.offset(),
3513 offset,
3514 "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3515 );
3516 assert_eq!(
3517 info.abbreviation(),
3518 abbrev,
3519 "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3520 );
3521 assert_eq!(
3522 info.offset().to_datetime(timestamp),
3523 date(year, month, day).at(hour, min, sec, nano),
3524 "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3525 );
3526 }
3527 }
3528 }
3529
3530 #[cfg(feature = "alloc")]
3531 #[test]
3532 fn time_zone_posix_to_ambiguous_timestamp() {
3533 let tests: &[(&str, &[_])] = &[
3534 // America/New_York, but a utopia in which DST is abolished.
3535 (
3536 "EST5",
3537 &[
3538 ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3539 ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3540 ],
3541 ),
3542 // The standard DST rule for America/New_York.
3543 (
3544 "EST5EDT,M3.2.0,M11.1.0",
3545 &[
3546 ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3547 ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3548 ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
3549 ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
3550 ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
3551 ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
3552 ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
3553 ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
3554 ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3555 ],
3556 ),
3557 // A bit of a nonsensical America/New_York that has DST, but whose
3558 // offset is equivalent to standard time. Having the same offset
3559 // means there's never any ambiguity.
3560 (
3561 "EST5EDT5,M3.2.0,M11.1.0",
3562 &[
3563 ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3564 ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3565 ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3566 ((2024, 3, 10, 2, 59, 59, 999_999_999), unambiguous(-5)),
3567 ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-5)),
3568 ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-5)),
3569 ((2024, 11, 3, 1, 0, 0, 0), unambiguous(-5)),
3570 ((2024, 11, 3, 1, 59, 59, 999_999_999), unambiguous(-5)),
3571 ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3572 ],
3573 ),
3574 // This is Europe/Dublin's rule. It's interesting because its
3575 // DST is an offset behind standard time. (DST is usually one hour
3576 // ahead of standard time.)
3577 (
3578 "IST-1GMT0,M10.5.0,M3.5.0/1",
3579 &[
3580 ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3581 ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3582 ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
3583 ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
3584 ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
3585 ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
3586 ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
3587 ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
3588 ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
3589 ],
3590 ),
3591 // This is Australia/Tasmania's rule. We chose this because it's
3592 // in the southern hemisphere where DST still skips ahead one hour,
3593 // but it usually starts in the fall and ends in the spring.
3594 (
3595 "AEST-10AEDT,M10.1.0,M4.1.0/3",
3596 &[
3597 ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
3598 ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
3599 ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
3600 ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
3601 ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
3602 ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
3603 ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
3604 ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
3605 ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
3606 ],
3607 ),
3608 // This is Antarctica/Troll's rule. We chose this one because its
3609 // DST transition is 2 hours instead of the standard 1 hour. This
3610 // means gaps and folds are twice as long as they usually are. And
3611 // it means there are 22 hour and 26 hour days, respectively. Wow!
3612 (
3613 "<+00>0<+02>-2,M3.5.0/1,M10.5.0/3",
3614 &[
3615 ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3616 // test the gap
3617 ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3618 ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
3619 ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
3620 // still in the gap!
3621 ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
3622 ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
3623 // finally out
3624 ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
3625 // test the fold
3626 ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
3627 ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
3628 ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
3629 // still in the fold!
3630 ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
3631 ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
3632 // finally out
3633 ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
3634 ],
3635 ),
3636 // This is America/St_Johns' rule, which has an offset with
3637 // non-zero minutes *and* a DST transition rule. (Indian Standard
3638 // Time is the one I'm more familiar with, but it turns out IST
3639 // does not have DST!)
3640 (
3641 "NST3:30NDT,M3.2.0,M11.1.0",
3642 &[
3643 (
3644 (1969, 12, 31, 20, 30, 0, 0),
3645 o_unambiguous(-Offset::hms(3, 30, 0)),
3646 ),
3647 (
3648 (2024, 3, 10, 1, 59, 59, 999_999_999),
3649 o_unambiguous(-Offset::hms(3, 30, 0)),
3650 ),
3651 (
3652 (2024, 3, 10, 2, 0, 0, 0),
3653 o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3654 ),
3655 (
3656 (2024, 3, 10, 2, 59, 59, 999_999_999),
3657 o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3658 ),
3659 (
3660 (2024, 3, 10, 3, 0, 0, 0),
3661 o_unambiguous(-Offset::hms(2, 30, 0)),
3662 ),
3663 (
3664 (2024, 11, 3, 0, 59, 59, 999_999_999),
3665 o_unambiguous(-Offset::hms(2, 30, 0)),
3666 ),
3667 (
3668 (2024, 11, 3, 1, 0, 0, 0),
3669 o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3670 ),
3671 (
3672 (2024, 11, 3, 1, 59, 59, 999_999_999),
3673 o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3674 ),
3675 (
3676 (2024, 11, 3, 2, 0, 0, 0),
3677 o_unambiguous(-Offset::hms(3, 30, 0)),
3678 ),
3679 ],
3680 ),
3681 ];
3682 for &(posix_tz, datetimes_to_ambiguous) in tests {
3683 let tz = TimeZone::posix(posix_tz).unwrap();
3684 for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
3685 let (year, month, day, hour, min, sec, nano) = datetime;
3686 let dt = date(year, month, day).at(hour, min, sec, nano);
3687 let got = tz.to_ambiguous_zoned_datetime(dt);
3688 assert_eq!(
3689 got.offset(),
3690 ambiguous_kind,
3691 "\nTZ: {posix_tz}\ndatetime: \
3692 {year:04}-{month:02}-{day:02}T\
3693 {hour:02}:{min:02}:{sec:02}.{nano:09}",
3694 );
3695 }
3696 }
3697 }
3698
3699 #[cfg(feature = "alloc")]
3700 #[test]
3701 fn time_zone_posix_to_datetime() {
3702 let o = |hours| offset(hours);
3703 let tests: &[(&str, &[_])] = &[
3704 ("EST5", &[((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0))]),
3705 (
3706 // From America/New_York
3707 "EST5EDT,M3.2.0,M11.1.0",
3708 &[
3709 ((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0)),
3710 ((1710052200, 0), o(-5), (2024, 3, 10, 1, 30, 0, 0)),
3711 (
3712 (1710053999, 999_999_999),
3713 o(-5),
3714 (2024, 3, 10, 1, 59, 59, 999_999_999),
3715 ),
3716 ((1710054000, 0), o(-4), (2024, 3, 10, 3, 0, 0, 0)),
3717 ((1710055800, 0), o(-4), (2024, 3, 10, 3, 30, 0, 0)),
3718 ((1730610000, 0), o(-4), (2024, 11, 3, 1, 0, 0, 0)),
3719 ((1730611800, 0), o(-4), (2024, 11, 3, 1, 30, 0, 0)),
3720 (
3721 (1730613599, 999_999_999),
3722 o(-4),
3723 (2024, 11, 3, 1, 59, 59, 999_999_999),
3724 ),
3725 ((1730613600, 0), o(-5), (2024, 11, 3, 1, 0, 0, 0)),
3726 ((1730615400, 0), o(-5), (2024, 11, 3, 1, 30, 0, 0)),
3727 ],
3728 ),
3729 (
3730 // From Australia/Tasmania
3731 //
3732 // We chose this because it's a time zone in the southern
3733 // hemisphere with DST. Unlike the northern hemisphere, its DST
3734 // starts in the fall and ends in the spring. In the northern
3735 // hemisphere, we typically start DST in the spring and end it
3736 // in the fall.
3737 "AEST-10AEDT,M10.1.0,M4.1.0/3",
3738 &[
3739 ((0, 0), o(11), (1970, 1, 1, 11, 0, 0, 0)),
3740 ((1728142200, 0), o(10), (2024, 10, 6, 1, 30, 0, 0)),
3741 (
3742 (1728143999, 999_999_999),
3743 o(10),
3744 (2024, 10, 6, 1, 59, 59, 999_999_999),
3745 ),
3746 ((1728144000, 0), o(11), (2024, 10, 6, 3, 0, 0, 0)),
3747 ((1728145800, 0), o(11), (2024, 10, 6, 3, 30, 0, 0)),
3748 ((1712415600, 0), o(11), (2024, 4, 7, 2, 0, 0, 0)),
3749 ((1712417400, 0), o(11), (2024, 4, 7, 2, 30, 0, 0)),
3750 (
3751 (1712419199, 999_999_999),
3752 o(11),
3753 (2024, 4, 7, 2, 59, 59, 999_999_999),
3754 ),
3755 ((1712419200, 0), o(10), (2024, 4, 7, 2, 0, 0, 0)),
3756 ((1712421000, 0), o(10), (2024, 4, 7, 2, 30, 0, 0)),
3757 ],
3758 ),
3759 (
3760 // Uses the maximum possible offset. A sloppy read of POSIX
3761 // seems to indicate the maximum offset is 24:59:59, but since
3762 // DST defaults to 1 hour ahead of standard time, it's possible
3763 // to use 24:59:59 for standard time, omit the DST offset, and
3764 // thus get a DST offset of 25:59:59.
3765 "XXX-24:59:59YYY,M3.2.0,M11.1.0",
3766 &[
3767 // 2024-01-05T00:00:00+00
3768 (
3769 (1704412800, 0),
3770 Offset::hms(24, 59, 59),
3771 (2024, 1, 6, 0, 59, 59, 0),
3772 ),
3773 // 2024-06-05T00:00:00+00 (DST)
3774 (
3775 (1717545600, 0),
3776 Offset::hms(25, 59, 59),
3777 (2024, 6, 6, 1, 59, 59, 0),
3778 ),
3779 ],
3780 ),
3781 ];
3782 for &(posix_tz, timestamps_to_datetimes) in tests {
3783 let tz = TimeZone::posix(posix_tz).unwrap();
3784 for &((unix_sec, unix_nano), offset, datetime) in
3785 timestamps_to_datetimes
3786 {
3787 let (year, month, day, hour, min, sec, nano) = datetime;
3788 let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3789 assert_eq!(
3790 tz.to_offset(timestamp),
3791 offset,
3792 "\ntimestamp({unix_sec}, {unix_nano})",
3793 );
3794 assert_eq!(
3795 tz.to_datetime(timestamp),
3796 date(year, month, day).at(hour, min, sec, nano),
3797 "\ntimestamp({unix_sec}, {unix_nano})",
3798 );
3799 }
3800 }
3801 }
3802
3803 #[test]
3804 fn time_zone_fixed_to_datetime() {
3805 let tz = offset(-5).to_time_zone();
3806 let unix_epoch = Timestamp::new(0, 0).unwrap();
3807 assert_eq!(
3808 tz.to_datetime(unix_epoch),
3809 date(1969, 12, 31).at(19, 0, 0, 0),
3810 );
3811
3812 let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3813 let timestamp = Timestamp::new(253402207200, 999_999_999).unwrap();
3814 assert_eq!(
3815 tz.to_datetime(timestamp),
3816 date(9999, 12, 31).at(23, 59, 59, 999_999_999),
3817 );
3818
3819 let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3820 let timestamp = Timestamp::new(-377705023201, 0).unwrap();
3821 assert_eq!(
3822 tz.to_datetime(timestamp),
3823 date(-9999, 1, 1).at(0, 0, 0, 0),
3824 );
3825 }
3826
3827 #[test]
3828 fn time_zone_fixed_to_timestamp() {
3829 let tz = offset(-5).to_time_zone();
3830 let dt = date(1969, 12, 31).at(19, 0, 0, 0);
3831 assert_eq!(
3832 tz.to_zoned_datetime(dt).unwrap().timestamp(),
3833 Timestamp::new(0, 0).unwrap()
3834 );
3835
3836 let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3837 let dt = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
3838 assert_eq!(
3839 tz.to_zoned_datetime(dt).unwrap().timestamp(),
3840 Timestamp::new(253402207200, 999_999_999).unwrap(),
3841 );
3842 let tz = Offset::from_seconds(93_598).unwrap().to_time_zone();
3843 assert!(tz.to_zoned_datetime(dt).is_err());
3844
3845 let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3846 let dt = date(-9999, 1, 1).at(0, 0, 0, 0);
3847 assert_eq!(
3848 tz.to_zoned_datetime(dt).unwrap().timestamp(),
3849 Timestamp::new(-377705023201, 0).unwrap(),
3850 );
3851 let tz = Offset::from_seconds(-93_598).unwrap().to_time_zone();
3852 assert!(tz.to_zoned_datetime(dt).is_err());
3853 }
3854
3855 #[cfg(feature = "alloc")]
3856 #[test]
3857 fn time_zone_tzif_previous_transition() {
3858 let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3859 (
3860 "UTC",
3861 &[
3862 ("1969-12-31T19Z", None),
3863 ("2024-03-10T02Z", None),
3864 ("-009999-12-01 00Z", None),
3865 ("9999-12-01 00Z", None),
3866 ],
3867 ),
3868 (
3869 "America/New_York",
3870 &[
3871 ("2024-03-10 08Z", Some("2024-03-10 07Z")),
3872 ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
3873 ("2024-03-10 07Z", Some("2023-11-05 06Z")),
3874 ("2023-11-05 06Z", Some("2023-03-12 07Z")),
3875 ("-009999-01-31 00Z", None),
3876 ("9999-12-01 00Z", Some("9999-11-07 06Z")),
3877 // While at present we have "fat" TZif files for our
3878 // testdata, it's conceivable they could be swapped to
3879 // "slim." In which case, the tests above will mostly just
3880 // be testing POSIX TZ strings and not the TZif logic. So
3881 // below, we include times that will be in slim (i.e.,
3882 // historical times the precede the current DST rule).
3883 ("1969-12-31 19Z", Some("1969-10-26 06Z")),
3884 ("2000-04-02 08Z", Some("2000-04-02 07Z")),
3885 ("2000-04-02 07:00:00.000000001Z", Some("2000-04-02 07Z")),
3886 ("2000-04-02 07Z", Some("1999-10-31 06Z")),
3887 ("1999-10-31 06Z", Some("1999-04-04 07Z")),
3888 ],
3889 ),
3890 (
3891 "Australia/Tasmania",
3892 &[
3893 ("2010-04-03 17Z", Some("2010-04-03 16Z")),
3894 ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
3895 ("2010-04-03 16Z", Some("2009-10-03 16Z")),
3896 ("2009-10-03 16Z", Some("2009-04-04 16Z")),
3897 ("-009999-01-31 00Z", None),
3898 ("9999-12-01 00Z", Some("9999-10-02 16Z")),
3899 // Tests for historical data from tzdb. No POSIX TZ.
3900 ("2000-03-25 17Z", Some("2000-03-25 16Z")),
3901 ("2000-03-25 16:00:00.000000001Z", Some("2000-03-25 16Z")),
3902 ("2000-03-25 16Z", Some("1999-10-02 16Z")),
3903 ("1999-10-02 16Z", Some("1999-03-27 16Z")),
3904 ],
3905 ),
3906 // This is Europe/Dublin's rule. It's interesting because its
3907 // DST is an offset behind standard time. (DST is usually one hour
3908 // ahead of standard time.)
3909 (
3910 "Europe/Dublin",
3911 &[
3912 ("2010-03-28 02Z", Some("2010-03-28 01Z")),
3913 ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
3914 ("2010-03-28 01Z", Some("2009-10-25 01Z")),
3915 ("2009-10-25 01Z", Some("2009-03-29 01Z")),
3916 ("-009999-01-31 00Z", None),
3917 ("9999-12-01 00Z", Some("9999-10-31 01Z")),
3918 // Tests for historical data from tzdb. No POSIX TZ.
3919 ("1990-03-25 02Z", Some("1990-03-25 01Z")),
3920 ("1990-03-25 01:00:00.000000001Z", Some("1990-03-25 01Z")),
3921 ("1990-03-25 01Z", Some("1989-10-29 01Z")),
3922 ("1989-10-25 01Z", Some("1989-03-26 01Z")),
3923 ],
3924 ),
3925 (
3926 // Sao Paulo eliminated DST in 2019, so the previous transition
3927 // from 2024 is several years back.
3928 "America/Sao_Paulo",
3929 &[("2024-03-10 08Z", Some("2019-02-17 02Z"))],
3930 ),
3931 ];
3932 for &(tzname, prev_trans) in tests {
3933 if tzname != "America/Sao_Paulo" {
3934 continue;
3935 }
3936 let test_file = TzifTestFile::get(tzname);
3937 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3938 for (given, expected) in prev_trans {
3939 let given: Timestamp = given.parse().unwrap();
3940 let expected =
3941 expected.map(|s| s.parse::<Timestamp>().unwrap());
3942 let got = tz.previous_transition(given).map(|t| t.timestamp());
3943 assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
3944 }
3945 }
3946 }
3947
3948 #[cfg(feature = "alloc")]
3949 #[test]
3950 fn time_zone_tzif_next_transition() {
3951 let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3952 (
3953 "UTC",
3954 &[
3955 ("1969-12-31T19Z", None),
3956 ("2024-03-10T02Z", None),
3957 ("-009999-12-01 00Z", None),
3958 ("9999-12-01 00Z", None),
3959 ],
3960 ),
3961 (
3962 "America/New_York",
3963 &[
3964 ("2024-03-10 06Z", Some("2024-03-10 07Z")),
3965 ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
3966 ("2024-03-10 07Z", Some("2024-11-03 06Z")),
3967 ("2024-11-03 06Z", Some("2025-03-09 07Z")),
3968 ("-009999-12-01 00Z", Some("1883-11-18 17Z")),
3969 ("9999-12-01 00Z", None),
3970 // While at present we have "fat" TZif files for our
3971 // testdata, it's conceivable they could be swapped to
3972 // "slim." In which case, the tests above will mostly just
3973 // be testing POSIX TZ strings and not the TZif logic. So
3974 // below, we include times that will be in slim (i.e.,
3975 // historical times the precede the current DST rule).
3976 ("1969-12-31 19Z", Some("1970-04-26 07Z")),
3977 ("2000-04-02 06Z", Some("2000-04-02 07Z")),
3978 ("2000-04-02 06:59:59.999999999Z", Some("2000-04-02 07Z")),
3979 ("2000-04-02 07Z", Some("2000-10-29 06Z")),
3980 ("2000-10-29 06Z", Some("2001-04-01 07Z")),
3981 ],
3982 ),
3983 (
3984 "Australia/Tasmania",
3985 &[
3986 ("2010-04-03 15Z", Some("2010-04-03 16Z")),
3987 ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
3988 ("2010-04-03 16Z", Some("2010-10-02 16Z")),
3989 ("2010-10-02 16Z", Some("2011-04-02 16Z")),
3990 ("-009999-12-01 00Z", Some("1895-08-31 14:10:44Z")),
3991 ("9999-12-01 00Z", None),
3992 // Tests for historical data from tzdb. No POSIX TZ.
3993 ("2000-03-25 15Z", Some("2000-03-25 16Z")),
3994 ("2000-03-25 15:59:59.999999999Z", Some("2000-03-25 16Z")),
3995 ("2000-03-25 16Z", Some("2000-08-26 16Z")),
3996 ("2000-08-26 16Z", Some("2001-03-24 16Z")),
3997 ],
3998 ),
3999 (
4000 "Europe/Dublin",
4001 &[
4002 ("2010-03-28 00Z", Some("2010-03-28 01Z")),
4003 ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
4004 ("2010-03-28 01Z", Some("2010-10-31 01Z")),
4005 ("2010-10-31 01Z", Some("2011-03-27 01Z")),
4006 ("-009999-12-01 00Z", Some("1880-08-02 00:25:21Z")),
4007 ("9999-12-01 00Z", None),
4008 // Tests for historical data from tzdb. No POSIX TZ.
4009 ("1990-03-25 00Z", Some("1990-03-25 01Z")),
4010 ("1990-03-25 00:59:59.999999999Z", Some("1990-03-25 01Z")),
4011 ("1990-03-25 01Z", Some("1990-10-28 01Z")),
4012 ("1990-10-28 01Z", Some("1991-03-31 01Z")),
4013 ],
4014 ),
4015 (
4016 // Sao Paulo eliminated DST in 2019, so the next transition
4017 // from 2024 no longer exists.
4018 "America/Sao_Paulo",
4019 &[("2024-03-10 08Z", None)],
4020 ),
4021 ];
4022 for &(tzname, next_trans) in tests {
4023 let test_file = TzifTestFile::get(tzname);
4024 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4025 for (given, expected) in next_trans {
4026 let given: Timestamp = given.parse().unwrap();
4027 let expected =
4028 expected.map(|s| s.parse::<Timestamp>().unwrap());
4029 let got = tz.next_transition(given).map(|t| t.timestamp());
4030 assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
4031 }
4032 }
4033 }
4034
4035 #[cfg(feature = "alloc")]
4036 #[test]
4037 fn time_zone_posix_previous_transition() {
4038 let tests: &[(&str, &[(&str, Option<&str>)])] = &[
4039 // America/New_York, but a utopia in which DST is abolished. There
4040 // are no time zone transitions, so next_transition always returns
4041 // None.
4042 (
4043 "EST5",
4044 &[
4045 ("1969-12-31T19Z", None),
4046 ("2024-03-10T02Z", None),
4047 ("-009999-12-01 00Z", None),
4048 ("9999-12-01 00Z", None),
4049 ],
4050 ),
4051 // The standard DST rule for America/New_York.
4052 (
4053 "EST5EDT,M3.2.0,M11.1.0",
4054 &[
4055 ("1969-12-31 19Z", Some("1969-11-02 06Z")),
4056 ("2024-03-10 08Z", Some("2024-03-10 07Z")),
4057 ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
4058 ("2024-03-10 07Z", Some("2023-11-05 06Z")),
4059 ("2023-11-05 06Z", Some("2023-03-12 07Z")),
4060 ("-009999-01-31 00Z", None),
4061 ("9999-12-01 00Z", Some("9999-11-07 06Z")),
4062 ],
4063 ),
4064 (
4065 // From Australia/Tasmania
4066 "AEST-10AEDT,M10.1.0,M4.1.0/3",
4067 &[
4068 ("2010-04-03 17Z", Some("2010-04-03 16Z")),
4069 ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
4070 ("2010-04-03 16Z", Some("2009-10-03 16Z")),
4071 ("2009-10-03 16Z", Some("2009-04-04 16Z")),
4072 ("-009999-01-31 00Z", None),
4073 ("9999-12-01 00Z", Some("9999-10-02 16Z")),
4074 ],
4075 ),
4076 // This is Europe/Dublin's rule. It's interesting because its
4077 // DST is an offset behind standard time. (DST is usually one hour
4078 // ahead of standard time.)
4079 (
4080 "IST-1GMT0,M10.5.0,M3.5.0/1",
4081 &[
4082 ("2010-03-28 02Z", Some("2010-03-28 01Z")),
4083 ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
4084 ("2010-03-28 01Z", Some("2009-10-25 01Z")),
4085 ("2009-10-25 01Z", Some("2009-03-29 01Z")),
4086 ("-009999-01-31 00Z", None),
4087 ("9999-12-01 00Z", Some("9999-10-31 01Z")),
4088 ],
4089 ),
4090 ];
4091 for &(posix_tz, prev_trans) in tests {
4092 let tz = TimeZone::posix(posix_tz).unwrap();
4093 for (given, expected) in prev_trans {
4094 let given: Timestamp = given.parse().unwrap();
4095 let expected =
4096 expected.map(|s| s.parse::<Timestamp>().unwrap());
4097 let got = tz.previous_transition(given).map(|t| t.timestamp());
4098 assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
4099 }
4100 }
4101 }
4102
4103 #[cfg(feature = "alloc")]
4104 #[test]
4105 fn time_zone_posix_next_transition() {
4106 let tests: &[(&str, &[(&str, Option<&str>)])] = &[
4107 // America/New_York, but a utopia in which DST is abolished. There
4108 // are no time zone transitions, so next_transition always returns
4109 // None.
4110 (
4111 "EST5",
4112 &[
4113 ("1969-12-31T19Z", None),
4114 ("2024-03-10T02Z", None),
4115 ("-009999-12-01 00Z", None),
4116 ("9999-12-01 00Z", None),
4117 ],
4118 ),
4119 // The standard DST rule for America/New_York.
4120 (
4121 "EST5EDT,M3.2.0,M11.1.0",
4122 &[
4123 ("1969-12-31 19Z", Some("1970-03-08 07Z")),
4124 ("2024-03-10 06Z", Some("2024-03-10 07Z")),
4125 ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
4126 ("2024-03-10 07Z", Some("2024-11-03 06Z")),
4127 ("2024-11-03 06Z", Some("2025-03-09 07Z")),
4128 ("-009999-12-01 00Z", Some("-009998-03-10 07Z")),
4129 ("9999-12-01 00Z", None),
4130 ],
4131 ),
4132 (
4133 // From Australia/Tasmania
4134 "AEST-10AEDT,M10.1.0,M4.1.0/3",
4135 &[
4136 ("2010-04-03 15Z", Some("2010-04-03 16Z")),
4137 ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
4138 ("2010-04-03 16Z", Some("2010-10-02 16Z")),
4139 ("2010-10-02 16Z", Some("2011-04-02 16Z")),
4140 ("-009999-12-01 00Z", Some("-009998-04-06 16Z")),
4141 ("9999-12-01 00Z", None),
4142 ],
4143 ),
4144 // This is Europe/Dublin's rule. It's interesting because its
4145 // DST is an offset behind standard time. (DST is usually one hour
4146 // ahead of standard time.)
4147 (
4148 "IST-1GMT0,M10.5.0,M3.5.0/1",
4149 &[
4150 ("2010-03-28 00Z", Some("2010-03-28 01Z")),
4151 ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
4152 ("2010-03-28 01Z", Some("2010-10-31 01Z")),
4153 ("2010-10-31 01Z", Some("2011-03-27 01Z")),
4154 ("-009999-12-01 00Z", Some("-009998-03-31 01Z")),
4155 ("9999-12-01 00Z", None),
4156 ],
4157 ),
4158 ];
4159 for &(posix_tz, next_trans) in tests {
4160 let tz = TimeZone::posix(posix_tz).unwrap();
4161 for (given, expected) in next_trans {
4162 let given: Timestamp = given.parse().unwrap();
4163 let expected =
4164 expected.map(|s| s.parse::<Timestamp>().unwrap());
4165 let got = tz.next_transition(given).map(|t| t.timestamp());
4166 assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
4167 }
4168 }
4169 }
4170
4171 /// This tests that the size of a time zone is kept at a single word.
4172 ///
4173 /// This is important because every jiff::ZonedDateTime has a TimeZone
4174 /// inside of it, and we want to keep its size as small as we can.
4175 #[test]
4176 fn time_zone_size() {
4177 #[cfg(feature = "alloc")]
4178 {
4179 let word = core::mem::size_of::<usize>();
4180 assert_eq!(word, core::mem::size_of::<TimeZone>());
4181 }
4182 #[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
4183 {
4184 #[cfg(debug_assertions)]
4185 {
4186 assert_eq!(8, core::mem::size_of::<TimeZone>());
4187 }
4188 #[cfg(not(debug_assertions))]
4189 {
4190 // This asserts the same value as the alloc value above, but
4191 // it wasn't always this way, which is why it's written out
4192 // separately. Moreover, in theory, I'd be open to regressing
4193 // this value if it led to an improvement in alloc-mode. But
4194 // more likely, it would be nice to decrease this size in
4195 // non-alloc modes.
4196 assert_eq!(8, core::mem::size_of::<TimeZone>());
4197 }
4198 }
4199 }
4200
4201 /// This tests a few other cases for `TimeZone::to_offset` that
4202 /// probably aren't worth showing in doctest examples.
4203 #[test]
4204 fn time_zone_to_offset() {
4205 let ts = Timestamp::from_second(123456789).unwrap();
4206
4207 let tz = TimeZone::fixed(offset(-5));
4208 let info = tz.to_offset_info(ts);
4209 assert_eq!(info.offset(), offset(-5));
4210 assert_eq!(info.dst(), Dst::No);
4211 assert_eq!(info.abbreviation(), "-05");
4212
4213 let tz = TimeZone::fixed(offset(5));
4214 let info = tz.to_offset_info(ts);
4215 assert_eq!(info.offset(), offset(5));
4216 assert_eq!(info.dst(), Dst::No);
4217 assert_eq!(info.abbreviation(), "+05");
4218
4219 let tz = TimeZone::fixed(offset(-12));
4220 let info = tz.to_offset_info(ts);
4221 assert_eq!(info.offset(), offset(-12));
4222 assert_eq!(info.dst(), Dst::No);
4223 assert_eq!(info.abbreviation(), "-12");
4224
4225 let tz = TimeZone::fixed(offset(12));
4226 let info = tz.to_offset_info(ts);
4227 assert_eq!(info.offset(), offset(12));
4228 assert_eq!(info.dst(), Dst::No);
4229 assert_eq!(info.abbreviation(), "+12");
4230
4231 let tz = TimeZone::fixed(offset(0));
4232 let info = tz.to_offset_info(ts);
4233 assert_eq!(info.offset(), offset(0));
4234 assert_eq!(info.dst(), Dst::No);
4235 assert_eq!(info.abbreviation(), "UTC");
4236 }
4237
4238 /// This tests a few other cases for `TimeZone::to_fixed_offset` that
4239 /// probably aren't worth showing in doctest examples.
4240 #[test]
4241 fn time_zone_to_fixed_offset() {
4242 let tz = TimeZone::UTC;
4243 assert_eq!(tz.to_fixed_offset().unwrap(), Offset::UTC);
4244
4245 let offset = Offset::from_hours(1).unwrap();
4246 let tz = TimeZone::fixed(offset);
4247 assert_eq!(tz.to_fixed_offset().unwrap(), offset);
4248
4249 #[cfg(feature = "alloc")]
4250 {
4251 let tz = TimeZone::posix("EST5").unwrap();
4252 assert!(tz.to_fixed_offset().is_err());
4253
4254 let test_file = TzifTestFile::get("America/New_York");
4255 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4256 assert!(tz.to_fixed_offset().is_err());
4257 }
4258 }
4259
4260 /// This tests that `TimeZone::following` correctly returns a final time
4261 /// zone transition.
4262 #[cfg(feature = "alloc")]
4263 #[test]
4264 fn time_zone_following_boa_vista() {
4265 use alloc::{vec, vec::Vec};
4266
4267 let test_file = TzifTestFile::get("America/Boa_Vista");
4268 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4269 let last4: Vec<Timestamp> = vec![
4270 "1999-10-03T04Z".parse().unwrap(),
4271 "2000-02-27T03Z".parse().unwrap(),
4272 "2000-10-08T04Z".parse().unwrap(),
4273 "2000-10-15T03Z".parse().unwrap(),
4274 ];
4275
4276 let start: Timestamp = "2001-01-01T00Z".parse().unwrap();
4277 let mut transitions: Vec<Timestamp> =
4278 tz.preceding(start).take(4).map(|t| t.timestamp()).collect();
4279 transitions.reverse();
4280 assert_eq!(transitions, last4);
4281
4282 let start: Timestamp = "1990-01-01T00Z".parse().unwrap();
4283 let transitions: Vec<Timestamp> =
4284 tz.following(start).map(|t| t.timestamp()).collect();
4285 // The regression here was that the 2000-10-15 transition wasn't
4286 // being found here, despite the fact that it existed and was found
4287 // by `preceding`.
4288 assert_eq!(transitions, last4);
4289 }
4290
4291 /// This tests that `TimeZone::following` stops after the last time zone
4292 /// transition when there is no POSIX TZ string to defer to.
4293 #[cfg(feature = "alloc")]
4294 #[test]
4295 fn time_zone_following_no_posix_tz() {
4296 use alloc::{vec, vec::Vec};
4297
4298 let test_file = TzifTestFile::get("America/Boa_Vista");
4299 // Parse this as V1 data, which has no POSIX TZ footer.
4300 let mut data = test_file.data.to_vec();
4301 data[4] = 0;
4302 let tz = TimeZone::tzif(test_file.name, &data).unwrap();
4303 let last4: Vec<Timestamp> = vec![
4304 "1999-10-03T04Z".parse().unwrap(),
4305 "2000-02-27T03Z".parse().unwrap(),
4306 "2000-10-08T04Z".parse().unwrap(),
4307 "2000-10-15T03Z".parse().unwrap(),
4308 ];
4309
4310 let start: Timestamp = "2001-01-01T00Z".parse().unwrap();
4311 let mut transitions: Vec<Timestamp> =
4312 tz.preceding(start).take(4).map(|t| t.timestamp()).collect();
4313 transitions.reverse();
4314 assert_eq!(transitions, last4);
4315
4316 let start: Timestamp = "1999-01-01T00Z".parse().unwrap();
4317 // The regression here was that the last transition was returned
4318 // forever, so bound the iterator to make this fail instead of hang.
4319 let transitions: Vec<Timestamp> =
4320 tz.following(start).take(5).map(|t| t.timestamp()).collect();
4321 assert_eq!(transitions, last4);
4322
4323 // With no transitions at all, the dummy first transition was
4324 // returned forever.
4325 let test_file = TzifTestFile::get("UTC");
4326 let mut data = test_file.data.to_vec();
4327 data[4] = 0;
4328 let tz = TimeZone::tzif(test_file.name, &data).unwrap();
4329 assert_eq!(tz.following(start).take(1).count(), 0);
4330 }
4331
4332 #[cfg(feature = "alloc")]
4333 #[test]
4334 fn regression_tzif_parse_panic() {
4335 _ = TimeZone::tzif(
4336 "",
4337 &[
4338 84, 90, 105, 102, 6, 0, 5, 35, 84, 10, 77, 0, 0, 0, 84, 82,
4339 105, 102, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4340 0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 82, 28, 77, 0, 0, 90, 105,
4341 78, 0, 0, 0, 0, 0, 0, 0, 84, 90, 105, 102, 0, 0, 5, 0, 84, 90,
4342 105, 84, 77, 10, 0, 0, 0, 15, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4343 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 82, 0, 64, 1, 0,
4344 0, 2, 0, 0, 0, 0, 0, 0, 126, 1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,
4345 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 0, 0,
4346 0, 160, 109, 1, 0, 90, 105, 102, 0, 0, 5, 0, 87, 90, 105, 84,
4347 77, 10, 0, 0, 0, 0, 0, 122, 102, 105, 0, 0, 0, 0, 0, 0, 0, 0,
4348 2, 0, 0, 0, 0, 0, 0, 5, 82, 0, 0, 0, 0, 0, 2, 0, 0, 90, 105,
4349 102, 0, 0, 5, 0, 84, 90, 105, 84, 77, 10, 0, 0, 0, 102, 0, 0,
4350 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 90, 195, 190, 10, 84,
4351 90, 77, 49, 84, 90, 105, 102, 49, 44, 74, 51, 44, 50, 10,
4352 ],
4353 );
4354 }
4355
4356 /// A regression test where a TZ lookup for the minimum civil datetime
4357 /// resulted in a panic in the TZif handling.
4358 #[cfg(feature = "alloc")]
4359 #[test]
4360 fn regression_tz_lookup_datetime_min() {
4361 use alloc::string::ToString;
4362
4363 let test_file = TzifTestFile::get("America/Boa_Vista");
4364 let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4365 let err = tz.to_timestamp(DateTime::MIN).unwrap_err();
4366 assert_eq!(
4367 err.to_string(),
4368 "converting datetime with time zone offset `-04:02:40` to timestamp overflowed: parameter 'Unix timestamp seconds' is not in the required range of -377705023201..=253402207200",
4369 );
4370 }
4371}