Skip to main content

jiff/tz/
mod.rs

1/*!
2Routines for interacting with time zones and the zoneinfo database.
3
4The main type in this module is [`TimeZone`]. For most use cases, you may not
5even need to interact with this type at all. For example, this code snippet
6converts a civil datetime to a zone aware datetime:
7
8```
9use jiff::civil::date;
10
11let zdt = date(2024, 7, 10).at(20, 48, 0, 0).in_tz("America/New_York")?;
12assert_eq!(zdt.to_string(), "2024-07-10T20:48:00-04:00[America/New_York]");
13
14# Ok::<(), Box<dyn std::error::Error>>(())
15```
16
17And this example parses a zone aware datetime from a string:
18
19```
20use jiff::ZonedDateTime;
21
22let zdt: ZonedDateTime = "2024-07-10 20:48[america/new_york]".parse()?;
23assert_eq!(zdt.year(), 2024);
24assert_eq!(zdt.month(), 7);
25assert_eq!(zdt.day(), 10);
26assert_eq!(zdt.hour(), 20);
27assert_eq!(zdt.minute(), 48);
28assert_eq!(zdt.offset().seconds(), -4 * 60 * 60);
29assert_eq!(zdt.time_zone().iana_name(), Some("America/New_York"));
30
31# Ok::<(), Box<dyn std::error::Error>>(())
32```
33
34Yet, neither of the above examples require uttering [`TimeZone`]. This is
35because the datetime types in this crate provide higher level abstractions for
36working with time zone identifiers. Nevertheless, sometimes it is useful to
37work with a `TimeZone` directly. For example, if one has a `TimeZone`, then
38conversion from a [`Timestamp`](crate::Timestamp) to a
39[`ZonedDateTime`](crate::ZonedDateTime) is infallible:
40
41```
42use jiff::{tz::TimeZone, Timestamp};
43
44let tz = TimeZone::get("America/New_York")?;
45let ts = Timestamp::UNIX_EPOCH;
46let zdt = ts.to_zoned_datetime(tz);
47assert_eq!(zdt.to_string(), "1969-12-31T19:00:00-05:00[America/New_York]");
48
49# Ok::<(), Box<dyn std::error::Error>>(())
50```
51
52# The [IANA Time Zone Database]
53
54Since a time zone is a set of rules for determining the civil time, via an
55offset from UTC, in a particular geographic region, a database is required to
56represent the full complexity of these rules in practice. The standard database
57is widespread use is the [IANA Time Zone Database]. On Unix systems, this is
58typically found at `/usr/share/zoneinfo`, and Jiff will read it automatically.
59On Windows systems, there is no canonical Time Zone Database installation, and
60so Jiff embeds it into the compiled artifact. (This does not happen on Unix
61by default.)
62
63See the [`TimeZoneDatabase`] for more information.
64
65# The system or "local" time zone
66
67In many cases, the operating system manages a "default" time zone. It might,
68for example, be how the `date` program converts a Unix timestamp to a time that
69is "local" to you.
70
71Unfortunately, there is no universal approach to discovering a system's default
72time zone. Instead, Jiff uses heuristics like reading `/etc/localtime` on Unix,
73and calling [`GetDynamicTimeZoneInformation`] on Windows. But in all cases,
74Jiff will always use the IANA Time Zone Database for implementing time zone
75transition rules. (For example, Windows specific APIs for time zone transitions
76are not supported by Jiff.)
77
78Moreover, Jiff supports reading the `TZ` environment variable, as specified
79by POSIX, on all systems.
80
81To get the system's default time zone, use [`TimeZone::system`].
82
83# Core-only environments
84
85By default, Jiff attempts to read time zone rules from `/usr/share/zoneinfo`
86on Unix and a bundled database on other platforms (like on Windows). This happens
87at runtime, and aside from requiring APIs to interact with the file system
88on Unix, it also requires dynamic memory allocation.
89
90For core-only environments that don't have file system APIs or dynamic
91memory allocation, Jiff provides a way to construct `TimeZone` values at
92compile time by compiling time zone rules into your binary. This does mean
93that your program will need to be re-compiled if the time zone rules change
94(in contrast to Jiff's default behavior of reading `/usr/share/zoneinfo` at
95runtime on Unix), but sometimes there isn't a practical alternative.
96
97With the `static` crate feature enabled, the [`jiff::tz::get`](crate::tz::get)
98macro becomes available in this module. This example shows how use it to build
99a `TimeZone` at compile time. Here, we find the next DST transition from a
100particular timestamp in `Europe/Zurich`, and then print that in local time for
101Zurich:
102
103```
104use jiff::{tz::{self, TimeZone}, Timestamp};
105
106static TZ: TimeZone = tz::get!("Europe/Zurich");
107
108let ts: Timestamp = "2025-02-25T00:00Z".parse()?;
109let Some(next_transition) = TZ.following(ts).next() else {
110    return Err("no time zone transitions".into());
111};
112let zdt = next_transition.timestamp().to_zoned_datetime(TZ.clone());
113assert_eq!(zdt.to_string(), "2025-03-30T03:00:00+02:00[Europe/Zurich]");
114
115# Ok::<(), Box<dyn std::error::Error>>(())
116```
117
118The above example does not require dynamic memory allocation or access to file
119system APIs. It also _only_ embeds the `Europe/Zurich` time zone into your
120compiled binary.
121
122[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
123[`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
124*/
125
126pub use self::{
127    ambiguous::{
128        AmbiguousOffset, AmbiguousTimestamp, AmbiguousZonedDateTime,
129        Disambiguation,
130    },
131    db::{
132        TimeZoneDatabase, TimeZoneLocation, TimeZoneName, TimeZoneNameIter, db,
133    },
134    offset::{Dst, Offset, OffsetArithmetic, OffsetConflict, OffsetRound},
135    timezone::{
136        TimeZone, TimeZoneFollowingTransitions, TimeZoneOffsetInfo,
137        TimeZonePrecedingTransitions, TimeZoneTransition,
138    },
139};
140
141mod ambiguous;
142#[cfg(feature = "tzdb-concatenated")]
143mod concatenated;
144mod db;
145mod offset;
146pub(crate) mod posix;
147#[cfg(feature = "tz-system")]
148mod system;
149#[cfg(all(test, feature = "alloc"))]
150pub(crate) mod testdata;
151mod timezone;
152mod tzif;
153// See module comment for WIP status. :-(
154#[cfg(all(test, feature = "alloc"))]
155mod zic;
156
157/// Create a `TimeZone` value from TZif data in [`jiff-tzdb`] at compile time.
158///
159/// This reads the data for the time zone with the IANA identifier given from
160/// [`jiff-tzdb`], parses it as TZif specified by [RFC 9636], and constructs a
161/// `TimeZone` value for use in a `const` context. This enables using IANA time
162/// zones with Jiff in core-only environments. No dynamic memory allocation is
163/// used.
164///
165/// # Input
166///
167/// This macro takes one positional parameter that must be a literal string.
168/// The string should be an IANA time zone identifier, e.g.,
169/// `America/New_York`.
170///
171/// # Return type
172///
173/// This macro returns a value with type `TimeZone`. To get a `&'static
174/// TimeZone`, simply use `&get!("...")`.
175///
176/// # Usage
177///
178/// Callers should only call this macro once for each unique IANA time zone
179/// identifier you need. Otherwise, multiple copies of the same embedded
180/// time zone data could appear in your binary. There are no correctness
181/// issues with this, but it could make your binary bigger than it needs to be.
182///
183/// # When should I use this?
184///
185/// Users should only use this macro if they have a _specific need_ for it
186/// (like using a time zone on an embedded device). In particular, this will
187/// embed the time zone transition rules into your binary. If the time zone
188/// rules change, your program will need to be re-compiled.
189///
190/// In contrast, Jiff's default configuration on Unix is to read from
191/// `/usr/share/zoneinfo` at runtime. This means your application will
192/// automatically use time zone updates and doesn't need to be re-compiled.
193///
194/// Using a static `TimeZone` may also be faster in some cases. In particular,
195/// a `TimeZone` created at runtime from a `/usr/share/zoneinfo` uses
196/// automatic reference counting internally. In contrast, a `TimeZone` created
197/// with this macro does not.
198///
199/// # Example
200///
201/// This example shows how to find the next DST transition from a particular
202/// timestamp in `Europe/Zurich`, and then print that in local time for Zurich:
203///
204/// ```
205/// use jiff::{tz::{self, TimeZone}, Timestamp};
206///
207/// static TZ: TimeZone = tz::get!("Europe/Zurich");
208///
209/// let ts: Timestamp = "2025-02-25T00:00Z".parse()?;
210/// let Some(next_transition) = TZ.following(ts).next() else {
211///     return Err("no time zone transitions".into());
212/// };
213/// let zdt = next_transition.timestamp().to_zoned_datetime(TZ.clone());
214/// assert_eq!(zdt.to_string(), "2025-03-30T03:00:00+02:00[Europe/Zurich]");
215///
216/// # Ok::<(), Box<dyn std::error::Error>>(())
217/// ```
218///
219/// [RFC 9636]: https://datatracker.ietf.org/doc/rfc9636/
220/// [`jiff-tzdb`]: https://docs.rs/jiff-tzdb
221#[cfg(feature = "static")]
222pub use jiff_static::get;
223
224/// Create a `TimeZone` value from TZif data in a file at compile time.
225///
226/// This reads the data in the file path given, parses it as TZif specified by
227/// [RFC 9636], and constructs a `TimeZone` value for use in a `const` context.
228/// This enables using IANA time zones with Jiff in core-only environments. No
229/// dynamic memory allocation is used.
230///
231/// Unlike [`jiff::tz::get`](get), this reads TZif data from a file.
232/// `jiff::tz::get`, in contrast, reads TZif data from the [`jiff-tzdb`] crate.
233/// `jiff::tz::get` is more convenient and doesn't require managing your own
234/// TZif files, but it comes at the cost of a compile-time dependency on
235/// `jiff-tzdb` and being forced to use whatever data is in `jiff-tzdb`.
236///
237/// # Input
238///
239/// This macro takes two positional parameters that must be literal strings.
240///
241/// The first is required and is a path to a file containing TZif data. For
242/// example, `/usr/share/zoneinfo/America/New_York`.
243///
244/// The second parameter is an IANA time zone identifier, e.g.,
245/// `America/New_York`, and is required only when an IANA time zone identifier
246/// could not be determined from the file path. The macro will automatically
247/// infer an IANA time zone identifier as anything after the last occurrence
248/// of the literal `zoneinfo/` in the file path.
249///
250/// # Return type
251///
252/// This macro returns a value with type `TimeZone`. To get a `&'static
253/// TimeZone`, simply use `&include!("...")`.
254///
255/// # Usage
256///
257/// Callers should only call this macro once for each unique IANA time zone
258/// identifier you need. Otherwise, multiple copies of the same embedded
259/// time zone data could appear in your binary. There are no correctness
260/// issues with this, but it could make your binary bigger than it needs to be.
261///
262/// # When should I use this?
263///
264/// Users should only use this macro if they have a _specific need_ for it
265/// (like using a time zone on an embedded device). In particular, this will
266/// embed the time zone transition rules into your binary. If the time zone
267/// rules change, your program will need to be re-compiled.
268///
269/// In contrast, Jiff's default configuration on Unix is to read from
270/// `/usr/share/zoneinfo` at runtime. This means your application will
271/// automatically use time zone updates and doesn't need to be re-compiled.
272///
273/// Using a static `TimeZone` may also be faster in some cases. In particular,
274/// a `TimeZone` created at runtime from a `/usr/share/zoneinfo` uses
275/// automatic reference counting internally. In contrast, a `TimeZone` created
276/// with this macro does not.
277///
278/// # Example
279///
280/// This example shows how to find the next DST transition from a particular
281/// timestamp in `Europe/Zurich`, and then print that in local time for Zurich:
282///
283/// ```ignore
284/// use jiff::{tz::{self, TimeZone}, Timestamp};
285///
286/// static TZ: TimeZone = tz::include!("/usr/share/zoneinfo/Europe/Zurich");
287///
288/// let ts: Timestamp = "2025-02-25T00:00Z".parse()?;
289/// let Some(next_transition) = TZ.following(ts).next() else {
290///     return Err("no time zone transitions".into());
291/// };
292/// let zdt = next_transition.timestamp().to_zoned_datetime(TZ.clone());
293/// assert_eq!(zdt.to_string(), "2025-03-30T03:00:00+02:00[Europe/Zurich]");
294///
295/// # Ok::<(), Box<dyn std::error::Error>>(())
296/// ```
297///
298/// # Example: using `/etc/localtime`
299///
300/// On most Unix systems, `/etc/localtime` is a symbolic link to a file in
301/// your `/usr/share/zoneinfo` directory. This means it is a valid input to
302/// this macro. However, Jiff currently does not detect the IANA time zone
303/// identifier, so you'll need to provide it yourself:
304///
305/// ```ignore
306/// use jiff::{tz::{self, TimeZone}, Timestamp};
307///
308/// static TZ: TimeZone = tz::include!("/etc/localtime", "America/New_York");
309///
310/// let ts: Timestamp = "2025-02-25T00:00Z".parse()?;
311/// let zdt = ts.to_zoned_datetime(TZ.clone());
312/// assert_eq!(zdt.to_string(), "2025-02-24T19:00:00-05:00[America/New_York]");
313///
314/// # Ok::<(), Box<dyn std::error::Error>>(())
315/// ```
316///
317/// Note that this is reading `/etc/localtime` _at compile time_, which means
318/// that the program will only use the time zone on the system in which it
319/// was compiled. It will _not_ use the time zone of the system running it.
320///
321/// [RFC 9636]: https://datatracker.ietf.org/doc/rfc9636/
322/// [`jiff-tzdb`]: https://docs.rs/jiff-tzdb
323#[cfg(feature = "static-tz")]
324pub use jiff_static::include;
325
326/// Creates a new time zone offset in a `const` context from a given number
327/// of hours.
328///
329/// Negative offsets correspond to time zones west of the prime meridian,
330/// while positive offsets correspond to time zones east of the prime
331/// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
332///
333/// The fallible non-const version of this constructor is
334/// [`Offset::from_hours`].
335///
336/// This is a convenience free function for [`Offset::constant`]. It is
337/// intended to provide a terse syntax for constructing `Offset` values from
338/// a value that is known to be valid.
339///
340/// # Panics
341///
342/// This routine panics when the given number of hours is out of range.
343/// Namely, `hours` must be in the range `-25..=25`.
344///
345/// Similarly, when used in a const context, an out of bounds hour will prevent
346/// your Rust program from compiling.
347///
348/// # Example
349///
350/// ```
351/// use jiff::tz::offset;
352///
353/// let o = offset(-5);
354/// assert_eq!(o.seconds(), -18_000);
355/// let o = offset(5);
356/// assert_eq!(o.seconds(), 18_000);
357/// ```
358#[inline]
359pub const fn offset(hours: i8) -> Offset {
360    Offset::constant(hours)
361}
362
363/// Resets Jiff's internal and global cache for this system's configured time
364/// zone.
365///
366/// The next request for the system time zone will be forced to re-fetch it.
367///
368/// It might be useful to call this if you believe the system time zone has
369/// changed and you don't want to wait for the cache to clear after Jiff's
370/// internal expiration has elapsed.
371///
372/// This has no effect when the `tz-system` crate feature is not enabled.
373pub fn reset_system_time_zone_cache() {
374    #[cfg(feature = "tz-system")]
375    {
376        crate::tz::system::reset();
377    }
378}