1/*!
2Jiff is a datetime library for Rust that encourages you to jump into the pit
3of success. The focus of this library is providing high level datetime
4primitives that are difficult to misuse and have reasonable performance.
56Jiff takes enormous inspiration from [Temporal], which is a [TC39] proposal to
7improve datetime handling in JavaScript.
89Here is a quick example that shows how to parse a typical RFC 3339 instant,
10convert it to a zone aware datetime, add a span of time and losslessly print
11it:
1213```
14use jiff::{Timestamp, ToSpan};
1516let time: Timestamp = "2024-07-11T01:14:00Z".parse()?;
17let zoned = time.in_tz("America/New_York")?.checked_add(1.month().hours(2))?;
18assert_eq!(zoned.to_string(), "2024-08-10T23:14:00-04:00[America/New_York]");
19// Or, if you want an RFC3339 formatted string:
20assert_eq!(zoned.timestamp().to_string(), "2024-08-11T03:14:00Z");
2122# Ok::<(), Box<dyn std::error::Error>>(())
23```
2425[TC39]: https://tc39.es/
26[Temporal]: https://tc39.es/proposal-temporal/docs/index.html
2728# Overview
2930The primary type in this crate is [`ZonedDateTime`]. A `ZonedDateTime` value is
31a datetime that corresponds to a precise instant in time in a particular
32geographic region. Users of this crate may find it helpful to think of a
33`ZonedDateTime` as a triple of the following components:
3435* A [`Timestamp`] is a 96-bit integer of nanoseconds since the [Unix epoch].
36A timestamp is a precise instant in time.
37* A [`civil::DateTime`] is an inexact calendar date and clock time in the
38proleptic Gregorian calendar. The terms "civil", "local", "plain" and "naive"
39are all used in various places to describe this same concept.
40* A [`tz::TimeZone`] is a set of rules for determining the civil time, via an
41offset from [UTC], in a particular geographic region.
4243All three of these components are used to provide convenient high level
44operations on `ZonedDateTime` such as computing durations, adding durations and
45rounding.
4647A [`Span`] is this crate's primary duration type. It mixes calendar and clock
48units into a single type. Jiff also provides [`SignedDuration`], which is like
49[`std::time::Duration`], but signed. Users should default to a `Span` for
50representing durations when using Jiff.
5152[Unix epoch]: https://en.wikipedia.org/wiki/Unix_time
53[UTC]: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
5455The remainder of this documentation is organized as follows:
5657* [Features](#features) gives a very brief summary of the features Jiff does
58and does not support.
59* [Usage](#usage) shows how to add Jiff to your Rust project.
60* [Examples](#examples) shows a small cookbook of programs for common tasks.
61* [Crate features](#crate-features) documents the Cargo features that can be
62enabled or disabled for this crate.
6364Also, the `_documentation` sub-module serves to provide longer form
65documentation:
6667* [Comparison with other Rust datetime crates](crate::_documentation::comparison)
68* [The API design rationale for Jiff](crate::_documentation::design)
69* [Platform support](crate::_documentation::platform)
70* [CHANGELOG](crate::_documentation::changelog)
7172# Features
7374Here is a non-exhaustive list of the things that Jiff supports:
7576* Automatic and seamless integration with your system's copy of the
77[IANA Time Zone Database]. When a platform doesn't have a time zone database,
78Jiff automatically embeds a copy of it.
79* A separation of datetime types between absolute times ([`Timestamp`] and
80[`ZonedDateTime`]) and civil times ([`civil::DateTime`]).
81* Nanosecond precision.
82* Time zone and daylight saving time aware arithmetic.
83* The primary duration type, [`Span`], mixes calendar and clock
84units to provide an all-in-one human friendly experience that is time zone
85aware.
86* An "absolute" duration type, [`SignedDuration`], is like
87[`std::time::Duration`] but signed.
88* Datetime rounding.
89* Span rounding, including calendar units and including taking time zones into
90account.
91* Formatting and parsing datetimes via a Temporal-specified hybrid format
92that takes the best parts of [RFC 3339], [RFC 9557] and [ISO 8601]. This
93includes lossless round tripping of IANA time zone aware datetimes and
94durations.
95* Formatting and parsing according to [RFC 2822].
96* Formatting and parsing via routines similar to [`strftime`] and [`strptime`].
97* Formatting and parsing durations via a bespoke
98["friendly" format](crate::fmt::friendly), with Serde support, that is meant
99to service the [`humantime`](https://docs.rs/humantime) use cases.
100* Opt-in Serde integration.
101* Full support for dealing with ambiguous civil datetimes.
102* Protection against deserializing datetimes in the future with an offset
103different than what is possible with your copy of the Time Zone Database.
104(This is done via [`tz::OffsetConflict`].)
105* APIs that panic by design are clearly documented as such and few in number.
106Otherwise, all operations that can fail, including because of overflow,
107return a `Result`.
108109Here is also a list of things that Jiff doesn't currently support, along with
110a link to a relevant issue (if one exists).
111112* [Leap seconds]. (Jiff will automatically constrain times like `23:59:60` to
113`23:59:59`.)
114* Time scales other than Unix.
115* [Calendars other than the proleptic Gregorian calendar].
116* [Localization].
117* [Changing the representation size, precision or limits on the minimum and
118maximum datetime values.][cppchrono]
119* [Jiff aims to have reasonable performance and may not be capable of doing the
120fastest possible thing.][perf]
121122At present, it is recommended to use the [`icu`] crate via [`jiff-icu`] for
123localization and non-Gregorian use cases.
124125[Leap seconds]: https://github.com/BurntSushi/jiff/issues/7
126[Calendars other than the proleptic Gregorian calendar]: https://github.com/BurntSushi/jiff/issues/6
127[Localization]: https://github.com/BurntSushi/jiff/issues/4
128[cppchrono]: https://github.com/BurntSushi/jiff/issues/3
129[perf]: https://github.com/BurntSushi/jiff/issues/17
130[`icu`]: https://docs.rs/icu
131[`jiff-icu`]: https://docs.rs/jiff-icu
132133Please file an issue if you can think of more (substantial) things to add to
134the above list.
135136[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
137[RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339
138[RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html
139[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
140141# Usage
142143Jiff is [on crates.io](https://crates.io/crates/jiff) and can be
144used by adding `jiff` to your dependencies in your project's `Cargo.toml`.
145Or more simply, just run `cargo add jiff`.
146147Here is a complete example that creates a new Rust project, adds a dependency
148on `jiff`, creates the source code for a simple datetime program and then runs
149it.
150151First, create the project in a new directory:
152153```text
154$ cargo new jiff-example
155$ cd jiff-example
156```
157158Second, add a dependency on `jiff`:
159160```text
161$ cargo add jiff
162```
163164Third, edit `src/main.rs`. Delete what's there and replace it with this:
165166```
167use jiff::{Unit, ZonedDateTime};
168169fn main() -> Result<(), jiff::Error> {
170 let now = ZonedDateTime::now().round(Unit::Second)?;
171 println!("{now}");
172 Ok(())
173}
174```
175176Fourth, run it with `cargo run`:
177178```text
179$ cargo run
180 Compiling jiff v0.2.0 (/home/andrew/rust/jiff)
181 Compiling jiff-play v0.2.0 (/home/andrew/tmp/scratch/rust/jiff-play)
182 Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.37s
183 Running `target/debug/jiff-play`
1842024-07-10T19:54:20-04:00[America/New_York]
185```
186187The first time you run the program will show more output like above. But
188subsequent runs shouldn't have to re-compile the dependencies.
189190# Examples
191192* [Get the current time in your system's time zone](#get-the-current-time-in-your-systems-time-zone)
193* [Print the current time rounded to the nearest second](#print-the-current-time-rounded-to-the-nearest-second)
194* [Print today's date at a specific time](#print-todays-date-at-a-specific-time)
195* [Print the current Unix timestamp](#print-the-current-unix-timestamp)
196* [Print the datetime for a timestamp](#print-the-datetime-for-a-timestamp)
197* [Create a zoned datetime from civil time](#create-a-zoned-datetime-from-civil-time)
198* [Change an instant from one time zone to another](#change-an-instant-from-one-time-zone-to-another)
199* [Find the duration between two zoned datetimes](#find-the-duration-between-two-zoned-datetimes)
200* [Add a duration to a zoned datetime](#add-a-duration-to-a-zoned-datetime)
201* [Dealing with ambiguity](#dealing-with-ambiguity)
202* [Parsing a span](#parsing-a-span)
203* [Parsing an RFC 2822 datetime string](#parsing-an-rfc-2822-datetime-string)
204* [Using `strftime` and `strptime` for formatting and parsing](#using-strftime-and-strptime-for-formatting-and-parsing)
205* [Serializing and deserializing integer timestamps with Serde](#serializing-and-deserializing-integer-timestamps-with-serde)
206207### Get the current time in your system's time zone
208209The [`ZonedDateTime::now`] returns your system's time and also attempts
210to automatically find your system's default time zone via
211[`tz::TimeZone::system`]:
212213```
214use jiff::ZonedDateTime;
215216let now = ZonedDateTime::now();
217println!("{now}");
218// Output: 2024-07-10T17:09:28.168146054-04:00[America/New_York]
219```
220221### Print the current time rounded to the nearest second
222223This uses the [`ZonedDateTime::round`] API to round a zoned datetime to the
224nearest second. This is useful, for example, if you don't care about fractional
225seconds:
226227```
228use jiff::{Unit, ZonedDateTime};
229230let now = ZonedDateTime::now().round(Unit::Second)?;
231println!("{now}");
232// Output: 2024-07-10T17:09:28-04:00[America/New_York]
233# Ok::<(), Box<dyn std::error::Error>>(())
234```
235236### Print today's date at a specific time
237238Let's say you want to get the current date at 2pm. Here's one way of doing it
239that makes use of [`ZonedDateTime::with`]:
240241```
242use jiff::ZonedDateTime;
243244let zdt = ZonedDateTime::now().with()
245 .hour(14)
246 .minute(0)
247 .second(0)
248 .subsec_nanosecond(0)
249 .build()?;
250println!("{zdt}");
251// Output: 2024-07-12T14:00:00-04:00[America/New_York]
252# Ok::<(), Box<dyn std::error::Error>>(())
253```
254255Or, if the time is known to be valid, you can use the infallible
256[`civil::time`](civil::time()) convenience constructor:
257258```
259use jiff::{civil::time, ZonedDateTime};
260261let zdt = ZonedDateTime::now().with().time(time(14, 0, 0, 0)).build()?;
262println!("{zdt}");
263// Output: 2024-07-12T14:00:00-04:00[America/New_York]
264# Ok::<(), Box<dyn std::error::Error>>(())
265```
266267You can eliminate the possibility of a panic at runtime by using `time` in
268a `const` block:
269270```
271use jiff::{ZonedDateTime, civil::time};
272273let zdt =
274 ZonedDateTime::now().with().time(const { time(14, 0, 0, 0) }).build()?;
275println!("{zdt}");
276// Output: 2024-07-12T14:00:00-04:00[America/New_York]
277# Ok::<(), Box<dyn std::error::Error>>(())
278```
279280### Print the current Unix timestamp
281282This prints a Unix timestamp as the number of seconds since the Unix epoch
283via [`Timestamp::now`]:
284285```
286use jiff::Timestamp;
287288let now = Timestamp::now();
289println!("{}", now.as_second());
290// Output: 1720646365
291```
292293Or print the current timestamp to nanosecond precision (which is the maximum
294supported by Jiff):
295296```
297use jiff::Timestamp;
298299let now = Timestamp::now();
300println!("{}", now.as_nanosecond());
301// Output: 1720646414218901664
302```
303304### Print the datetime for a timestamp
305306This example shows how to convert a Unix timestamp, in milliseconds, to a zoned
307datetime in the system's current time zone. This utilizes the
308[`Timestamp::from_millisecond`] constructor, [`tz::TimeZone::system`] to get
309the default time zone and the [`Timestamp::to_zoned_datetime`] routine to
310convert a timestamp to a zoned datetime.
311312```
313use jiff::{tz::TimeZone, Timestamp};
314315let ts = Timestamp::from_millisecond(1_720_646_365_567)?;
316let zdt = ts.to_zoned_datetime(TimeZone::system());
317println!("{zdt}");
318// Output: 2024-07-10T17:19:25.567-04:00[America/New_York]
319// Or if you just want the RFC 3339 time without bothering with time zones:
320assert_eq!(ts.to_string(), "2024-07-10T21:19:25.567Z");
321322# Ok::<(), Box<dyn std::error::Error>>(())
323```
324325### Create a zoned datetime from civil time
326327This example demonstrates the convenience constructor, [`civil::date`],
328for a [`civil::Date`]. And use the [`civil::Date::at`] method to create
329a [`civil::DateTime`]. Once we have a civil datetime, we can use
330[`civil::DateTime::in_tz`] to do a time zone lookup and convert it to a precise
331instant in time:
332333```
334use jiff::civil::date;
335336let zdt = date(2023, 12, 31).at(18, 30, 0, 0).in_tz("America/New_York")?;
337assert_eq!(zdt.to_string(), "2023-12-31T18:30:00-05:00[America/New_York]");
338339# Ok::<(), Box<dyn std::error::Error>>(())
340```
341342Note that [`civil::date`] should only be used for inputs that are known to be
343correct since it panics for an invalid date. If your date isn't known to be
344valid, then use the fallible [`civil::Date::new`] constructor.
345346### Change an instant from one time zone to another
347348This shows how to find the civil time, in New York, when World War 1 ended:
349350```
351use jiff::civil::date;
352353let zdt1 = date(1918, 11, 11).at(11, 0, 0, 0).in_tz("Europe/Paris")?;
354let zdt2 = zdt1.in_tz("America/New_York")?;
355assert_eq!(
356 zdt2.to_string(),
357 "1918-11-11T06:00:00-05:00[America/New_York]",
358);
359360# Ok::<(), Box<dyn std::error::Error>>(())
361```
362363### Find the duration between two zoned datetimes
364365This shows how to compute a span between two zoned datetimes. This utilizes a
366[`ZonedDateTime`]'s implementation for `Sub`, permitting one to subtract two
367zoned datetimes via the `-` operator:
368369```
370use jiff::civil::date;
371372let zdt1 = date(2020, 8, 26).at(6, 27, 0, 0).in_tz("America/New_York")?;
373let zdt2 = date(2023, 12, 31).at(18, 30, 0, 0).in_tz("America/New_York")?;
374let span = zdt2 - zdt1;
375assert_eq!(format!("{span:#}"), "29341h 3m");
376377# Ok::<(), Box<dyn std::error::Error>>(())
378```
379380The above returns no units bigger than hours because it makes the operation
381reversible in all cases. But if you don't need reversibility (i.e., adding the
382span returned to `zdt1` gives you `zdt2`), then you can ask for bigger units
383via [`ZonedDateTime::until`] to make the span more comprehensible:
384385```
386use jiff::{civil::date, Unit};
387388let zdt1 = date(2020, 8, 26).at(6, 27, 0, 0).in_tz("America/New_York")?;
389let zdt2 = date(2023, 12, 31).at(18, 30, 0, 0).in_tz("America/New_York")?;
390let span = zdt1.until((Unit::Year, &zdt2))?;
391assert_eq!(format!("{span:#}"), "3y 4mo 5d 12h 3m");
392393# Ok::<(), Box<dyn std::error::Error>>(())
394```
395396### Add a duration to a zoned datetime
397398This example shows how one can add a [`Span`] to a [`ZonedDateTime`] via
399[`ZonedDateTime::checked_add`] to get a new `ZonedDateTime` value. We utilize
400the [`ToSpan`] trait for convenience construction of `Span` values.
401402```
403use jiff::{civil::date, ToSpan};
404405let zdt1 = date(2020, 8, 26).at(6, 27, 0, 0).in_tz("America/New_York")?;
406let span = 3.years().months(4).days(5).hours(12).minutes(3);
407let zdt2 = zdt1.checked_add(span)?;
408assert_eq!(zdt2.to_string(), "2023-12-31T18:30:00-05:00[America/New_York]");
409410# Ok::<(), Box<dyn std::error::Error>>(())
411```
412413As with [`civil::date`], the [`ToSpan`] trait should only be used with inputs
414that are known to be valid. If you aren't sure whether the inputs are valid,
415then use [`Span::new`] and its fallible mutators like [`Span::try_years`].
416417### Dealing with ambiguity
418419In some cases, civil datetimes either don't exist in a particular time zone or
420are repeated. By default, Jiff automatically uses the
421[`tz::Disambiguation::Compatible`] strategy for choosing an instant in all
422cases:
423424```
425use jiff::civil::date;
426427// 2:30 on 2024-03-10 in New York didn't exist. It's a "gap."
428// The compatible strategy selects the datetime after the gap.
429let zdt = date(2024, 3, 10).at(2, 30, 0, 0).in_tz("America/New_York")?;
430assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
431432// 1:30 on 2024-11-03 in New York appeared twice. It's a "fold."
433// The compatible strategy selects the datetime before the fold.
434let zdt = date(2024, 11, 3).at(1, 30, 0, 0).in_tz("America/New_York")?;
435assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
436437# Ok::<(), Box<dyn std::error::Error>>(())
438```
439440For more control over disambiguation, see
441[`tz::TimeZone::to_ambiguous_zoned_datetime`]. Or
442[`fmt::temporal::DateTimeParser::disambiguation`]
443if you're parsing zoned datetimes.
444445### Parsing a span
446447Jiff supports parsing ISO 8601 duration strings:
448449```
450use jiff::Span;
451452let span: Span = "P5y1w10dT5h59m".parse()?;
453let expected = Span::new().years(5).weeks(1).days(10).hours(5).minutes(59);
454assert_eq!(span, expected.fieldwise());
455456# Ok::<(), Box<dyn std::error::Error>>(())
457```
458459The same format is used for serializing and deserializing `Span` values when
460the `serde` feature is enabled.
461462Jiff also supports a bespoke ["friendly" format](crate::fmt::friendly) as
463well:
464465```
466use jiff::Span;
467468let expected = Span::new().years(5).weeks(1).days(10).hours(5).minutes(59);
469let span: Span = "5 years, 1 week, 10 days, 5 hours, 59 minutes".parse()?;
470assert_eq!(span, expected.fieldwise());
471let span: Span = "5yrs 1wk 10d 5hrs 59mins".parse()?;
472assert_eq!(span, expected.fieldwise());
473let span: Span = "5y 1w 10d 5h 59m".parse()?;
474assert_eq!(span, expected.fieldwise());
475476# Ok::<(), Box<dyn std::error::Error>>(())
477```
478479### Parsing an RFC 2822 datetime string
480481While you probably shouldn't pick [RFC 2822] as a format for new things, it is
482sometimes necessary to use it when something else requires it (like HTTP
483or email). Parsing and printing of RFC 2822 datetimes is done via the
484[`fmt::rfc2822`] module:
485486```
487use jiff::fmt::rfc2822;
488489let zdt1 = rfc2822::parse("Thu, 29 Feb 2024 05:34 -0500")?;
490let zdt2 = zdt1.in_tz("Australia/Hobart")?;
491assert_eq!(rfc2822::to_string(&zdt2)?, "Thu, 29 Feb 2024 21:34:00 +1100");
492let zdt3 = zdt1.in_tz("Asia/Kolkata")?;
493assert_eq!(rfc2822::to_string(&zdt3)?, "Thu, 29 Feb 2024 16:04:00 +0530");
494495# Ok::<(), Box<dyn std::error::Error>>(())
496```
497498[RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
499500### Using `strftime` and `strptime` for formatting and parsing
501502Jiff has support for the C style [`strftime`] and [`strptime`] functions for
503formatting and parsing datetime types. All of Jiff's datetime types having a
504`strptime` constructor for parsing, and a `strftime` method for formatting. For
505example, this shows how to use [`ZonedDateTime::strptime`] to parsed a string
506in a "odd" custom format into a zoned datetime:
507508```
509use jiff::ZonedDateTime;
510511let zdt = ZonedDateTime::strptime(
512 "%A, %B %d, %Y at %I:%M%p %Q",
513 "Monday, July 15, 2024 at 5:30pm America/New_York",
514)?;
515assert_eq!(zdt.to_string(), "2024-07-15T17:30:00-04:00[America/New_York]");
516517# Ok::<(), Box<dyn std::error::Error>>(())
518```
519520And this shows how to use [`ZonedDateTime::strftime`] to format a zoned
521datetime. Note the use of `%Z`, which will print a time zone abbreviation (when
522one is available) instead of an offset (`%Z` can't be used for parsing):
523524```
525use jiff::civil::date;
526527let zdt = date(2024, 7, 15).at(17, 30, 59, 0).in_tz("Australia/Hobart")?;
528// %-I instead of %I means no padding.
529let string = zdt.strftime("%A, %B %d, %Y at %-I:%M%P %Z").to_string();
530assert_eq!(string, "Monday, July 15, 2024 at 5:30pm AEST");
531532# Ok::<(), Box<dyn std::error::Error>>(())
533```
534535However, time zone abbreviations aren't parsable because they are ambiguous.
536For example, `CST` can stand for `Central Standard Time`, `Cuba Standard Time`
537or `China Standard Time`. Instead, it is recommended to use `%Q` to format an
538IANA time zone identifier (which can be parsed, as shown above):
539540```
541use jiff::civil::date;
542543let zdt = date(2024, 7, 15).at(17, 30, 59, 0).in_tz("Australia/Hobart")?;
544// %-I instead of %I means no padding.
545let string = zdt.strftime("%A, %B %d, %Y at %-I:%M%P %Q").to_string();
546assert_eq!(string, "Monday, July 15, 2024 at 5:30pm Australia/Hobart");
547548# Ok::<(), Box<dyn std::error::Error>>(())
549```
550551See the [`fmt::strtime`] module documentation for supported conversion
552specifiers and other APIs.
553554[`strftime`]: https://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
555[`strptime`]: https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html
556557### Serializing and deserializing integer timestamps with Serde
558559Sometimes you need to interact with external services that use integer timestamps
560instead of something more civilized like RFC 3339. Since [`Timestamp`]'s
561Serde integration uses RFC 3339, you'll need to override the default. While
562you could hand-write this, Jiff provides convenience routines that do this
563for you. But you do need to wire it up via [Serde's `with` attribute]:
564565```
566use jiff::Timestamp;
567568#[derive(Debug, serde::Deserialize, serde::Serialize)]
569struct Record {
570 #[serde(with = "jiff::fmt::serde::timestamp::second::required")]
571 timestamp: Timestamp,
572}
573574let json = r#"{"timestamp":1517644800}"#;
575let got: Record = serde_json::from_str(&json)?;
576assert_eq!(got.timestamp, Timestamp::from_second(1517644800)?);
577assert_eq!(serde_json::to_string(&got)?, json);
578579# Ok::<(), Box<dyn std::error::Error>>(())
580```
581582If you need to support optional timestamps via `Option<Timestamp>`, then use
583`jiff::fmt::serde::timestamp::second::optional` instead.
584585For more, see the [`fmt::serde`] sub-module. (This requires enabling Jiff's
586`serde` crate feature.)
587588[Serde's `with` attribute]: https://serde.rs/field-attrs.html#with
589590# Crate features
591592### Ecosystem features
593594* **std** (enabled by default) -
595 When enabled, Jiff will depend on Rust's standard library. This is needed
596 for things that require interacting with your system, such as reading
597 `/usr/share/zoneinfo` on Unix systems for time zone information, or for
598 finding your system's default time zone. But if you don't need that (or can
599 bundle the Time Zone Database), then Jiff has nearly full functionality
600 without `std` enabled.
601* **alloc** (enabled by default) -
602 When enabled, Jiff will depend on the `alloc` crate. In particular, this
603 enables functionality that requires or greatly benefits from dynamic memory
604 allocation. If you can enable this, it is strongly encouraged that you do so.
605 Without it, only fixed time zones are supported and error messages are
606 significantly degraded. Also, the sizes of some types get bigger. If you
607 have use cases for Jiff in a no-std and no-alloc context, I would love
608 feedback on the issue tracker about your use cases.
609* **logging** -
610 When enabled, the `log` crate is used to emit messages where appropriate.
611 Generally speaking, this is reserved for system interaction points, such as
612 finding the system copy of the Time Zone Database or finding the system's
613 default time zone.
614* **serde** -
615 When enabled, all of the datetime and span types in Jiff implement
616 serde's `Serialize` and `Deserialize` traits. The format used is specified by
617 Temporal, but it's a mix of the "best" parts of RFC 3339, RFC 9557 and
618 ISO 8601. See the [`fmt::temporal`] module for more details on the format
619 used.
620* **js** -
621 On _only_ the `wasm32-unknown-unknown` and `wasm64-unknown-unknown` targets,
622 the `js` feature will add dependencies on `js-sys` and `wasm-bindgen`.
623 These dependencies are used to determine the current datetime and time
624 zone from the web browser. On these targets without the `js` feature
625 enabled, getting the current datetime will panic (because that's what
626 `std::time::SystemTime::now()` does), and it won't be possible to determine
627 the time zone. This feature is disabled by default because not all uses
628 of `wasm{32,64}-unknown-unknown` are in a web context, although _many_ are
629 (for example, when using `wasm-pack`). Only binary, tests and benchmarks
630 should enable this feature. See
631 [Platform support](crate::_documentation::platform) for more details.
632* **defmt** -
633 When enabled, Jiff will implement the [`defmt::Format`] trait for many
634 of its types. This is useful for embedded environments where the usual
635 `core::fmt` machinery is not practical to use. Note that, at time of writing
636 (2026-06-12), not all public types in this crate implement [`defmt::Format`].
637 If there are types for which you need `defmt` support but don't have it in
638 Jiff, then please [open a new issue][issue-new].
639* **arbitrary** -
640 When enabled, `Arbitrary` trait implementations (for the `arbitrary` crate)
641 are provided for many of Jiff's core datetime primitives.
642643### Time zone features
644645* **tz-system** (enabled by default) -
646 When enabled, Jiff will include code that attempts to determine the "system"
647 time zone. For example, on Unix systems, this is usually determined by
648 looking at the symlink information on `/etc/localtime`. But in general, it's
649 very platform specific and heuristic oriented.
650* **tz-fat** (enabled by default) -
651 When enabled, Jiff will "fatten" time zone data with extra transitions to
652 make time zone lookups faster. This may result in increased heap memory
653 (when loading time zones from `/usr/share/zoneinfo`) or increased binary
654 size (when using the `jiff-static` proc macros). Note that this doesn't add
655 more transitions than are likely already in `/usr/share/zoneinfo`, depending
656 on how it was generated.
657* **tzdb-bundle-always** -
658 When enabled, Jiff will forcefully depend on the `jiff-tzdb` crate, which
659 embeds an entire copy of the Time Zone Database. You should avoid this unless
660 you have a specific need for it, since it is better to rely on your system's
661 copy of time zone information. (Which may be updated multiple times per
662 year.)
663* **tzdb-bundle-platform** (enabled by default) -
664 When enabled, Jiff will depend on `jiff-tzdb` only for platforms where it is
665 known that there is no canonical copy of the Time Zone Database. For example,
666 Windows.
667* **tzdb-zoneinfo** (enabled by default) -
668 When enabled, Jiff will attempt to look for your system's copy of the Time
669 Zone Database.
670* **tzdb-concatenated** (enabled by default) -
671 When enabled, Jiff will attempt to look for a system copy of the
672 [Concatenated Time Zone Database]. This is primarily meant for reading time
673 zone information on Android platforms. The `ANDROID_ROOT` and `ANDROID_DATA`
674 environment variables (with sensible default fallbacks) are used to construct
675 candidate paths to look for this database. For more on this, see the
676 [Android section of the platform support documentation](crate::_documentation::platform#android).
677* **static** -
678 When enabled, new procedural macros will be added to the `tz` sub-module for
679 creating static `TimeZone` values at compile-time. This adds a dependency on
680 [`jiff-static`] and [`jiff-tzdb`]. `jiff-static` defines the macros, and Jiff
681 re-exports them. This also enables `static-tz`.
682* **static-tz** -
683 When enabled, a `jiff::tz::include` procedural macro will become available.
684 This takes a TZif file path, like `/usr/share/zoneinfo/Asia/Jerusalem`, as
685 input and returns a `TimeZone` value at compile time.
686687### Performance features
688689* **perf-inline** (enabled by default) -
690 When enabled, a number of `inline(always)` annotations are used inside of
691 Jiff to improve performance. This can especially impact formatting and
692 parsing of datetimes. If the extra performance isn't needed or if you want
693 to prioritize smaller binary sizes and shorter compilation times over
694 runtime performance, then it can be useful to disable this feature.
695696[`jiff-static`]: https://docs.rs/jiff-static
697[`jiff-tzdb`]: https://docs.rs/jiff-tzdb
698[Concatenated Time Zone Database]: https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/util/ZoneInfoDB.java
699[issue-new]: https://github.com/BurntSushi/jiff/issues/new
700*/
701702#![no_std]
703// Lots of rustdoc links break when disabling default features because docs
704// aren't written conditionally.
705#![cfg_attr(
706 all(
707 feature = "std",
708 feature = "serde",
709 feature = "static",
710 feature = "tzdb-zoneinfo"
711),
712 deny(rustdoc::broken_intra_doc_links)
713)]
714#![cfg_attr(
715 not(all(
716 feature = "std",
717 feature = "serde",
718 feature = "static",
719 feature = "tzdb-zoneinfo"
720)),
721 allow(rustdoc::broken_intra_doc_links)
722)]
723// These are just too annoying to squash otherwise.
724#![cfg_attr(
725 not(all(
726 feature = "std",
727 feature = "tzdb-zoneinfo",
728 feature = "tzdb-concatenated",
729 feature = "tz-system",
730 )),
731 allow(dead_code, unused_imports)
732)]
733#![cfg_attr(miri, allow(dead_code, unused_imports))]
734// This adds Cargo feature annotations to items in the rustdoc output. Which is
735// sadly hugely beneficial for this crate due to the number of features.
736#![cfg_attr(docsrs_jiff, feature(doc_cfg))]
737// We generally want all types to impl Debug.
738#![warn(missing_debug_implementations)]
739// Document ALL THE THINGS!
740#![deny(missing_docs)]
741// See: https://github.com/rust-lang/rust/pull/121364
742#![allow(unknown_lints, ambiguous_negative_literals)]
743// See: https://github.com/rust-lang/rust/pull/121364
744#![doc(test(attr(allow(unknown_lints, ambiguous_negative_literals))))]
745746// It should be possible to support other pointer widths, but this library
747// hasn't been tested nor thought about much in contexts with pointers less
748// than 32 bits.
749//
750// If you need support for 8-bit or 16-bit, please submit a bug report at
751// https://github.com/BurntSushi/jiff
752#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
753compile_error!("jiff currently not supported on non-{32,64}");
754755#[cfg(any(test, feature = "std"))]
756extern crate std;
757758#[cfg(any(test, feature = "alloc"))]
759extern crate alloc;
760761/// This is NOT part of Jiff's public API.
762///
763/// This is exported for use by `jiff-static`'s procedural macro.
764#[doc(hidden)]
765pub use jcoreas __jcore;
766767pub use crate::{
768error::Error,
769 signed_duration::{SignedDuration, SignedDurationRound},
770 span::{
771Span, SpanArithmetic, SpanCompare, SpanFieldwise, SpanRelativeTo,
772SpanRound, SpanTotal, ToSpan, Unit,
773 },
774 timestamp::{
775Timestamp, TimestampArithmetic, TimestampDifference,
776TimestampDisplayWithOffset, TimestampRound, TimestampSeries,
777 },
778util::round::RoundMode,
779 zoned::{
780ZonedDateTime, ZonedDateTimeArithmetic, ZonedDateTimeDifference,
781ZonedDateTimeRound, ZonedDateTimeSeries, ZonedDateTimeWith,
782 },
783};
784785#[macro_use]
786mod logging;
787788pub mod civil;
789mod duration;
790mod error;
791pub mod fmt;
792#[cfg(feature = "std")]
793mod now;
794mod signed_duration;
795mod span;
796mod timestamp;
797pub mod tz;
798mod util;
799mod zoned;
800801/// Longer form documentation for Jiff.
802pub mod _documentation {
803#[doc = "# Comparison with other Rust datetime crates\n\nThis document is meant to be a comparison between Jiff and each of the other\nprominent open source datetime libraries for Rust. If you feel like there is a\nlibrary missing from this list, please file an issue about it. I would prefer\nto only add libraries to this list that are being used in production or have a\nsubstantial number of users.\n\nThe goal of this document is to be as _descriptive_ and _substantively\ncomplete_ as possible. For example, \"Chrono has a better API design than Jiff\"\nwould be a pretty vague value judgment that someone could easily disagree with.\nBut, \"Chrono allows using a zone-aware datetime type that is `Copy` while Jiff\ndoes not\" would be a factual comparison that someone might use to _support_ an\nopinion that Chrono\'s API design is better than Jiff\'s. In other words, this\ndocument should provide the \"facts of comparison\" but refrain from assigning\nvalue judgments.\n\nIn terms of completeness, it is probably not realistic to expect 100%\ncompletion here. We aren\'t hunting for Korok Seeds. Instead, this document\naims for _substantive_ completion. That is, if there\'s a point of difference\nbetween Jiff and another library that would likely influence someone\'s decision\nof which library to use, and can be articulated descriptively, then it should\nprobably be in this document.\n\nThe current status of this document is that it is both _incomplete_ and\n_biased_. That is, this first draft was written by the author of Jiff without\nany input from other crate maintainers. (To other crate maintainers: I welcome\nfeedback. Even if it\'s just filing an issue.)\n\nNote that this document contains many code snippets. They can be tested with\n`cargo test --doc _documentation::comparison` from the root of this repository.\n\n## [`chrono`](https://docs.rs/chrono) (v0.4.38)\n\nChrono is a Rust datetime library that provides a time zone aware datetime\ntype.\n\nFor the following comparisons, a `Cargo.toml` with the following dependencies\nshould be able to run any of the programs in this section:\n\n```toml\nanyhow = \"1.0.81\"\nchrono = \"0.4.38\"\nchrono-tz = { version = \"0.9.0\", features = [\"serde\"] }\njiff = { version = \"0.2.0\", features = [\"serde\"] }\nserde = \"1.0.203\"\nserde_json = \"1.0.117\"\ntzfile = \"0.1.3\"\n```\n\n### Time zone database integration\n\nJiff gives you automatic integration with your copy of the Time Zone Database.\nOn Unix, it\'s usually found at `/usr/share/zoneinfo`. On Windows, since there\nis no canonical location, Jiff will depend on `jiff-tzdb` by default, which\nwill embed the entire database into your binary. Jiff hides these details from\nyou. For example, to convert a civil time into an absolute time in a particular\ntime zone:\n\n```rust\nuse jiff::civil::date;\n\nfn main() -> anyhow::Result<()> {\n let zdt = date(2024, 6, 30).at(9, 46, 0, 0).in_tz(\"America/New_York\")?;\n assert_eq!(zdt.to_string(), \"2024-06-30T09:46:00-04:00[America/New_York]\");\n Ok(())\n}\n```\n\nFor Chrono, one recommended option is to use the\n[`chrono-tz`](https://docs.rs/chrono-tz) crate:\n\n```rust\nuse anyhow::Context;\nuse chrono::TimeZone;\nuse chrono_tz::America::New_York;\n\nfn main() -> anyhow::Result<()> {\n let zdt = New_York.with_ymd_and_hms(2024, 6, 30, 9, 46, 0)\n .single()\n .context(\"invalid naive time\")?;\n assert_eq!(zdt.to_string(), \"2024-06-30 09:46:00 EDT\");\n Ok(())\n}\n```\n\n`chrono-tz` works by embedding an entire copy of the Time Zone Database into\nyour binary, where each time zone is represented as a Rust value that can be\nimported via `use`. A disadvantage of this approach is that you\'re reliant on\n`chrono-tz` updates to get the most recent time zone information. An advantage\nof this approach is that you never need to worry about an end user\'s system\nstate. Another advantage is that this allows a `TimeZone` trait implementation\nto be `Copy` via a `&Tz`, and that in turn allows a `chrono::DateTime` to be\n`Copy`. In contrast, in Jiff, a `TimeZone` is never `Copy`. Since a\n`ZonedDateTime` embeds a `TimeZone`, a `ZonedDateTime` is never `Copy` either.\n\nAnother recommended option is the [`tzfile`](https://docs.rs/tzfile) crate.\nUnlike `chrono-tz`, the `tzfile` crate will try to read time zone data from\nyour system\'s copy of the Time Zone Database.\n\n```rust\nuse anyhow::Context;\nuse chrono::TimeZone;\nuse tzfile::Tz;\n\n#[cfg(unix)]\nfn main() -> anyhow::Result<()> {\n let tz = Tz::named(\"America/New_York\")?;\n let zdt = (&tz).with_ymd_and_hms(2024, 6, 30, 9, 46, 0)\n .single()\n .context(\"invalid naive time\")?;\n assert_eq!(zdt.to_string(), \"2024-06-30 09:46:00 EDT\");\n Ok(())\n}\n\n// `tzfile` exposes a platform specific API, which means\n// users of the crate have to deal with platform differences\n// themselves.\n#[cfg(not(unix))]\nfn main() -> anyhow::Result<()> {\n Ok(())\n}\n```\n\nNote though that at time of writing (2024-07-11), `tzfile::Tz::named` will\nread and parse the corresponding time zone rules from disk on every call.\nConversely, in Jiff, all time zone lookups by name are cached. This may or may\nnot matter for your use case.\n\n### Jiff losslessly roundtrips time zone aware datetimes\n\nIn Jiff, with `serde` support enabled, one can serialize and deserialize a\n`ZonedDateTime` value losslessly. This means that, after deserialization, you\ncan expect it to still perform DST arithmetic:\n\n```rust\nuse jiff::{ToSpan, ZonedDateTime, civil::date};\n\nfn main() -> anyhow::Result<()> {\n let zdt = date(2024, 3, 10).at(1, 59, 59, 0).in_tz(\"America/New_York\")?;\n\n let json = serde_json::to_string_pretty(&zdt)?;\n assert_eq!(json, \"\\\"2024-03-10T01:59:59-05:00[America/New_York]\\\"\");\n\n let got: ZonedDateTime = serde_json::from_str(&json)?;\n assert_eq!(got.to_string(), \"2024-03-10T01:59:59-05:00[America/New_York]\");\n let next = got.checked_add(1.minute())?;\n assert_eq!(next.to_string(), \"2024-03-10T03:00:59-04:00[America/New_York]\");\n\n Ok(())\n}\n```\n\nNotice that when we add a minute, it jumps to `03:00` civil time because of the\ntransition into daylight saving time in my selected time zone. Notice also the\noffset change from `-05` to `-04`.\n\nCompare this with Chrono which also supports `serde`, but not with `chrono-tz`\nor `tzfile`. One option is to use its `Local` implementation of its `TimeZone`\ntrait:\n\n```rust,no_run\nuse anyhow::Context;\nuse chrono::{DateTime, FixedOffset, Local, TimeDelta, TimeZone};\n\nfn main() -> anyhow::Result<()> {\n let zdt = Local.with_ymd_and_hms(2024, 3, 10, 1, 59, 59)\n .single()\n .context(\"invalid naive time\")?;\n\n let json = serde_json::to_string_pretty(&zdt)?;\n // Chrono only serializes the offset, which makes lossless\n // deserialization impossible. Chrono loses the time zone\n // information.\n assert_eq!(json, \"\\\"2024-03-10T01:59:59-05:00\\\"\");\n\n // The serialized datetime has no time zone information,\n // so unless there is some out-of-band information saying\n // what its time zone is, we\'re forced to use a fixed offset:\n let got: DateTime<FixedOffset> = serde_json::from_str(&json)?;\n assert_eq!(got.to_string(), \"2024-03-10 01:59:59 -05:00\");\n let next = got.checked_add_signed(TimeDelta::minutes(1))\n .context(\"arithmetic failed\")?;\n // This is correct for fixed offset, but it\'s no longer\n // DST aware.\n assert_eq!(next.to_string(), \"2024-03-10 02:00:59 -05:00\");\n\n // We could deserialize into a `DateTime<Local>`, but this\n // requires knowing that the time zone of the datetime matches\n // local time zone. Which you might know. But you might not.\n let got: DateTime<Local> = serde_json::from_str(&json)?;\n assert_eq!(got.to_string(), \"2024-03-10 01:59:59 -05:00\");\n let next = got.checked_add_signed(TimeDelta::minutes(1))\n .context(\"arithmetic failed\")?;\n assert_eq!(next.to_string(), \"2024-03-10 03:00:59 -04:00\");\n\n Ok(())\n}\n```\n\nOr, if you have a `Tz` from `chrono-tz`. But in this case, since `chrono-tz`\ndoesn\'t support Serde, you have to convert to a `DateTime<FixedOffset>`. Like\nabove, you\'ll lose DST safe arithmetic after deserialization:\n\n```rust\nuse anyhow::Context;\nuse chrono::{DateTime, FixedOffset, TimeDelta, TimeZone};\nuse chrono_tz::America::New_York;\n\nfn main() -> anyhow::Result<()> {\n let zdt = New_York.with_ymd_and_hms(2024, 3, 10, 1, 59, 59)\n .single()\n .context(\"invalid naive time\")?;\n\n let json = serde_json::to_string_pretty(&zdt.fixed_offset())?;\n // Chrono only serializes the offset, which makes lossless\n // deserialization impossible. Chrono loses the time zone\n // information.\n assert_eq!(json, \"\\\"2024-03-10T01:59:59-05:00\\\"\");\n\n // The serialized datetime has no time zone information,\n // so unless there is some out-of-band information saying\n // what its time zone is, we\'re forced to use a fixed offset:\n let got: DateTime<FixedOffset> = serde_json::from_str(&json)?;\n assert_eq!(got.to_string(), \"2024-03-10 01:59:59 -05:00\");\n let next = got.checked_add_signed(TimeDelta::minutes(1))\n .context(\"arithmetic failed\")?;\n // This is correct for fixed offset, but it\'s no longer\n // DST aware.\n assert_eq!(next.to_string(), \"2024-03-10 02:00:59 -05:00\");\n\n Ok(())\n}\n```\n\nThe main way to solve this problem (and is how `java.time`, Temporal and Jiff\nsolve it), is by supporting [RFC 9557]. Otherwise, the only way to fully\ncapture Jiff\'s functionality in Chrono is to define a custom serialization\nformat that includes the instant, the time zone identifier *and* the offset.\n(The offset is used for conflict resolution when deserializing datetimes made\nin the future for which their offset has changed due to changes in the time\nzone database.)\n\n[RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/\n\n### Jiff provides support for zone aware calendar arithmetic\n\nWith Jiff, you can add non-uniform units like days to time zone aware datetimes,\nand get non-uniform units like days as a representation of a span between\ndatetimes. And they agree on the results.\n\n```rust\nuse jiff::{civil::date, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2024, 3, 9).at(21, 0, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = zdt1.checked_add(1.day())?;\n\n // Even though 2 o\'clock didn\'t occur on 2024-03-10, adding 1 day\n // returns the same civil time the next day.\n assert_eq!(zdt2.to_string(), \"2024-03-10T21:00:00-04:00[America/New_York]\");\n // The span of time is 23 hours:\n assert_eq!(&zdt2 - &zdt1, 23.hours().fieldwise());\n // But if you ask for the span in units of days, you get exactly 1:\n assert_eq!(zdt1.until((Unit::Day, &zdt2))?, 1.day().fieldwise());\n\n Ok(())\n}\n```\n\nThis is important and difficult to get right because some days are only 23\nhours long (typically the day of the year where DST starts) and some days are\n25 hours long (typically the day of the year where DST ends). With Jiff, you\ncan seamlessly go back-and-forth between calendar units and clock units without\nworrying about whether \"day\" will be interpreted differently.\n\nChrono has some support for this. Namely, it can add units of days in a time\nzone aware fashion, but it cannot produce spans of time involving days between\ntwo zone aware datetimes that is consistent with adding days.\n\n```rust\nuse anyhow::Context;\nuse chrono::{Days, TimeDelta, TimeZone};\nuse chrono_tz::America::New_York;\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = New_York.with_ymd_and_hms(2024, 3, 9, 21, 0, 0)\n .single()\n .context(\"invalid naive time\")?;\n\n // Adding 1 day via TimeDelta leads to a result that is\n // 24 hours later, including the gap at 2am on 2024-03-10.\n // As a result, you get a different civil time, which is\n // usually not what is intended.\n let zdt2 = zdt1.checked_add_signed(TimeDelta::days(1))\n .context(\"adding a time delta failed\")?;\n assert_eq!(zdt2.to_string(), \"2024-03-10 22:00:00 EDT\");\n\n // However, Chrono does expose a separate API for adding\n // units of days specifically. This does get you the\n // correct result.\n let zdt2 = zdt1.checked_add_days(Days::new(1))\n .context(\"adding days failed\")?;\n assert_eq!(zdt2.to_string(), \"2024-03-10 21:00:00 EDT\");\n\n // The only way to compute a duration between two datetimes\n // in Chrono is with a `TimeDelta`:\n let delta = zdt2.signed_duration_since(&zdt1);\n // And since `TimeDelta` assumes all days are exactly 24\n // hours long, you get a result of `0` days. If this were\n // a fold, the number of days would be `1`, but you\'d also\n // have a number of hours equal to `1`.\n assert_eq!(delta.num_days(), 0);\n\n Ok(())\n}\n```\n\n### Jiff losslessly roundtrips durations\n\nJiff implements something close to ISO 8601 to provide lossless serialization\nand deserialization of its `Span` type. A `Span` covers both calendar and clock\nunits.\n\n```rust\nuse jiff::{Span, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n let span = 5.years().months(2).days(1).hours(20);\n let json = serde_json::to_string_pretty(&span)?;\n assert_eq!(json, \"\\\"P5Y2M1DT20H\\\"\");\n\n let got: Span = serde_json::from_str(&json)?;\n assert_eq!(got, span.fieldwise());\n\n Ok(())\n}\n```\n\nChrono [does not currently have Serde support for its duration type][serde-duration].\n\n[serde-duration]: https://github.com/chronotope/chrono/issues/117\n\n### Jiff supports dealing with gaps in civil time\n\nA gap in civil time most typically occurs when a particular region enters\ndaylight saving time. When this happens, some time on the clocks in that region\nis skipped. It never appears. (A fold happens when the clocks are rolled back,\nusually when leaving daylight saving time. In this case, some time on the clock\nis repeated.)\n\nJiff supports automatically selecting a \"reasonable\" choice in either case\nvia its \"compatible\" strategy (as specified by [RFC 5545]).\n\n```rust\nuse jiff::ZonedDateTime;\n\nfn main() -> anyhow::Result<()> {\n // This is a gap. The default strategy takes the time after the gap.\n let zdt: ZonedDateTime = \"2024-03-10 02:30[America/New_York]\".parse()?;\n assert_eq!(zdt.to_string(), \"2024-03-10T03:30:00-04:00[America/New_York]\");\n\n // This is a fold. The default strategy takes the time before the fold.\n let zdt: ZonedDateTime = \"2024-11-03 01:30[America/New_York]\".parse()?;\n // The time after the fold would be identical,\n // except the offset would be -05.\n assert_eq!(zdt.to_string(), \"2024-11-03T01:30:00-04:00[America/New_York]\");\n\n Ok(())\n}\n```\n\nJiff also exposes all information available with respect to ambiguous civil\ndatetimes via `tz::AmbiguousZonedDateTime`, `tz::AmbiguousTimestamp` and\n`tz::AmbiguousOffset`. This enables callers to implement whatever strategy\nthey want.\n\nWhile Chrono will let you deal with folds, it returns `MappedLocalTime::None`\nin the case of a gap with no additional information. So there\'s really nothing\nelse you can conveniently do in this case except return an error:\n\n```rust\nuse anyhow::Context;\nuse chrono::{offset::MappedLocalTime, TimeZone};\nuse chrono_tz::America::New_York;\n\nfn main() -> anyhow::Result<()> {\n // For gaps, Chrono exposes no additional information.\n let mapped = New_York.with_ymd_and_hms(2024, 3, 10, 2, 30, 0);\n assert_eq!(mapped, MappedLocalTime::None);\n\n // For folds, Chrono gives you the two choices.\n // This is approximately equivalent to what Jiff exposes\n // in the case of a fold.\n let zdt = New_York.with_ymd_and_hms(2024, 11, 3, 1, 30, 0)\n .earliest()\n .context(\"invalid datetime\")?;\n assert_eq!(zdt.to_string(), \"2024-11-03 01:30:00 EDT\");\n\n Ok(())\n}\n```\n\n[RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545\n\n### Jiff supports rounding durations\n\nIn Jiff, one can round the duration computed between two datetimes:\n\n```rust\nuse jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz(\"America/New_York\")?;\n\n let round_options = ZonedDateTimeDifference::new(&zdt2)\n .largest(Unit::Year)\n .smallest(Unit::Day)\n .mode(RoundMode::HalfExpand);\n let span = zdt1.until(round_options)?;\n assert_eq!(span.fieldwise(), 22.years().months(7).days(24));\n\n Ok(())\n}\n```\n\nWhile Chrono supports rounding datetimes themselves via its\n`chrono::duration::DurationRound` trait, it does not support rounding durations\nthemselves. Indeed, its principle duration type, `TimeDelta`, is an \"absolute\"\nduration like `std::time::Duration` (except that it is signed). It doesn\'t keep\ntrack of individual units like Jiff does. Instead, everything gets normalized\ninto a 96-bit integer number of nanoseconds. With this representation, it is\nimpossible to do DST safe rounding to non-uniform units like days.\n\n### Jiff supports zone-aware rounding of durations\n\nJiff\'s duration rounding is time zone aware. For example, if you\'re rounding to\na number of days, it knows to round 11.5 hours up to 1 day on days with gaps,\nand round 12 hours down to 0 days on days with folds. The only requirement\nis that we provide a reference datetime with which to interpret the span.\n\n```rust\nuse jiff::{civil::date, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n let gapday = date(2024, 3, 10).in_tz(\"America/New_York\")?;\n let foldday = date(2024, 11, 3).in_tz(\"America/New_York\")?;\n\n let span1 = 11.hours().minutes(30);\n let span2 = span1.round(\n SpanRound::new().smallest(Unit::Day).relative(&gapday),\n )?;\n // rounds up, even though on a normal day 11.5 hours would round down.\n assert_eq!(span2, 1.day().fieldwise());\n\n let span1 = 12.hours();\n let span2 = span1.round(\n SpanRound::new().smallest(Unit::Day).relative(&foldday),\n )?;\n // rounds down, even though on a normal day 12 hours would round up.\n assert_eq!(span2, 0.days().fieldwise());\n\n Ok(())\n}\n```\n\nAs with the previous section, Chrono does not support rounding durations or\nrounding units like `Days` with respect to a reference datetime.\n\n### Jiff supports re-balancing durations\n\nThis example is like the one above, except we choose a smaller \"largest\" unit:\n\n```rust\nuse jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz(\"America/New_York\")?;\n\n let round_options = ZonedDateTimeDifference::new(&zdt2)\n .largest(Unit::Month)\n .smallest(Unit::Day)\n .mode(RoundMode::HalfExpand);\n let span = zdt1.until(round_options)?;\n assert_eq!(span, 271.months().days(24).fieldwise());\n\n Ok(())\n}\n```\n\n### Jiff supports getting the `nth` weekday from the current date\n\n```rust\nuse jiff::civil::{date, Weekday};\n\nfn main() -> anyhow::Result<()> {\n let zdt = date(2024, 7, 11).at(22, 59, 0, 0).in_tz(\"America/New_York\")?;\n assert_eq!(zdt.weekday(), Weekday::Thursday);\n\n let next_tuesday = zdt.nth_weekday(1, Weekday::Tuesday)?;\n assert_eq!(\n next_tuesday.to_string(),\n \"2024-07-16T22:59:00-04:00[America/New_York]\",\n );\n\n Ok(())\n}\n```\n\nChrono does have `NaiveDate::from_weekday_of_month_opt`, but it only counts\nthe number of weekdays for a particular month. (The Jiff equivalent is\n`nth_weekday_of_month`.) Moreover, Chrono\'s method is only available on naive\ndates and not zone aware datetimes.\n\n### Jiff supports detecting time zone offset conflicts\n\nOne of the problems with storing datetimes in the future is that time\nzone rules can change. For example, if you stored the zone aware datetime\n`2020-01-15T12:00-02[America/Sao_Paulo]` in 2018, then it would be considered\nto be in daylight saving time with an offset of `-2`. However, in 2019,\ndaylight saving time was abolished in this time zone, which renders the\ndatetime invalid because its offset *should* be `-3`.\n\nJiff can detect these sorts of conflicts and will actually return a parse error\nby default. We exemplify this by creating and serializing a zoned datetime from\nan old copy of the Time Zone Database, and then try to parse it back using our\nsystem\'s current copy of the Time Zone Database. (This also demonstrate\'s Jiff\nsupport for using multiple copies of the Time Zone Database simultaneously.\nBut the main point here is to simulate the process of \"serialize datetime,\ntime zone rules change, deserialize datetime.\")\n\n```rust,no_run\nuse jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}};\n\n// We use a custom parser with a default configuration because we need\n// to ask the parser to use a different time zone database than the\n// default. This can\'t be done via the nice `\"...\".parse()` API one\n// would typically use.\nstatic PARSER: DateTimeParser = DateTimeParser::new();\n\nfn main() -> anyhow::Result<()> {\n // Open a version of tzdb from before Brazil announced its abolition\n // of daylight saving time.\n let tzdb2018 = TimeZoneDatabase::from_dir(\"path/to/tzdb-2018b\")?;\n // Open the system tzdb.\n let tzdb = tz::db();\n\n // Parse the same datetime string with the same parser, but using two\n // different versions of tzdb.\n let dt = \"2020-01-15T12:00[America/Sao_Paulo]\";\n let zdt2018 = PARSER.parse_zoned_datetime_with(&tzdb2018, dt)?;\n let zdt = PARSER.parse_zoned_datetime_with(tzdb, dt)?;\n\n // Before DST was abolished, 2020-01-15 was in DST, which corresponded\n // to UTC offset -02. Since DST rules applied to datetimes in the\n // future, the 2018 version of tzdb would lead one to interpret\n // 2020-01-15 as being in DST.\n assert_eq!(zdt2018.offset(), tz::offset(-2));\n // But DST was abolished in 2019, which means that 2020-01-15 was no\n // no longer in DST. So after a tzdb update, the same datetime as above\n // now has a different offset.\n assert_eq!(zdt.offset(), tz::offset(-3));\n\n // So if you try to parse a datetime serialized from an older copy of\n // tzdb with a new copy of tzdb, you\'ll get an error under the default\n // configuration because of `OffsetConflict::Reject`. This would succeed if\n // you parsed it using tzdb2018!\n assert!(\n PARSER.parse_zoned_datetime_with(tzdb, zdt2018.to_string()).is_err()\n );\n\n Ok(())\n}\n```\n\nWith Chrono, this sort of checking isn\'t possible in the first place because\nit doesn\'t support an interchange format that includes the IANA time zone\nidentifier.\n\n### Jiff supports adding durations with calendar units\n\nSince `Span` is Jiff\'s single duration type that combines calendar and clock\nunits, one can freely add them together. The only requirement is that if a span\nhas calendar units, you need to provide a reference date. (Because 1 month from\nApril 1 is shorter than 1 month from May 1.)\n\n```rust\nuse jiff::{civil::date, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n let span1 = 2.years().months(4).days(25).hours(23);\n let span2 = 3.hours();\n let span3 = span1.checked_add((span2, date(2024, 1, 1)))?;\n assert_eq!(span3.fieldwise(), 2.years().months(4).days(26).hours(2));\n\n Ok(())\n}\n```\n\nWhile Chrono has types like `Months` and `Days`, there\'s no way to combine\nthem into one, and Chrono does not provide operations on both at the same time.\n\n### Jiff supports zone-aware re-balancing of durations\n\nIf you have a span of `1.day()` and want to convert it to hours, then that\ncalculation depends on how long the day is. If you provide a civil date as\na relative reference point, then Jiff assumes the day is always 24 hours long:\n\n```rust\nuse jiff::{civil, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n let relative = civil::date(2024, 4, 1);\n let span1 = 1.day();\n let span2 = span1.round(\n SpanRound::new().largest(Unit::Hour).relative(relative),\n )?;\n assert_eq!(span2, 24.hours().fieldwise());\n\n Ok(())\n}\n```\n\nBut if a reference date is provided with a time zone, then the re-balancing is\nDST safe:\n\n```rust\nuse jiff::{civil::date, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n // In the case of a gap (typically transitioning in DST):\n let zdt = date(2024, 3, 9).at(21, 0, 0, 0).in_tz(\"America/New_York\")?;\n let span1 = 1.day();\n let span2 = span1.round(\n SpanRound::new().largest(Unit::Hour).relative(&zdt)\n )?;\n assert_eq!(span2, 23.hours().fieldwise());\n\n // In the case of a fold (typically transitioning out of DST):\n let zdt = date(2024, 11, 2).at(21, 0, 0, 0).in_tz(\"America/New_York\")?;\n let span1 = 1.day();\n let span2 = span1.round(\n SpanRound::new().largest(Unit::Hour).relative(&zdt)\n )?;\n assert_eq!(span2, 25.hours().fieldwise());\n\n Ok(())\n}\n```\n\n### Jiff is generally faster than Chrono\n\nThere are some cases where Chrono is faster than Jiff, but Jiff should\ngenerally be competitive for equivalent operations. It\'s generally not\npossible for Chrono or Jiff to always be faster than the other, since\nthey each use different representations for fundamental types. This in turn\nmakes some operations faster and others slower, depending on what you\'re\ntrying to do. With that said, Jiff is uniformly faster than Chrono when it\ncomes to printing and parsing.\n\n```text\n$ cd bench\n$ cargo bench -- --save-baseline base\n[.. snip ..]\n$ critcmp base -g \'(.*)/(?:jiff|chrono)$\'\ngroup baseline//chrono baseline//jiff\n----- ---------------- --------------\ncivil_datetime/add_days/diffyear/duration 1.00 8.5\u{b1}0.08ns ? ?/sec 1.56 13.3\u{b1}0.15ns ? ?/sec\ncivil_datetime/add_days/diffyear/span 1.00 23.9\u{b1}0.13ns ? ?/sec\ncivil_datetime/add_days/sameyear/duration 1.00 6.8\u{b1}0.05ns ? ?/sec 1.96 13.3\u{b1}0.17ns ? ?/sec\ncivil_datetime/add_days/sameyear/span 1.00 23.8\u{b1}0.13ns ? ?/sec\ncivil_datetime/to_timestamp_static/bundled 2.05 22.3\u{b1}0.24ns ? ?/sec 1.00 10.9\u{b1}0.14ns ? ?/sec\ncivil_datetime/to_timestamp_static/zoneinfo 1.53 16.2\u{b1}0.15ns ? ?/sec 1.00 10.6\u{b1}0.09ns ? ?/sec\ncivil_datetime/to_timestamp_tzdb_lookup/bundled 1.00 32.0\u{b1}0.15ns ? ?/sec\ncivil_datetime/to_timestamp_tzdb_lookup/zoneinfo 45.85 1919.7\u{b1}6.17ns ? ?/sec 1.00 41.9\u{b1}0.15ns ? ?/sec\ndate/add_days/diffyear/duration 1.00 5.8\u{b1}0.05ns ? ?/sec 1.12 6.5\u{b1}0.04ns ? ?/sec\ndate/add_days/diffyear/span 1.00 6.5\u{b1}0.04ns ? ?/sec\ndate/add_days/one/duration 1.00 2.1\u{b1}0.02ns ? ?/sec 2.55 5.4\u{b1}0.05ns ? ?/sec\ndate/add_days/one/span 1.00 5.8\u{b1}0.02ns ? ?/sec\ndate/add_days/sameyear/duration 1.00 2.1\u{b1}0.01ns ? ?/sec 3.08 6.5\u{b1}0.05ns ? ?/sec\ndate/add_days/sameyear/span 1.00 6.5\u{b1}0.05ns ? ?/sec\ndate/difference_days/duration 1.18 3.4\u{b1}0.04ns ? ?/sec 1.00 2.9\u{b1}0.02ns ? ?/sec\ndate/difference_days/span 1.00 2.5\u{b1}0.02ns ? ?/sec\ndate/tomorrow/diff-month 1.00 0.4\u{b1}0.00ns ? ?/sec 3.25 1.3\u{b1}0.01ns ? ?/sec\ndate/tomorrow/diff-year 1.16 1.7\u{b1}0.01ns ? ?/sec 1.00 1.4\u{b1}0.01ns ? ?/sec\ndate/tomorrow/same-month 1.00 0.4\u{b1}0.00ns ? ?/sec 1.99 0.8\u{b1}0.00ns ? ?/sec\ndate/yesterday/diff-month 1.00 0.4\u{b1}0.02ns ? ?/sec 3.17 1.3\u{b1}0.01ns ? ?/sec\ndate/yesterday/diff-year 1.85 2.0\u{b1}0.01ns ? ?/sec 1.00 1.1\u{b1}0.01ns ? ?/sec\ndate/yesterday/same-month 1.00 0.4\u{b1}0.03ns ? ?/sec 1.72 0.7\u{b1}0.02ns ? ?/sec\nparse/civil_datetime 2.95 73.6\u{b1}0.72ns ? ?/sec 1.00 24.9\u{b1}0.19ns ? ?/sec\nparse/rfc2822 3.09 59.9\u{b1}0.30ns ? ?/sec 1.00 19.3\u{b1}0.17ns ? ?/sec\nparse/strptime/oneshot 3.11 197.8\u{b1}0.80ns ? ?/sec 1.00 63.6\u{b1}1.19ns ? ?/sec\nparse/strptime/prebuilt 1.00 77.1\u{b1}1.44ns ? ?/sec\nprint/civil_datetime 13.10 147.4\u{b1}0.60ns ? ?/sec 1.00 11.3\u{b1}0.04ns ? ?/sec\nprint/iso8601_duration/long-time/duration/buffer 2.38 46.5\u{b1}0.34ns ? ?/sec 1.00 19.5\u{b1}0.04ns ? ?/sec\nprint/iso8601_duration/long-time/duration/to_string 3.13 71.7\u{b1}0.36ns ? ?/sec 1.00 23.0\u{b1}0.07ns ? ?/sec\nprint/iso8601_duration/short/duration/buffer 2.65 32.3\u{b1}0.30ns ? ?/sec 1.00 12.2\u{b1}0.04ns ? ?/sec\nprint/iso8601_duration/short/duration/to_string 2.08 36.8\u{b1}0.33ns ? ?/sec 1.00 17.7\u{b1}0.05ns ? ?/sec\nprint/iso8601_duration/tiny/duration/buffer 2.74 31.6\u{b1}0.32ns ? ?/sec 1.00 11.6\u{b1}0.03ns ? ?/sec\nprint/iso8601_duration/tiny/duration/to_string 2.28 36.5\u{b1}0.40ns ? ?/sec 1.00 16.0\u{b1}0.08ns ? ?/sec\nprint/rfc2822/buffer 4.91 64.6\u{b1}0.59ns ? ?/sec 1.00 13.2\u{b1}0.03ns ? ?/sec\nprint/rfc2822/to_string 5.75 111.0\u{b1}0.37ns ? ?/sec 1.00 19.3\u{b1}0.05ns ? ?/sec\nprint/rfc3339/buffer 3.79 64.2\u{b1}0.56ns ? ?/sec 1.00 17.0\u{b1}0.14ns ? ?/sec\nprint/rfc3339/to_string 4.75 112.4\u{b1}0.33ns ? ?/sec 1.00 23.6\u{b1}0.11ns ? ?/sec\nprint/rfc9557/buffer 1.00 16.2\u{b1}0.05ns ? ?/sec\nprint/rfc9557/to_string 1.00 22.2\u{b1}0.07ns ? ?/sec\nprint/strftime/oneshot/buffer 3.90 213.9\u{b1}1.99ns ? ?/sec 1.00 54.8\u{b1}0.32ns ? ?/sec\nprint/strftime/oneshot/to_string 3.63 261.3\u{b1}1.26ns ? ?/sec 1.00 72.1\u{b1}0.49ns ? ?/sec\nprint/strftime/oneshot/zoned 1.00 65.5\u{b1}0.64ns ? ?/sec\nprint/strftime/prebuilt/buffer 1.00 85.4\u{b1}0.52ns ? ?/sec\nprint/strftime/prebuilt/to_string 1.00 147.4\u{b1}0.76ns ? ?/sec\ntimestamp/add_time_secs/duration 2.42 6.1\u{b1}0.08ns ? ?/sec 1.00 2.5\u{b1}0.03ns ? ?/sec\ntimestamp/add_time_secs/span 1.00 3.8\u{b1}0.06ns ? ?/sec\ntimestamp/add_time_subsec/duration 2.10 6.1\u{b1}0.04ns ? ?/sec 1.00 2.9\u{b1}0.02ns ? ?/sec\ntimestamp/add_time_subsec/span 1.00 8.1\u{b1}0.09ns ? ?/sec\ntimestamp/every_hour_in_week/byhand 16.15 1679.6\u{b1}6.13ns ? ?/sec 1.00 104.0\u{b1}0.72ns ? ?/sec\ntimestamp/every_hour_in_week/series 1.00 105.9\u{b1}0.66ns ? ?/sec\ntimestamp/from_seconds/integer 14.45 4.7\u{b1}0.03ns ? ?/sec 1.00 0.3\u{b1}0.00ns ? ?/sec\ntimestamp/to_civil_datetime_offset_conversion 1.65 7.3\u{b1}0.02ns ? ?/sec 1.00 4.4\u{b1}0.04ns ? ?/sec\ntimestamp/to_civil_datetime_offset_holistic 1.00 4.4\u{b1}0.04ns ? ?/sec\ntimestamp/to_civil_datetime_static/America-New-York/bundled 1.00 16.0\u{b1}0.16ns ? ?/sec\ntimestamp/to_civil_datetime_static/America-New-York/zoneinfo 1.42 18.4\u{b1}0.11ns ? ?/sec 1.00 13.0\u{b1}0.11ns ? ?/sec\ntimestamp/to_civil_datetime_static/Asia-Shanghai/bundled 1.00 15.2\u{b1}0.16ns ? ?/sec\ntimestamp/to_civil_datetime_static/Asia-Shanghai/zoneinfo 3.16 15.7\u{b1}0.11ns ? ?/sec 1.00 5.0\u{b1}0.05ns ? ?/sec\nzoned/fixed_offset_add_time/duration 1.00 6.1\u{b1}0.06ns ? ?/sec 1.56 9.5\u{b1}0.05ns ? ?/sec\nzoned/fixed_offset_add_time/span 1.00 16.6\u{b1}0.09ns ? ?/sec\nzoned/fixed_offset_to_civil_datetime 1.23 5.6\u{b1}0.01ns ? ?/sec 1.00 4.5\u{b1}0.01ns ? ?/sec\nzoned/fixed_offset_to_timestamp 3.15 1.2\u{b1}0.01ns ? ?/sec 1.00 0.4\u{b1}0.00ns ? ?/sec\n```\n\nQuestions about benchmarks are welcome in\n[Discussions on GitHub](https://github.com/BurntSushi/jiff/discussions).\n\n## [`time`](https://docs.rs/time) (v0.3.36)\n\n`time` is a Rust datetime library that provides a time zone offset aware\ndatetime type.\n\nFor the following comparisons, a `Cargo.toml` with the following dependencies\nshould be able to run any of the programs in this section:\n\n```toml\nanyhow = \"1.0.81\"\njiff = { version = \"0.2.0\", features = [\"serde\"] }\ntime = { version = \"0.3.36\", features = [\"local-offset\", \"macros\", \"parsing\"] }\ntime-tz = \"2.0.0\"\n```\n\n### Time zone database integration\n\nLike `chrono`, the `time` crate does not come with any out of the box\nfunctionality for reading your system\'s copy of the Time Zone Database.\nHowever, there is a third party crate, [`time-tz`](https://docs.rs/time-tz)\nthat provides some time zone support in a fashion similar to `chrono-tz`. That\nis, it requires bundling the time zone data into your binary and does not\nsupport reading the system copy of the Time Zone Database when available.\n\nNote also that `time` does not provide the extension points necessary in its API\nto make handling time zone aware datetimes ergonomic. Indeed, many operations\nare not expressible at all.\n\nThe main thing `time` supports is a concept of \"local\" time. In particular, it\nis limited to determining your system\'s default time zone offset, but nothing\nmore. That is, it doesn\'t support DST safe arithmetic:\n\n```rust\nuse anyhow::Context;\nuse time::{ext::NumericalDuration, macros::datetime, Duration};\n\nfn main() -> anyhow::Result<()> {\n // We create a fixed datetime for testing purposes,\n // but it\'s the same sort of value we would get back\n // from `OffsetDateTime::now_local()`.\n let dt1 = datetime!(2024-03-10 01:30:00 -05:00);\n let dt2 = dt1.checked_add(1.hours())\n .context(\"datetime arithmetic failed\")?;\n // The 2 o\'clock hour didn\'t exist on 2024-03-10\n // in New York.\n assert_eq!(dt2.to_string(), \"2024-03-10 2:30:00.0 -05:00:00\");\n\n Ok(())\n}\n```\n\n`time`, in its present design, is fundamentally incapable of doing daylight\nsaving time safe arithmetic because its `OffsetDateTime` type doesn\'t know\nanything about the time zone rules. Compare this with Jiff, which lets you not\nonly create a datetime with an offset, but with a _time zone_:\n\n```rust\nuse jiff::{civil::date, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2024, 3, 10).at(1, 30, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = zdt1.checked_add(1.hour())?;\n assert_eq!(zdt2.to_string(), \"2024-03-10T03:30:00-04:00[America/New_York]\");\n\n Ok(())\n}\n```\n\nIf you use `time-tz`, then you can make the above example with `time` work:\n\n```rust\nuse anyhow::Context;\nuse time::{ext::NumericalDuration, macros::datetime, Duration};\nuse time_tz::{OffsetDateTimeExt, Tz};\n\nfn main() -> anyhow::Result<()> {\n let tz = time_tz::timezones::db::america::NEW_YORK;\n\n // We create a fixed datetime for testing purposes,\n // but it\'s the same sort of value we would get back\n // from `OffsetDateTime::now_local()`.\n let dt1 = datetime!(2024-03-10 01:30:00 -05:00);\n let dt2 = dt1.checked_add(1.hours())\n .context(\"datetime arithmetic failed\")?\n .to_timezone(tz);\n assert_eq!(dt2.to_string(), \"2024-03-10 3:30:00.0 -04:00:00\");\n\n Ok(())\n}\n```\n\nBut note that you have to be careful to call `.to_timezone()` before printing\nthe datetime. In particular, there is no time zone aware datetime type.\n\nIn my comparison with Chrono I went through a lot of examples involving\ntime zones. I did this because Chrono supports DST safe arithmetic generally,\nbut with a lot of nuanced differences from what Jiff supports. Conversely,\n`time` doesn\'t have a time zone aware datetime type. And the time zone support\nprovided by `time-tz` is extremely limited. So at this time, in this document,\nwe won\'t belabor the point.\n\n### `time` supports its own custom format description\n\nSome users may find this easier to use:\n\n```rust\nuse time::{macros::format_description, OffsetDateTime};\n\nfn main() -> anyhow::Result<()> {\n let format = format_description!(\n \"[year]-[month]-[day] [hour]:[minute]:[second] \\\n [offset_hour sign:mandatory]:[offset_minute]:[offset_second]\"\n );\n let odt = OffsetDateTime::parse(\"2024-07-11 22:49:00 -04:00:00\", &format)?;\n assert_eq!(odt.to_string(), \"2024-07-11 22:49:00.0 -04:00:00\");\n\n Ok(())\n}\n```\n\nJiff does support a `strptime`/`strftime` style API via the\n`jiff::fmt::strtime` module:\n\n```rust\nuse jiff::ZonedDateTime;\n\nfn main() -> anyhow::Result<()> {\n let zdt = ZonedDateTime::strptime(\n \"%Y-%m-%d %H:%M:%S %:z\",\n \"2024-07-11 22:49:00 -04:00:00\",\n )?;\n assert_eq!(zdt.to_string(), \"2024-07-11T22:49:00-04:00[-04:00]\");\n\n Ok(())\n}\n```\n\n`time` also supports `strptime`/`strftime` style APIs:\n\n```rust\nuse time::OffsetDateTime;\n\nfn main() -> anyhow::Result<()> {\n // I don\'t believe `time` supports `%:z`, so we just drop the colons here.\n let format = time::format_description::parse_strftime_borrowed(\n \"%Y-%m-%d %H:%M:%S %z\"\n )?;\n let odt = OffsetDateTime::parse(\"2024-07-11 22:49:00 -0400\", &format)?;\n assert_eq!(odt.to_string(), \"2024-07-11 22:49:00.0 -04:00:00\");\n\n Ok(())\n}\n```\n\n### Jiff supports rounding datetimes\n\nWe use a `ZonedDateTime` with a `TimeZone` that has a fixed offset. This is\nsame as `time`\'s `OffsetDateTime` type:\n\n```rust\nuse jiff::{civil::date, tz::{self, TimeZone}, Unit, ZonedDateTime};\n\nfn main() -> anyhow::Result<()> {\n let tz = TimeZone::fixed(tz::offset(-4));\n let zdt1 = date(2024, 7, 11).at(16, 46, 0, 0).to_zoned_datetime(tz)?;\n let zdt2 = zdt1.round(Unit::Hour)?;\n assert_eq!(zdt2.to_string(), \"2024-07-11T17:00:00-04:00[-04:00]\");\n\n Ok(())\n}\n```\n\nNote though that because Jiff has support for time zones, you generally\nshouldn\'t need to (and shouldn\'t _want_ to) use fixed offset datetimes. It\'s\nbecause they don\'t take time zone rules into account and thus do not provide\nDST safe arithmetic. Instead, the code above should be written like this\n(unless you have a very specific reason to do otherwise):\n\n```rust\nuse jiff::{civil::date, Unit};\n\nfn main() -> anyhow::Result<()> {\n // Can also use `.to_zoned_datetime(TimeZone::system())` to use your\n // system\'s default time zone.\n let zdt1 = date(2024, 7, 11).at(16, 46, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = zdt1.round(Unit::Hour)?;\n assert_eq!(zdt2.to_string(), \"2024-07-11T17:00:00-04:00[America/New_York]\");\n\n Ok(())\n}\n```\n\nFrom here on, we won\'t use fixed offset datetimes in order to avoid encouraging\ntheir use.\n\nThe `time` crate has no rounding APIs.\n\n### Jiff supports rounding durations\n\nIn Jiff, one can round the duration computed between two datetimes\n\n```rust\nuse jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2001, 11, 18).at(8, 30, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = date(2024, 7, 11).at(22, 38, 0, 0).in_tz(\"America/New_York\")?;\n\n let round_options = ZonedDateTimeDifference::new(&zdt2)\n .largest(Unit::Year)\n .smallest(Unit::Day)\n .mode(RoundMode::HalfExpand);\n let span = zdt1.until(round_options)?;\n assert_eq!(span, 22.years().months(7).days(24).fieldwise());\n\n Ok(())\n}\n```\n\nThe `time` crate has no rounding APIs.\n\n### Jiff provides support for calendar arithmetic\n\nWith Jiff, you can add durations with calendar units:\n\n```rust\nuse jiff::{civil::date, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n let zdt1 = date(2024, 7, 11).at(21, 0, 0, 0).in_tz(\"America/New_York\")?;\n let zdt2 = zdt1.checked_add(2.years().months(6).days(1))?;\n assert_eq!(zdt2.to_string(), \"2027-01-12T21:00:00-05:00[America/New_York]\");\n\n Ok(())\n}\n```\n\nThe `time` crate does provide a way to construct a `Duration` from units of\ndays via `Duration::days`, but this of course requires assuming that all days\nare 24 hours long. And `time` does not support adding years or months.\n\n### Jiff supports conveniently re-balancing durations\n\nAside from calendar arithmetic, Jiff also supports re-balancing durations\nbased on what you want the largest unit to be:\n\n```rust\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n // Balance down to seconds.\n let span1 = 4.hours().minutes(36).seconds(59);\n let span2 = span1.round(SpanRound::new().largest(Unit::Second))?;\n assert_eq!(span2, 16_619.seconds().fieldwise());\n\n // Now go back by balancing up to hours.\n let span1 = 16_619.seconds();\n let span2 = span1.round(SpanRound::new().largest(Unit::Hour))?;\n assert_eq!(span2, 4.hours().minutes(36).seconds(59).fieldwise());\n\n Ok(())\n}\n```\n\nThe `time` crate\'s `Duration` type can go from bigger units down to smaller\nunits easily enough:\n\n```rust\nuse time::{ext::NumericalDuration, Duration};\n\nfn main() -> anyhow::Result<()> {\n let span = 4.hours() + 36.minutes() + 59.seconds();\n assert_eq!(span.whole_seconds(), 16_619);\n Ok(())\n}\n```\n\nBut going from smaller units back up to larger units is difficult:\n\n```rust\nuse time::{ext::NumericalDuration, Duration};\n\nfn main() -> anyhow::Result<()> {\n let span = 16_619.seconds();\n assert_eq!(span.whole_hours(), 4);\n assert_eq!(span.whole_minutes(), 276);\n assert_eq!(span.whole_seconds(), 16_619);\n\n Ok(())\n}\n```\n\nNotice that the accessors just report how many whole units the span is. You\ncan\'t get the span broken down into smaller units. To achieve that, you need to\ndo the arithmetic yourself:\n\n```rust\nuse time::{convert::{Hour, Minute, Second}, ext::NumericalDuration, Duration};\n\nfn main() -> anyhow::Result<()> {\n let mut span = 16_619.seconds();\n assert_eq!(span.whole_hours(), 4);\n assert_eq!(span.whole_minutes() % Minute::per(Hour) as i64, 36);\n assert_eq!(span.whole_seconds() % Second::per(Minute) as i64, 59);\n\n Ok(())\n}\n```\n\n### Jiff is generally faster than `time`\n\nWhen it comes to parsing and printing, Jiff is generally faster than `time`\nalthough not always. `time` is sometimes faster than Jiff on date arithmetic,\nbut not by much. (Some of these may be due to faster equality comparisons on\ndate values, on which `time` is legitimately faster at than Jiff at present.)\n\nThe following results were collected with `time 0.3.47`.\n\n```text\n$ cd bench\n$ cargo bench -- --save-baseline baseline\n[.. snip ..]\n$ critcmp base -g \'(.*)/(?:jiff|time)$\'\ngroup baseline//time baseline//jiff\n----- -------------- --------------\ncivil_datetime/add_days/diffyear/duration 1.00 7.8\u{b1}0.08ns ? ?/sec 1.67 12.9\u{b1}0.19ns ? ?/sec\ncivil_datetime/add_days/diffyear/span 1.00 18.0\u{b1}0.28ns ? ?/sec\ncivil_datetime/add_days/sameyear/duration 1.00 7.8\u{b1}0.11ns ? ?/sec 1.66 12.9\u{b1}0.16ns ? ?/sec\ncivil_datetime/add_days/sameyear/span 1.00 18.0\u{b1}0.25ns ? ?/sec\ndate/add_days/diffyear/duration 1.00 3.8\u{b1}0.02ns ? ?/sec 1.67 6.3\u{b1}0.04ns ? ?/sec\ndate/add_days/diffyear/span 1.00 4.9\u{b1}0.05ns ? ?/sec\ndate/add_days/one/duration 1.00 3.8\u{b1}0.03ns ? ?/sec 1.38 5.2\u{b1}0.03ns ? ?/sec\ndate/add_days/one/span 1.00 5.8\u{b1}0.06ns ? ?/sec\ndate/add_days/sameyear/duration 1.00 3.8\u{b1}0.04ns ? ?/sec 1.68 6.4\u{b1}0.07ns ? ?/sec\ndate/add_days/sameyear/span 1.00 4.9\u{b1}0.05ns ? ?/sec\ndate/days_in_month/leap/feb 1.90 1.1\u{b1}0.01ns ? ?/sec 1.00 0.6\u{b1}0.03ns ? ?/sec\ndate/days_in_month/leap/nofeb 2.70 1.0\u{b1}0.01ns ? ?/sec 1.00 0.4\u{b1}0.00ns ? ?/sec\ndate/days_in_month/noleap/feb 2.78 1.1\u{b1}0.02ns ? ?/sec 1.00 0.4\u{b1}0.01ns ? ?/sec\ndate/days_in_month/noleap/nofeb 2.70 1.0\u{b1}0.02ns ? ?/sec 1.00 0.4\u{b1}0.00ns ? ?/sec\ndate/difference_days/duration 1.00 2.1\u{b1}0.02ns ? ?/sec 1.41 2.9\u{b1}0.04ns ? ?/sec\ndate/difference_days/span 1.00 2.4\u{b1}0.03ns ? ?/sec\ndate/tomorrow/diff-month 1.00 0.4\u{b1}0.02ns ? ?/sec 3.42 1.4\u{b1}0.01ns ? ?/sec\ndate/tomorrow/diff-year 1.00 1.0\u{b1}0.01ns ? ?/sec 1.59 1.5\u{b1}0.01ns ? ?/sec\ndate/tomorrow/same-month 1.00 0.4\u{b1}0.00ns ? ?/sec 2.25 0.9\u{b1}0.01ns ? ?/sec\ndate/yesterday/diff-month 1.00 0.4\u{b1}0.01ns ? ?/sec 3.65 1.4\u{b1}0.02ns ? ?/sec\ndate/yesterday/diff-year 1.00 0.9\u{b1}0.01ns ? ?/sec 1.35 1.2\u{b1}0.02ns ? ?/sec\ndate/yesterday/same-month 1.00 0.4\u{b1}0.02ns ? ?/sec 2.06 0.8\u{b1}0.01ns ? ?/sec\ndatetime/add_years_months_days 1.00 29.1\u{b1}0.18ns ? ?/sec\nparse/civil_datetime 1.00 12.9\u{b1}0.19ns ? ?/sec 1.63 21.1\u{b1}0.19ns ? ?/sec\nparse/rfc2822 2.24 43.4\u{b1}1.90ns ? ?/sec 1.00 19.4\u{b1}0.15ns ? ?/sec\nparse/strptime/oneshot 1.00 62.2\u{b1}0.39ns ? ?/sec\nparse/strptime/prebuilt 1.00 73.7\u{b1}0.91ns ? ?/sec\nprint/civil_datetime 3.27 37.4\u{b1}0.32ns ? ?/sec 1.00 11.4\u{b1}0.04ns ? ?/sec\nprint/rfc2822/buffer 1.55 20.4\u{b1}0.08ns ? ?/sec 1.00 13.2\u{b1}0.05ns ? ?/sec\nprint/rfc2822/to_string 3.61 72.0\u{b1}1.25ns ? ?/sec 1.00 19.9\u{b1}0.06ns ? ?/sec\nprint/rfc3339/buffer 1.33 22.1\u{b1}0.29ns ? ?/sec 1.00 16.7\u{b1}0.11ns ? ?/sec\nprint/rfc3339/to_string 2.91 68.1\u{b1}1.30ns ? ?/sec 1.00 23.4\u{b1}0.12ns ? ?/sec\nprint/rfc9557/buffer 1.00 16.2\u{b1}0.07ns ? ?/sec\nprint/rfc9557/to_string 1.00 22.6\u{b1}0.20ns ? ?/sec\nprint/strftime/oneshot/buffer 6.88 421.5\u{b1}1.39ns ? ?/sec 1.00 61.3\u{b1}0.82ns ? ?/sec\nprint/strftime/oneshot/to_string 5.59 434.0\u{b1}1.44ns ? ?/sec 1.00 77.7\u{b1}0.96ns ? ?/sec\nprint/strftime/oneshot/zoned 1.00 74.6\u{b1}1.07ns ? ?/sec\nprint/strftime/prebuilt/buffer 1.00 97.7\u{b1}0.99ns ? ?/sec\nprint/strftime/prebuilt/buffer/bespoke 1.00 105.8\u{b1}1.45ns ? ?/sec\nprint/strftime/prebuilt/to_string 1.00 165.3\u{b1}1.19ns ? ?/sec\nprint/strftime/prebuilt/to_string/bespoke 1.00 175.0\u{b1}1.79ns ? ?/sec\ntimestamp/add_time_secs/duration 3.82 9.6\u{b1}0.04ns ? ?/sec 1.00 2.5\u{b1}0.03ns ? ?/sec\ntimestamp/add_time_secs/span 1.00 3.7\u{b1}0.05ns ? ?/sec\ntimestamp/add_time_subsec/duration 3.33 9.7\u{b1}0.09ns ? ?/sec 1.00 2.9\u{b1}0.03ns ? ?/sec\ntimestamp/add_time_subsec/span 1.00 7.8\u{b1}0.08ns ? ?/sec\ntimestamp/every_hour_in_week/byhand 14.30 1530.8\u{b1}16.96ns ? ?/sec 1.00 107.1\u{b1}0.74ns ? ?/sec\ntimestamp/every_hour_in_week/series 1.00 105.8\u{b1}1.01ns ? ?/sec\ntimestamp/from_seconds/integer 11.69 4.4\u{b1}0.03ns ? ?/sec 1.00 0.4\u{b1}0.01ns ? ?/sec\ntimestamp/to_civil_datetime_offset_conversion 1.00 3.9\u{b1}0.03ns ? ?/sec 1.49 5.8\u{b1}0.04ns ? ?/sec\ntimestamp/to_civil_datetime_offset_holistic 1.00 4.6\u{b1}0.03ns ? ?/sec 1.04 4.8\u{b1}0.04ns ? ?/sec\nzoned/fixed_offset_add_time/duration 1.00 9.6\u{b1}0.09ns ? ?/sec 1.06 10.3\u{b1}0.08ns ? ?/sec\nzoned/fixed_offset_add_time/span 1.00 16.9\u{b1}0.12ns ? ?/sec\nzoned/fixed_offset_to_civil_datetime 1.00 0.6\u{b1}0.00ns ? ?/sec 7.32 4.2\u{b1}0.01ns ? ?/sec\nzoned/fixed_offset_to_timestamp 6.08 1.8\u{b1}0.02ns ? ?/sec 1.00 0.3\u{b1}0.01ns ? ?/sec\n```\n\nQuestions about benchmarks are welcome in\n[Discussions on GitHub](https://github.com/BurntSushi/jiff/discussions).\n\n## [`hifitime`](https://docs.rs/hifitime) (v3.9.0)\n\n`hifitime` is a datetime library with a focus on engineering and scientific\ncalculations where general relativity and time dilation matter. It supports\nconversion between many different time scales: TAI, Terrestrial Time, UTC, GPST\nand more. It also supports leap seconds.\n\nFor the following comparisons, a `Cargo.toml` with the following dependencies\nshould be able to run any of the programs in this section:\n\n```toml\nanyhow = \"1.0.81\"\nhifitime = \"3.9.0\"\njiff = { version = \"0.2.0\", features = [\"serde\"] }\n```\n\n### Time zone database integration\n\nLike the `time` crate, `hifitime` does not support time zones and does not have\nany integration with the Time Zone Database. `hifitime` doesn\'t have any\nequivalent to `OffsetDateTime` like in `time` either. The only datetime type\nthat `hifitime` has is `Epoch`, and it is an absolute time. While you can\nconvert between it and civil time (assuming civil time is in UTC), there is no\ndata type in `hifitime` for representing civil time.\n\n### `hifitime` supports leap seconds\n\nIn particular, when computing a duration from two `Epoch` values that spans\na positive leap second (a second gets repeated), `hifitime` will correctly\nreport the accurate duration. With that said, to get an accurate duration, one\nof the two time scales has to be converted to to TAI (or another time scale\nwhich does not have leap seconds):\n\n```rust\nuse hifitime::{Duration, Epoch, TimeScale};\n\nfn main() -> anyhow::Result<()> {\n let e1: Epoch = \"2015-06-30T23:00:00 UTC\".parse()?;\n let e2: Epoch = \"2015-07-01T00:00:00 UTC\".parse()?;\n let e2 = e2.to_time_scale(TimeScale::TAI);\n\n let duration = e2 - e1;\n assert_eq!(duration, Duration::from_seconds(3_601.0));\n\n Ok(())\n}\n```\n\nJiff, however, [does not support leap seconds][jiff-leap-seconds]:\n\n```rust\nuse jiff::{SignedDuration, Timestamp};\n\nfn main() -> anyhow::Result<()> {\n let ts1: Timestamp = \"2015-06-30T23:00:00Z\".parse()?;\n let ts2: Timestamp = \"2015-07-01T00:00:00Z\".parse()?;\n let span = ts2 - ts1;\n assert_eq!(span, SignedDuration::from_secs(3_600));\n\n Ok(())\n}\n```\n\nSo in this case, Jiff reports `3,600` seconds as the duration, but the _actual_\nduration was `3,601` seconds, as reported by `hifitime`.\n\n[jiff-leap-seconds]: https://github.com/BurntSushi/jiff/issues/7\n\n### Jiff makes checked or saturating arithmetic explicit\n\nFor Jiff, whether you want to saturate or not is an explicit part of the API.\nAnd implementations of the `Add` operator will panic on overflow:\n\n```rust\nuse jiff::{Timestamp, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n let ts = Timestamp::MAX;\n assert!(ts.checked_add(1.day()).is_err());\n assert_eq!(ts.saturating_add(1.hour())?, ts);\n\n Ok(())\n}\n```\n\nIn contrast, `hifitime` appears to use saturating arithmetic everywhere (I\'ve\nnot been able to find this behavior documented though, so I\'m not clear on what\nthe intended semantics are):\n\n```rust\nuse hifitime::{Duration, Epoch};\n\nfn main() -> anyhow::Result<()> {\n let e1 = Epoch::from_unix_seconds(f64::MAX);\n let e2 = e1 + Duration::from_days(1.0);\n assert_eq!(e1, e2);\n\n Ok(())\n}\n```\n\n\n## [`icu`](https://docs.rs/icu) (v1.5.0)\n\nThe ICU4X project fulfils a slightly different need than `jiff`. Its main\nfeatures are calendrical calculations (`icu::calendar`), supporting conversions\nbetween different calendar systems such as Gregorian, Buddhist, Islamic,\nJapanese, etc., as well as localized datetime formatting (`icu::datetime`).\n\nIt does not perform datetime or time-zone arithmetic, and does not have a\ntimestamp or duration type.\n\n`icu` can be used to complement `jiff` when localized date formatting or\ncalendar conversions are required. To facilitate this, the\n[`jiff-icu`](https://docs.rs/jiff-icu) crate makes conversions between Jiff\nand ICU4X data types seamless. For example, to do localization starting from\na Jiff data type:\n\n```text\nuse icu::{\n calendar::{japanese::Japanese, DateTime},\n datetime::TypedDateTimeFormatter,\n locid::locale,\n};\nuse jiff::Timestamp;\nuse jiff_icu::ConvertFrom as _;\n\nfn main() -> anyhow::Result<()> {\n let ts: Timestamp = \"2024-09-10T23:37:20Z\".parse()?;\n let zoned = ts.in_tz(\"Asia/Tokyo\")?;\n\n // Create ICU datetime.\n let datetime = DateTime::convert_from(zoned.datetime());\n\n // Convert to Japanese calendar.\n let japanese_datetime = DateTime::new_from_iso(datetime, Japanese::new());\n\n // Format for the en-GB locale.\n let formatter = TypedDateTimeFormatter::try_new(\n &locale!(\"en-GB\").into(),\n Default::default(),\n )?;\n\n // Assert that we get the expected result.\n assert_eq!(\n formatter.format(&japanese_datetime).to_string(),\n \"Sept 11, 6 Reiwa, 08:37:20\",\n );\n\n Ok(())\n}\n```\n\nThe above example requires the following dependency specifications:\n\n```toml\nanyhow = \"1.0.81\"\nicu = { version = \"1.5.0\", features = [\"std\"] }\njiff = { version = \"0.1.0\", features = [\"serde\"] }\njiff-icu = { version = \"0.1.0\" }\n```\n"include_str!("../COMPARE.md")]
804pub mod comparison {}
805#[doc = "# The API design rationale for Jiff\n\nThis document discusses some of the design decisions that led to Jiff\'s API.\nThe purpose of writing this document is to help folks understand _why_ Jiff\'s\nAPI is the way it is, above and beyond \"Jiff did it this way to match\n[Temporal].\"\n\nThis document is written as an FAQ, although it is restricted in scope to the\nAPI design of Jiff. This isn\'t a FAQ for questions like, \"How do I add 1 day\nto a zoned datetime?\"\n\nUnlike \"[Comparison with other Rust datetime crates][comparison],\" this\ndocument is _opinionated_. That is, some value judgments are expressed that are\nopinion based, and on which reasonable people may disagree.\n\n\n## Why name the library \"jiff\"?\n\nI wanted something short and related to time for the library name. Most of the\n\"obvious\" names are taken.\n\nI thought a lot about phrases or words that had some connection to time. There\nare more than you think. One phrase I heard a lot as a kid who grew up in New\nEngland was, \"I\'ll be back in a jiff\" or \"I\'ll be back in a jiffy.\" The meaning\nof that phrase was, roughly, \"I\'ll be back very soon.\" So \"jiff\" refers to some\n\"short span of time.\" Since \"jiff\" was shorter than \"jiffy,\" that\'s what I went\nwith.\n\nJiff is pronounced like \"gif\" with a soft \"g,\" as in \"gem.\"\n\n\n## Why build another datetime library?\n\nAt the time of writing, there are four existing prominent datetime libraries\nfor Rust: [`chrono`], [`time`], [`hifitime`] and [`icu`]. \"[Comparison with\nother Rust datetime crates][comparison]\" goes over the \"facts of comparison\"\nbetween the crates (mostly for just `chrono` and `time`), but it intentionally\nleaves out value judgments. To answer this question, I have to introduce value\njudgments and my opinions on existing libraries. **These are opinions on which\nreasonable people can disagree.** Moreover, since these are opinions meant to\njustify an alternative, these opinions tend to be oriented on the faults (as\nthis author sees them) in existing crates as opposed to their benefits.\n\nBroadly speaking, my view on Rust datetime libraries was that they had reached\na local maximum, and there didn\'t seem to be much movement toward breaking out\nof that local maximum and getting to something that was categorically better.\nMuch of my thoughts revolve around not just the functionality provided, but\nalso the API design of these crates. Thus, I perceived a gap in the ecosystem\nthat I felt like I could fill.\n\nI\'ll share my brief thoughts on each crate. I\'ll cover \"why not contribute to\nan existing library and make it better\" in the next question.\n\n### `chrono`\n\nIn my view, Chrono is the closest to Jiff in terms of the functionality it\nprovides. It has some support for DST safe arithmetic for example, and even\nsome support for doing calendar math. But its support is incomplete. While one\ncan add units of days to Chrono datetimes, Chrono lacks the ability to do math\non multiple calendar units at the same time. Moreover, Chrono cannot _produce_\ncalendar durations between two time zone aware datetimes.\n\nMoreover, Chrono\'s integration with the [IANA Time Zone Database] is somewhat\nspotty. Support for it isn\'t included in the `chrono` crate itself, but\nis instead something you need to opt into with additional crates, such\nas [`chrono-tz`] or [`tzfile`]. And each crate comes with its own set of\ntrade-offs. `chrono-tz` embeds the entire database into your binary and makes\nthe time zones available at compile time, while `tzfile` reads the database\nfrom your system\'s copy of the database (i.e., `/usr/share/zoneinfo` on Unix).\nIn my view, this creates a difficult situation for non-expert users of Chrono\nwhere the \"right\" choice isn\'t obvious. In my opinion, the _default_ should be\nto read time zone transition data from the system\'s copy of the database on\ndisk, and only bundle the data into the binary as a last resort when a copy of\nthe database isn\'t reliably available (like on Windows). The main reason for\nthis is that the database is frequently updated (a few times each year) since\nthe rules for time zone transitions can change. If that time zone data is\nembedded into your binary, then you need to 1) wait for `chrono-tz` to update\ntheir data and 2) re-compile your application and ship it out to users.\n\nIn contrast, Jiff _abstracts_ the method of time zone data discovery. That\nis, there are no API differences between \"read time zone data from the system\ndatabase\" and \"read embedded time zone data.\" Of course, Jiff provides options\nto choose which method to use (like forcing bundling on Unix), but all of this\nis transparent to users of Jiff itself. That is, _Jiff tries to do the right\nthing by default_. There\'s no need to go off and find a different crate to\nhandle time zone data for you.\n\nWhile on the topic of time zones, Chrono also has no support for serializing\nIANA time zone identifiers. This implies that if you have a time zone aware\ndatetime in Chrono (whether by `chrono-tz` or `tzfile`), then you can\'t\nlosslessly serialize and deserialize it. Namely, serialization will lose\nthe time zone the datetime is associated with, and instead only include\nthe offset. Then when it\'s deserialized, you\'re left with an offset-only\ndatetime that won\'t, for example, provide DST safe arithmetic based on the\noriginal time zone. In contrast, Jiff follows [RFC 9557] to support embedding\nIANA time zone identifiers in the serialized representation. For example,\n`2024-07-21T17:11-04[America/New_York]`.\n\nThere are a variety of other things that Jiff supports which Chrono does\nnot, but that\'s covered in [the comparison section between Jiff and\nChrono][comparison-chrono].\n\nAs for API design, I found Chrono\'s API to be overengineered and difficult to\ndeal with. This is a frustratingly vague complaint, but here are some things\nthat I believe contribute to that opinion:\n\n* I\'ve used Chrono for various things, and I found it very difficult to figure\nout from its API what the right operations to use were.\n* Chrono has been steadily deprecating huge portions of its API in favor of\nfallible routines. I find the resulting documentation difficult to read and the\nnaming to be very clunky.\n* The fallible routines return a mixture of `Option<T>` and `Result<T, E>`.\nThis is frustrating in my experience because the `Option<T>` _usually_ needs to\nbe converted to a human readable error message, and I think the library should\nmake use of its contextual information to do this for you. Indeed, Jiff rarely\nreturns `Option<T>` and instead returns `Result<T, E>` with a contextualized\nhuman readable error message. (Although I\'m sure the error messages could use a\nlot of improvement.)\n* I find the use of generics in Chrono to be overengineered. It has some\nkey benefits, for example, making the notion of \"time zone\" an open concept\nthat can be defined by users of the crate. But in my opinion, this is rarely\nneeded. The Chrono crate ecosystem makes use of this via the `chrono-tz` and\n`tzfile` crates, but Jiff covers both of those use cases (broadly speaking)\nautomatically.\n* Chrono overall puts a large emphasis on \"fixed offset\" datetimes, but these\nare rarely the right abstraction to use. It\'s possible this is due to the fact\nthat IANA time zone support is external to Chrono itself. Instead, Jiff just\ntries to do the right thing by default, and gives users IANA time zone support\nout of the box. Jiff does support fixed offset datetimes as well, but they are\nde-emphasized.\n* I find generic traits like `Datelike` to also be very confusing because they\nsplit the APIs of types like `NaiveDate` into concrete methods and generic\nmethods, and there\'s no obvious rhyme or reason as to how those methods are\nsplit up.\n* Chrono\'s API doesn\'t offer clean on-ramps from civil (\"naive\") datetimes to\ntime zone aware datetimes. For example, Chrono provides `NaiveDate::succ_opt`\nto get the next day, but this method isn\'t available on `NaiveDateTime` or\n`DateTime`. Instead, to implement it correctly on `DateTime`, you have to get\nthe naive date, get the date for tomorrow via `succ_opt`, and then convert it\nback to the same `NaiveDateTime` and finally make it time zone aware by\napplying the original time zone to it. In contrast, in Jiff, it\'s just a matter\nof calling `ZonedDateTime::tomorrow`. Indeed, (almost) any method you can call\non `civil::Date` in Jiff is also available on `civil::DateTime` and likewise\nfor `ZonedDateTime`. This makes transitioning between datetime types very easy.\nChrono almost appears to provide this same experience via traits like\n`Datelike`, but doesn\'t fully commit and, in my opinion, the end result has a\nfeeling of arbitrariness to it.\n* Chrono lacks a standard timestamp type. You can approximate this with a\n`DateTime<Utc>`, but it\'s a more complicated type that includes a full datetime\nrepresentation. In contrast, Jiff provides a `Timestamp` type for when you just\nwant the number of seconds from the Unix epoch. And then integrates it with the\nrest of the datetime types in a consistent way.\n\n### `time`\n\nMy main gripe with the `time` crate is that it has very limited\n[IANA Time Zone Database] support. This means it is difficult to do DST safe\narithmetic. Consequently, it emphasizes the use of \"fixed offset\" datetimes\nin a similar fashion as Chrono, except `time` does not provide any extension\nmechanism like a `TimeZone` trait. In my view, fixed offset datetimes are\nrarely the right thing to use. In my opinion, this makes writing correct\ndatetime code with the `time` crate rather difficult. In contrast, Jiff\nprovides full [IANA Time Zone Database] support, and it should be very\nrare to need fixed offset datetimes (although Jiff does support them via\n`TimeZone::fixed`).\n\n(Note that at time of writing, there does exist an unofficial [`time-tz`]\ncrate that provides very limited support for time zones in concert with the\n`time` crate. However, there is no time zone aware datetime type and no way to\ndistinguish between calendar arithmetic and time arithmetic across daylight\nsaving time boundaries. The `time-tz` crate borrows the design of `chrono-tz`,\nand thus has all of its downsides as well.)\n\nI overall find the API of `time` to be easier to understand than Chrono, likely\nbecause there are fewer generics. But `time` is also supporting a lot less than\nChrono and Jiff (because of the missing time zone support in `time` itself).\n\nAs with Chrono, I\'ve done a\n[more detailed comparison between Jiff and `time`][comparison-time].\n\n### `hifitime`\n\n`hifitime` is more of a specialized datetime library suited to scientific\napplications, and so while Jiff and `hifitime` have overlapping use cases,\n`hifitime` fundamentally has a different target demographic than Jiff. As noted\nin a [comparison between Jiff and `hifitime`][comparison-hifitime], `hifitime`\ndoesn\'t have any time zone support, but it does support conversions between\nmany different time scales and leap second support. Leap second support, in\nthis context, means that the durations between two points in time take leap\nseconds into account in `hifitime`, but Jiff pretends as if they don\'t exist.\n\nIn terms of building a new datetime library, I felt like `hifitime` wasn\'t\nreally targeting the \"general purpose datetime library\" use case that I felt\n`chrono` and `time` were. And so, whether it existed or not didn\'t really\nimpact whether another _general purpose_ datetime library should be built.\n\n### `icu`\n\n`icu` is, as I understand it, still under construction with respect to datetime\nsupport. For example, it doesn\'t have [IANA Time Zone Database] support.\nBut, it does support locale aware formatting of datetimes and non-Gregorian\ncalendars.\n\nWhen I started working on Jiff, I didn\'t have a good understanding of what the\n`icu` crate offers. I still don\'t really. In part because the API is difficult\nfor me to understand and in part because I haven\'t dedicated a ton of time to\nstudying its API. But either way, I don\'t think it is currently in a position\nto be a general purpose datetime library and I wasn\'t clear on what its goals\nwere.\n\nSince I haven\'t spent a lot of time with `icu`, I didn\'t have much to say about\nit in my [comparison with it and Jiff][comparison-icu].\n\n\n## Why not contribute to an existing library instead of building a new one?\n\nGiven that Rust already has at least two prominent datetime libraries, doesn\'t\nadding another one just make things worse? And why not contribute to an\nexisting library to make it better instead of starting over from scratch?\n\nI first want to say that I acknowledge that throwing a new crate into the\necosystem, and adding yet another choice, does actually come with downsides.\nThere is a cost to having too many choices, and when possible, I do believe it\nis better to improve an existing project rather than start a new one.\n\nImproving existing projects can be difficult. Jiff has a different design than\nboth `chrono` and `time`. Evolving either one of those crates into what Jiff is\nwould, in my view, require a huge amount of resources. Not just in time, but in\nsocial capital as well. Because it wouldn\'t be greenfield development done by\none person making all of the design choices, but instead someone from outside\nthe project trying to convince the maintainers of established projects to move\nin a radically different direction. I know what it\'s like to be on the side of\nmaintaining an established API for a library with a lot of users. There is a\nhuge inertial cost to making sweeping API changes.\n\nMoreover, when I started Jiff, I was not a domain expert in datetime libraries\nor datetime handling in general. Therefore, my opinion that `chrono` and `time`\n_could_ be better would arguably not carry a lot of weight. It was only through\nthe process of actually building a datetime library did I learn enough to form\nnuanced opinions about the status quo. When I started, my opinions were much\nmore vague (but still strong enough to start this project).\n\nOn top of all of this, I was _intrinsically_ motivated to work on this problem.\nI found it very interesting, and especially because I perceived there to be a\ngap in the ecosystem that I thought I could fill in. I had a vision for what\na datetime library _should_ look like. And it took a lot of iteration to get\nfrom my initial vision to something that works in practice. Doing this on an\nexisting datetime library with real users would be extremely difficult.\n\nAnd speaking as someone who has had folks publish _better_ versions of some of\nmy own crates, I know what it\'s like to be on the other end of this. Sometimes\nyou just have to start fresh.\n\n\n## Are there any published alternative perspectives on Rust datetime libraries?\n\nHere\'s a list. More may be added in the future:\n\n* [Commentary from the original author of the `chrono` crate.][alt1]\n\n[alt1]: https://github.com/BurntSushi/jiff/issues/63\n\n\n## Why are there two duration types?\n\nThe two duration types provided by Jiff are `Span` and `SignedDuration`. A\n`SignedDuration` is effectively identical to a `std::time::Duration`, but it\'s\nsigned instead of unsigned. A `Span` is also a duration type, but is likely\ndifferent than most other duration types you\'ve used before.\n\nWhile a `SignedDuration` can be thought of as a single integer corresponding\nto the number of nanoseconds between two points in time, a `Span` is a\ncollection of individual unit values that combine to represent the difference\nbetween two point in time. Stated more concretely, while the spans `2\nhours` and `120 minutes` both correspond to the same duration of time, when\nrepresented as a Jiff `Span`, they correspond to two distinct values in\nmemory. This is something that is fundamentally not expressible by a type\nlike `SignedDuration`, where `2 hours` and `120 minutes` are completely\nindistinguishable.\n\nOne of the key advantages of a `Span` is that it can represent units of\nnon-uniform length. For example, not every month has the same number of days,\nbut a `Span` can still represent units of months because it tracks the values\nof each unit independently. For example, Jiff is smart enough to know that the\ndifference between `2024-03-01` and `2024-04-01` is the same number of months\nas `2024-04-01` and `2024-05-01`, even though the number of days is different:\n\n```rust\nuse jiff::{civil::date, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n let date1 = date(2024, 3, 1);\n let date2 = date(2024, 4, 1);\n let date3 = date(2024, 5, 1);\n\n // When computing durations between `Date` values,\n // the spans default to days.\n assert_eq!(date1.until(date2)?, 31.days().fieldwise());\n assert_eq!(date2.until(date3)?, 30.days().fieldwise());\n\n // But we can request bigger units!\n assert_eq!(date1.until((Unit::Month, date2))?, 1.month().fieldwise());\n assert_eq!(date2.until((Unit::Month, date3))?, 1.month().fieldwise());\n\n Ok(())\n}\n```\n\nWhile most folks are very in tune with the fact that years and months have\nnon-uniform length, a less obvious truth is that days themselves also have\nnon-uniform length in the presence of time zones. For example, `2024-03-10` in\n`America/New_York` was only 23 hours long (the region entered daylight saving\ntime, creating a gap in time), while `2024-11-03` was 25 hours long (the region\nleft daylight saving time, creating a fold in time). Being unaware of this\ncorner case leads to folks assuming that \"1 day\" and \"24 hours\" are _always_\nexactly equivalent. But they aren\'t. The design of Jiff leans into this and\nensures that so long as you\'re using `Span` to encode a concept of days and are\ndoing arithmetic with it on `ZonedDateTime` values, then you can never get it\nwrong. Jiff will always take time zones into account when dealing with units of\ndays or bigger.\n\nThe design of `Span` comes from [Temporal], which [uses only one duration\ntype][temporal-one-duration]. From that issue, there are some significant\nadvantages to using a `Span`. In my own words:\n\n* It more closely lines up with ISO 8601 durations, which themselves combine\ncalendar and clock units.\n* With a `Span`, it is very easy to move between `5 years 2 months` and\nthe number of hours in that same span.\n* Jiff\'s `Span` type specifically represents each unit as distinct from the\nothers. In contrast, most absolute duration types (like `std::time::Duration`\nand Jiff\'s own `SignedDuration`), are \"just\" a 96-bit integer number of\nnanoseconds. This means that, for example, `1 hour 30 minutes` is impossible to\ndifferentiate from `90 minutes`. But depending on the use case, you might want\none or the other. Jiff\'s `Span` design (copied from Temporal) enables users\nto express durations in whatever units they want. And this expression can be\nmanipulated via APIs like `Span::round` in intuitive ways.\n\nA `SignedDuration` is still useful in some respects. For example, when you\nneed tighter integration with the standard library\'s `std::time::Duration`\n(since a `SignedDuration` is the same, but just signed), or when you need\nbetter performance than what `Span` gives you. In particular, since a `Span`\nkeeps track of the values for each individual unit, it is a much heavier type\nthan a `SignedDuration`. It uses up more stack space and also required more\ncomputation to do arithmetic with it.\n\n\n## Why isn\'t there a `TimeZone` trait?\n\nFirst, let\'s start by explaining what a `TimeZone` is. In Jiff, a `TimeZone`\nis a concrete type that cannot be extended by users of Jiff. Instead, users of\nJiff are forced to use one of three different kinds of time zones:\n\n* A \"fixed offset\" time zone where the civil time for any particular instant\nis computed by simply adding or subtracting a fixed number of seconds from UTC.\nThe `TimeZone::fixed` constructor enables callers to build time zones with any\noffset within the limits imposed by Jiff.\n* A [POSIX time zone][POSIX TZ], typically set via the `TZ` environment\nvariable. These are rarely used by end users, but do provide a way to specify\na rule for when daylight saving time transitions occur thoughtout the year.\n(But it does not support historical transitions that might not conform to the\ncurrent rule.) The `TimeZone::posix` constructor enables callers to build a\n`TimeZone` with a POSIX time zone string.\n* [TZif formatted data][RFC 8536], usually from the\n[IANA Time Zone Database]. This data contains historical time zone transitions\nin addition to rules governing the future in the form of POSIX TZ strings.The\n`TimeZone::tzif` constructor enables callers to build a `TimeZone` with any\nTZif formatted data.\n\nThe `jiff::tz::TimeZoneDatabase` automatically looks for TZif formatted\nfiles in your system\'s copy of the IANA Time Zone Database, usually at\n`/usr/share/zoneinfo`. (On Windows, Jiff embeds a copy of the IANA Time Zone\nDatabase into the compiled artifact itself.)\n\nSo why isn\'t `TimeZone` a trait? Well, the above formulation should cover the\n_vast majority_ of use cases. And even if that doesn\'t cover everything, it\nis possible for callers to use `TimeZone::tzif` to construct arbitrary time\nzones by building their own TZif data. This is a somewhat large hurdle though,\nso if this is something that is commonly needed, I\'m open to exploring other\noptions for building custom time zones. For example, perhaps we introduce a way\nto describe time zone transitions in Rust code that can then be used to build a\n`TimeZone` directly. But, the benefit of TZif is that it is inter-operable and\na standard. There are tools that can build them.\n\nAn important thing to note here is that I actually approach questions like \"Why\nisn\'t `TimeZone` a trait?\" as instead \"Why _should_ `TimeZone` be a trait?\" In\nparticular, I personally perceive costs to introducing generics, especially on\na fundamental type in the crate. For example, if `TimeZone` were a trait, then\n`ZonedDateTime` would not be a concrete type. It would be generic over a type\nparameter that implements the `TimeZone` trait. This in turn implies that\nanyone _using_ a `ZonedDateTime` in their own types or APIs needs to think\nabout the `TimeZone` trait and likely incorporate it into their own type\nsignatures. This is because a `TimeZone` trait implies an open system that\ninfects everything it touches. The complexity isn\'t contained. But a concrete\n`TimeZone` type, like what Jiff has, encapsulates everything there is about\ntime zones.\n\n(Making `ZonedDateTime` generic over a type parameter with a _default_ type\ndoes contain the complexity in some cases, but not all. I explored using\ndefault type parameters in Jiff for supporting [leap\nseconds][github-issue-leap], and it was overall quite awkward in my opinion.)\n\nThe trade off is that we do give up some flexibility. For example, Chrono uses\na `TimeZone` trait design. This enables external crates to provide their own\nimplementations of the `TimeZone` trait. But the two principle instances of\nthis occurring, `chrono-tz` and `tzfile`, are both supported by Jiff itself.\nWith that said, one key advantage of Chrono\'s design is that it permits its\nzone aware datetime type (`DateTime<T>`) to be `Copy` if `T` is `Copy`. It is\nsomewhat difficult (although not literally impossible) to make a TZif-backed\ntime zone implement `Copy`, but a _reference_ to it is `Copy` and a reference\nto it can still implement Chrono\'s `TimeZone` trait. (And indeed, this is what\nthe `tzfile` crate does.) This ultimately leads to more flexibility compared to\nJiff, where its `ZonedDateTime` type embeds a `TimeZone` and a `TimeZone`\ncannot easily be made `Copy` without giving up something else.\n\nMy opinions on the costs of generics tend to overestimate them compared to many\nothers in my experience, so your mileage may vary on where you land on this\nissue. Buy in my opinion, being able to just write `ZonedDateTime` as a\nconcrete type without any generics is a huge win for comprehensibility.\n\n\n## Why doesn\'t `TimeZone` implement `Copy`?\n\nWhen initially setting out to build Jiff, I _really_ wanted the `TimeZone` type\nto implement `Copy`. The reason why I wanted it to implement `Copy` is because\nI wanted all datetime types to have \"plain old data\" semantics. That is, I want\ncallers to think of them as small immutable bits of data that can be freely\ncopied without worry. This makes APIs a little nicer because you can ask for a\n`ZonedDateTime` instead of a `&ZonedDateTime`, assuming the `ZonedDateTime`\ntype is small enough.\n\nBut, in order for `ZonedDateTime` to be `Copy`, it must be the case that\n`TimeZone` is `Copy`. This is because `ZonedDateTime` embeds a `TimeZone`.\nIndeed, this is the reason for its existence: it couples an instant in time\nwith a particular geographic region. This makes it possible to expose very\nergonomic high level APIs that don\'t require the caller to keep passing in a\n`TimeZone` value repeatedly.\n\nSo, how can a `TimeZone` be `Copy`? Well, both fixed offset and POSIX time\nzones could be `Copy`. There\'s no huge challenge in that. (Internally, a POSIX\ntime zone is not currently `Copy` because there\'s no reason for it given what\nwe\'re about to discuss.) The main challenge is the TZif-backed time zone. TZif\nformatted data can contain an arbitrary number of time zone transitions. There\nis just no way to avoid some kind of dynamic memory allocation.\n\nSince we need dynamic memory allocation, there is really only one way to\nmake it `Copy` at this point: introduce some kind of caching mechanism with\na small `Copy` identifier that lets us \"look up\" the time zone in some kind\nof global or thread-local cache. I thought a lot about how I might wire this\ntogether, and I could not come up with a satisfactory design. I believe\ngarbage collection is the main challenge, but also synchronization overhead\nfor accessing a time zone is likely also a problem. The nice benefit of the\n`TimeZone` type as it exists now is that it\'s just data. While _getting_ a\n`TimeZone` from a `TimeZoneDatabase` might require synchronization and possibly\neven I/O if the cache for it was invalidated, a `TimeZone` itself requires no\nsynchronization whatsoever to use it. It is just an `Arc` internally to make it\npointer-sized.\n\n\n## Why no `SystemZonedDateTime` or `OffsetZonedDateTime` types?\n\nSome datetime libraries have multiple different zone aware datetime types. Jiff\nopts to have just one, and embeds support for the different types of time zones\nthat most people will ever need into that one type. Jiff does this via the\n`TimeZone` type, which can be a fixed offset, a POSIX time zone or TZif-backed\n(usually from the [IANA Time Zone Database]).\n\n\n## Why doesn\'t Jiff support leap seconds?\n\nThe short summary is that the use cases for leap second support are rather\nlimited, and the effect they have on overall API complexity is quite large.\nThat is, I believe they would make the API of Jiff more complicated than the\nvalue they bring to the domain.\n\nA standard work-around for _part_ of the leap second problem---and usually the\none people care about---is to use custom TZif data that describes when each of\nthe leap seconds occurs. In effect, you can treat [TAI] as its own time zone.\nThis enables callers to compute accurate durations of time that span a leap\nsecond (positive or negative). And indeed, so long as you build that TZif\ndata, Jiff supports this via `TimeZone::tzif`.\n\nI wrote a lot more [about leap seconds on the issue\ntracker][github-issue-leap].\n\n\n## Why isn\'t there any integration with `std::time::Duration`?\n\nThe initial release of `jiff 0.1` originally left out any integration\npoints with `std::time::Duration`. Since then, `SignedDuration` has\nbeen added to Jiff. And `TryFrom` trait implementations have been added\nto both `SignedDuration` and `Span` to make conversions between it and\n`std::time::Duration` easier.\n\n\n## What are the `ZoneDifference` and `ZonedDateTimeRound` types for?\n\nThe `ZonedDateTimeDifference` and `ZonedDateTimeRound` are builders for\nexpressing the parameters to the functions `ZonedDateTime::{since, until}` and\n`ZonedDateTime::round`, respectively. For example, this:\n\n```rust\nuse jiff::{civil::date, ToSpan};\n\nlet zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz(\"America/New_York\")?;\nassert_eq!(zdt1.until(&zdt2)?, 744.hours().seconds(36).fieldwise());\n\n# Ok::<(), Box<dyn std::error::Error>>(())\n```\n\nIs equivalent to:\n\n```rust\nuse jiff::{civil::date, ToSpan, ZonedDateTimeDifference};\n\nlet zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz(\"America/New_York\")?;\nassert_eq!(\n zdt1.until(ZonedDateTimeDifference::new(&zdt2))?,\n 744.hours().seconds(36).fieldwise(),\n);\n\n# Ok::<(), Box<dyn std::error::Error>>(())\n```\n\nThe point of this is that `ZonedDateTimeDifference` permits specifying\nadditional configuration. For example, rounding the span returned:\n\n```rust\nuse jiff::{civil::date, ToSpan, Unit, ZonedDateTimeDifference};\n\nlet zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz(\"America/New_York\")?;\nassert_eq!(\n zdt1.until(ZonedDateTimeDifference::new(&zdt2).smallest(Unit::Minute))?,\n 744.hours().fieldwise(),\n);\n\n# Ok::<(), Box<dyn std::error::Error>>(())\n```\n\nBy using a dedicated type to represent the parameters, we can enable ergonomic\nuses of the API for common cases (by using `From<&ZonedDateTime> for\nZonedDateTimeDifference` trait implementations) while still permitting callers\nto provide additional configuration.\n\nAn alternative API would be to remove the additional parameters to\n`ZonedDateTime::until`, and instead require callers to do span rounding\nthemselves explicitly. But this is more verbose and requires repeating the\ncorrect zoned datetime to indicate how to interpret non-uniform units. For\nexample, instead of this:\n\n```rust\nuse jiff::{civil::date, ToSpan, Unit, ZonedDateTimeDifference};\n\nlet zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz(\"America/New_York\")?;\nlet diff = ZonedDateTimeDifference::new(&zdt2)\n .largest(Unit::Month)\n .smallest(Unit::Minute);\nassert_eq!(zdt1.until(diff)?, 1.month().fieldwise());\n\n# Ok::<(), Box<dyn std::error::Error>>(())\n```\n\nOne would need to do this:\n\n```rust\nuse jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit};\n\nlet zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz(\"America/New_York\")?;\nlet span = zdt1.until(&zdt2)?;\nlet rounded = span.round(\n SpanRound::new()\n .largest(Unit::Month)\n .smallest(Unit::Minute)\n .relative(&zdt1)\n .mode(RoundMode::Trunc),\n)?;\nassert_eq!(rounded, 1.month().fieldwise());\n\n# Ok::<(), Box<dyn std::error::Error>>(())\n```\n\nThis is somewhat fiddly and easy to get wrong. Moreover, the\n`ZonedDateTime::until` API, when rounding is enabled, will automatically use\n`RoundMode::Trunc`, since this is what usually expects when computing the span\nbetween two datetimes. But span rounding uses `RoundMode::HalfExpand` by\ndefault, corresponding to how you were likely taught to round in school.\n(Rounds to the nearest unit, with ties breaking away from zero.)\n\nSimilar reasoning applies to other \"parameter builder\" types like\n`civil::DateTimeDifference` as well.\n\n\n## Why isn\'t `Timestamp` called `Instant`?\n\nThe main reason why is because of the existence of `std::time::Instant`. While\nthat doesn\'t in and of itself prevent Jiff from using the name `Instant`, it\ncreates a naming clash with something that is _similar_ but different. Namely,\na Jiff `Timestamp` corresponds to a time from your system clock, where as an\n`Instant` represents _monotonic_ time. The system clock might change or even\ngo backwards, where as a monotonic instant will always produce time that is\ngreater than or equal to a previous time.\n\nAn `Instant` is, for example, something you might use to measure the time\nsomething takes in a program. Like in capturing a measurement for a benchmark.\nConversely, a `Timestamp` is something you use to represent time as represented\nby the system. In particular, a `Timestamp` is like a `std::time::SystemTime`\nand _not_ a `std::time::Instant`.\n\nWhile [Temporal] uses the name `Instant` for their equivalent of Jiff\'s\n`Timestamp` type, using the name `Instant` in Jiff would likely result in\nserious confusion and conflicts in names when someone wants to use both an\n`Instant` and a `Timestamp` in the same namespace.\n\n[Temporal]: https://tc39.es/proposal-temporal/docs/\n[temporal-one-duration]: https://github.com/tc39/proposal-temporal/issues/2915\n[comparison]: http://docs.rs/jiff/*/jiff/_documentation/comparison/index.html\n[comparison-chrono]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#chrono-v0438\n[comparison-time]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#time-v0336\n[comparison-hifitime]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#hifitime-v0390\n[comparison-icu]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#icu-v150\n[RFC 8536]: https://datatracker.ietf.org/doc/draft-murchison-rfc8536bis/\n[RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/\n[POSIX TZ]: https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html\n[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database\n[TAI]: https://en.wikipedia.org/wiki/International_Atomic_Time\n[github-issue-leap]: https://github.com/BurntSushi/jiff/issues/7\n[`java.time`]: https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\n[NodaTime]: https://nodatime.org/\n[`chrono-tz`]: https://docs.rs/chrono-tz\n[`tzfile`]: https://docs.rs/tzfile\n[`chrono`]: https://docs.rs/chrono\n[`time`]: https://docs.rs/time\n[`time-tz`]: https://docs.rs/time-tz\n[`hifitime`]: https://docs.rs/hifitime\n[`icu`]: https://docs.rs/icu\n"include_str!("../DESIGN.md")]
806pub mod design {}
807#[doc = "# Platform support\n\nThis document describes Jiff\'s platform support. That is, it describes the\ninteraction points between this library and its environment. Most of the\ndetails in this document are written down elsewhere on individual APIs, but\nthis document serves to centralize everything in one place.\n\nAs a general rule, interaction with the environment requires that Jiff\'s\n`std` feature is enabled. The `std` feature is what allows Jiff to read\nenvironment variables and files, for example.\n\nBefore starting, let\'s cover some vocabulary first.\n\n## Vocabulary\n\nThis section defines the key terms used below when describing platform support.\nWe also try to contextualize the concepts to make their meaning concrete in a\nway that hopefully relates to your lived experience.\n\n* [Civil time]: The time you see on your clock. And in general, the time that\nthe humans in your approximate geographic vicinity also see. That is, civil\ntime is a human coordinated agreement for communicating time in a particular\ngeographic region. Civil time is also known as: local time, plain time, naive\ntime, clock time and others.\n* [Time zone]: A set of rules for determining the civil (or \"local\") time,\nvia an offset from UTC, in a particular geographic region. In many cases, the\noffset in a particular time zone can vary over the course of a year through\ntransitions into and out of [daylight saving time]. A time zone is necessary\nto convert civil time into a precise unambiguous instant in time.\n* [IANA Time Zone Database]: A directory on your system containing a store of\nfiles, one per time zone, which encode the time at which transitions between\nUTC offsets occur in a specific geographic region. In effect, each time zone\nfile provides a mapping between civil (or \"local\") time and UTC. The format\nof each file is called TZif and is specified by [RFC 8536]. This database is\ntypically found at `/usr/share/zoneinfo` and only on Unix systems (including\nmacOS). Other environments, like Windows and WASM, do not have a standard copy\nof the Time Zone Database. (Jiff will instead embed it into your program by\ndefault on these platforms.)\n* [IANA time zone identifier]: A short ASCII human readable string identifying\na time zone in the IANA Time Zone Database. The time zone for where I live,\n`America/New_York`, has an entry at `/usr/share/zoneinfo/America/New_York` on\nmy system. IANA time zone identifiers are used by Jiff\'s `ZonedDateTime` type\nto losslessly roundtrip datetimes via an interchange format specified by\n[Temporal] that draws inspiration from [RFC 3339], [RFC 9557] and [ISO 8601].\n\n## Environment variables\n\nJiff generally only reads two environment variables. These variables are\nread on all platforms that support environment variables. So for example,\nJiff will respect `TZ` on Windows. Note though that some environments, like\n`wasm32-wasip1` or `wasm32-unknown-emscripten`, are sandboxed by default. A\nsandboxed environment typically makes reading environment variables set outside\nthe sandbox impossible (or require opt-in support, such as [wasmtime]\'s\n`-S inherit-env` or `--env` flags).\n\nJiff may read additional environment variables for platform specific\nintegration.\n\n### `TZDIR`\n\nThe `TZDIR` environment variable tells Jiff where to look for the\n[IANA Time Zone Database]. When it isn\'t set, Jiff will check a few standard\nlocations for the database. It\'s usually found at `/usr/share/zoneinfo`.\n\nIt can be useful to set this for non-standard environments or when you\nspecifically want Jiff to prefer using a non-system copy of the database.\n(If you want Jiff to _only_ use a non-system copy of the database, then you\'ll\nneed to use `TimeZoneDatabase::from_dir` and use the resulting handle\nexplicitly.)\n\nIf a IANA Time Zone Database could not be found at `TZDIR`, then Jiff will\nstill attempt to look for a database at the standard locations (like\n`/usr/share/zoneinfo`).\n\n### `TZ`\n\nThe `TZ` environment variable overrides and sets the default system time zone.\nIt is [specified by POSIX][POSIX TZ]. Jiff implements the POSIX specification\n(even on non-POSIX platforms like Windows) with some common extensions.\n\nIt is useful to set `TZ` when Jiff could not detect (or had a problem\ndetecting) the system time zone, or if the system time zone is wrong in a\nspecific circumstance.\n\nSummarizing POSIX (and common extensions supported by GNU libc and musl), the\n`TZ` environment variable accepts these kinds of values:\n\n* `America/New_York` sets the time zone via a IANA time zone identifier.\n* `/usr/share/zoneinfo/America/New_York` sets the time zone by providing a path\nto a TZif formatted file.\n* `EST5EDT,M3.2.0,M11.1.0` sets the time zone using a POSIX daylight saving\ntime rule. The rule shown here is for `America/New_York` at time of writing\n(2024). This is useful for specifying a custom time zone without generating\nTZif data, but is rarely used in practice.\n\nWhen `TZ` isn\'t set, then Jiff uses heuristics to detect the system\'s\nconfigured time zone. If this automatic detection fails, please first check\nfor an [existing issue for your platform][issue-platform], and if one doesn\'t\nexist, please [file a new issue][issue-new]. Otherwise, setting `TZ` should be\nconsidered as a work-around.\n\n### `ANDROID_ROOT` and `ANDROID_DATA`\n\nThese environment variables are read to help determine the location of\nAndroid\'s [Concatenated Time Zone Database]. If `ANDROID_ROOT` is not defined,\nthen Jiff uses `/system` as its default value. If `ANDROID_DATA` is not\ndefined, then Jiff uses `/data/misc` as its default value.\n\nNote that these environment variables are not necessarily only read on\nAndroid, although they likely only make sense in the context of an Android\nenvironment. This is because Jiff\'s support for the Concatenated Time\nZone Database is platform independent. For example, Jiff will let users\ncreate a database from a Concatenated Time Zone Database file via the\n`TimeZoneDatabase::from_concatenated_path` API on _any_ platform. This is\nintended to enable maximum flexibility, and because there is no specific reason\nto make the Concatenated Time Zone Database format Android-specific.\n\n## Platforms\n\nThis section lists the platforms that Jiff has explicit support for. Support\nmay not be perfect, so if something isn\'t working as it should, check the\nlist of [existing platform related issues][issue-platform]. If you can\'t find\none that matches your specific problem, [create a new issue][issue-new].\n\nFor each platform, there are generally three things to consider:\n\n1. Whether getting the current time is supported.\n2. How Jiff finds the IANA Time Zone Database.\n3. How Jiff finds the system configured time zone.\n\nWe answer these questions for each platform.\n\n### Unix\n\n#### Current time\n\nAll Unix platforms should be supported in terms of getting the current time.\nThis support comes from Rust\'s standard library.\n\n#### IANA Time Zone Database\n\nThe vast majority of Unix systems, including macOS, store a copy of the IANA\ntime zone database at `/usr/share/zoneinfo`, which Jiff will automatically\ndetect. If your Unix system uses a different directory, you may try to submit\na PR adding support for it in Jiff proper, or just set the `TZDIR` environment\nvariable.\n\nThe existence of `/usr/share/zoneinfo` is not guaranteed in all Unix\nenvironments. For example, stripped down Docker containers might omit a full\ncopy of the time zone database. Jiff will still work in such environments, but\nall IANA time zone identifier lookups will fail. To fix this, you can either\ninstall the IANA Time Zone Database into your environment, or you can enable\nthe Jiff crate feature `tzdb-bundle-always`. This compile time setting will\ncause Jiff to depend on `jiff-tzdb`, which includes a complete copy of the IANA\nTime Zone Database embedded into the compiled artifact.\n\nBundling the IANA Time Zone Database should only be done as a last resort.\nEspecially on Unix systems, it is greatly preferred to use the system copy of\nthe database, as the database is typically updated a few times each year. By\nusing the system copy, Jiff will automatically pick up updates without needing\nto be recompiled.\n\nBut if bundling is needed, it is a fine solution. It just means that Jiff will\nneed to be re-compiled after `jiff-tzdb` is updated when a new IANA Time Zone\nDatabase release is published.\n\n#### System time zone\n\nOn most Unix systems, the system configured time zone manifests as a symbolic\nlink at `/etc/localtime`. The symbolic link usually points to a file in\nyour system copy of the IANA Time Zone Database. For example, on my Linux\nsystem:\n\n```text\n$ ls -l /etc/localtime\nlrwxrwxrwx 1 root root 36 Jul 15 20:26 /etc/localtime -> /usr/share/zoneinfo/America/New_York\n```\n\nAnd my macOS system:\n\n```text\n$ ls -l /etc/localtime\nlrwxr-xr-x 1 root wheel 42 Jun 20 07:13 /etc/localtime -> /var/db/timezone/zoneinfo/America/New_York\n```\n\nJiff examines the symbolic link metadata to extract the IANA time zone\nidentifier from the file path. In the above two examples, that would be\n`America/New_York`. The identifier is then used to do a lookup in the system\ncopy of the IANA Time Zone Database.\n\nIf `/etc/localtime` is not a symbolic link, then Jiff reads it directly as a\nTZif file. When this happens, Jiff cannot feasibly know the IANA time zone\nidentifier. While arithmetic on the resulting `ZonedDateTime` value will still\nbe DST safe, one cannot losslessly serialize and deserialize it since Jiff\nwon\'t be able to include the IANA time zone identifier in the serialized\nformat. When such a `ZonedDateTime` value is serialized, the offset of the\ndatetime will be used in lieu of the IANA time zone identifier.\n\n(NOTE: Not all Unix systems follow this pattern. If your system uses a\ndifferent way to configure the system time zone, please check [available\nplatform issues][issue-platform] for a related issue. If one doesn\'t exist,\nplease [create a new issue][issue-new].)\n\n### Android\n\n#### Current time\n\nAll Android platforms should be supported in terms of getting the current time.\nThis support comes from Rust\'s standard library.\n\n#### IANA Time Zone Database\n\nUnlike effectively every other Unix system, Android has its own special time\nzone database format. While it still makes use of TZif formatted data for\ndefining time zone transitions themselves, it does not use the `zoneinfo`\ndirectory format (where there is one file per time zone). Instead, it\n_concatenates_ all time zone files into one single file. This is combined with\nsome meta data that makes it quick to search for time zones by their IANA time\nzone identifier.\n\nThis format is technically unnamed, but Jiff refers to it as the [Concatenated\nTime Zone Database] format. It has no formal specification. Jiff\'s\nimplementation was done by inferring the format implemented by the Android\nPlatform and also the implementation in [Go\'s standard library]. In practice\nthis tends to work well, although there are obviously no guarantees. This is\na practical trade-off given that there doesn\'t appear to be any obvious\nalternative. Moreover, others (such as Go, a project maintained by the same\ncompany that maintains Android) are already doing it, so it seems likely that\nif Android decides to make breaking changes to the format, they\'ll need to\nversion it in some way to avoid breaking the ecosystem.\n\nNote that Jiff supports reading this format on all platforms, not just Android.\nFor example, Jiff users can use the `TimeZoneDatabase::from_concatenated_path`\nAPI to create a `TimeZoneDatabase` from a concatenated `tzdata` file on any\nplatform.\n\nIf users of Jiff are uncomfortable relying on Android\'s \"unstable\" time zone\ndatabase format, then there are a few options available to them after disabling\nthe `tzdb-concatenated` crate feature:\n\n* They can own the responsibility of putting a standard `zoneinfo` database\ninstallation into their environment. Then set the `TZDIR` environment variable\nto point at it, and Jiff will automatically use it.\n* Enable the `tzdb-bundle-always` crate feature. This will cause the entire\ntime zone database to be compiled into your binary. Nothing else needs to be\ndone. Jiff will automatically use the bundled copy.\n* Manually create `TimeZone` values via `TimeZone::tzif` from TZif formatted\ndata. With this approach, you may need to change how you use Jiff in some\ncases. For example, any `in_tz` method will need to be changed to use the\n`to_zoned_datetime` equivalent.\n* Embed specific time zones into your binary with `jiff::tz::get` or\n`jiff::tz::include`. This requires enabling Jiff\'s `static` feature.\n\n#### System time zone\n\nThe system time zone on Android is discovered by reading the\n`persist.sys.timezone` property.\n\nNote that in addition to Android developers citing the [Concatenated Time Zone\nDatabase] format as unstable, they also discourage the discovery of the system\ntime zone through properties as well. (See [chrono#1018] and [chrono#1148]\nfor some discussion on this topic.) For Jiff at least, there is no feasible\nalternative. Apparently, the blessed API is to use their Java libraries, but\nthat doesn\'t seem feasible to me inside of Jiff since I (Jiff\'s author) is\nunaware of a mechanism for easily calling Java code from Rust. The only option\nleft is to use their `libc` APIs, which they did at least improve to make them\nthread safe, but this isn\'t enough for Jiff. For Jiff, we really want the\nactual IANA time zone identifier, and it isn\'t clear how to discover this from\ntheir `libc` APIs. Moreover, Jiff supports far more sophisticated operations on\na time zone (like dealing with discontinuities in civil time) that cannot be\nimplemented on top of `libc`-style APIs. Using Android\'s `libc` APIs for time\nhandling would be a huge regression compared to all other platforms.\n\nIt\'s worth noting that all other popular Unix systems provide at least some\nreliable means of both querying the time zone database _and_ discovering the\nsystem-wide IANA time zone identifier. Why Android is incapable of following\nthe existing conventions for Unix systems is unclear.\n\nIf users of Jiff are uncomfortable relying on Android\'s `persist.sys.timezone`\nproperty, then they should avoid APIs like `ZonedDateTime::now` and\n`TimeZone::system`. Instead, they can use `TimeZone::unknown()`, which is what\nthe fallback time zone would be when the system time zone cannot be discovered.\n\n### Windows\n\n#### Current time\n\nAll Windows platforms should be supported in terms of getting the current time.\nThis support comes from Rust\'s standard library.\n\n#### IANA Time Zone Database\n\nWindows does not have a canonical installation of the IANA Time Zone Database\nlike Unix. Because of this, and because of the importance of time zone support\nto Jiff\'s design, Jiff will automatically embed an entire copy of the IANA Time\nZone Database into your binary on Windows.\n\nThe automatic bundling is done via the Jiff crate feature\n`tzdb-bundle-platform`. This is a _target activated feature_. Namely, it is\nenabled by default, but only results in a bundled database on an enumerated set\nof platforms (where Windows is one of them). If you want to opt out of bundling\nthe database on Windows, you\'ll need to disable this feature.\n\nBundling the IANA Time Zone Database is not ideal, since after a new release of\nthe database, you\'ll need to wait for the `jiff-tzdb` crate to be updated. Then\nyou\'ll need to update your dependency version and re-compile your software to\nget the database updates.\n\nOne alternative is to point Jiff to a copy of the IANA Time Zone Database via\nthe `TZDIR` environment variable. Even on Windows, Jiff will attempt to read\nthe directory specified as a time zone database. But you\'ll likely need to\nmanage the database yourself.\n\n#### System time zone\n\nJiff currently uses [`GetDynamicTimeZoneInformation`] from the Windows C API\nto query the current time zone information. This provides a value of type\n[`DYNAMIC_TIME_ZONE_INFORMATION`]. Jiff uses the `TimeZoneKeyName` member\nof that type to do a lookup in Unicode\'s [CLDR XML data] that maps Windows\ntime zone names to IANA time zone identifiers. The resulting IANA time zone\nidentifier is then used as a key to find a time zone in the configured IANA\nTime Zone Database.\n\n### WASM\n\nThere are a variety of WASM targets available for Rust that service different\nuse cases. Here is a possibly incomplete list of those targets and a short\nimprecise blurb about them:\n\n* `wasm32-unknown-emscripten`: Sandboxed and emulates Unix as much as possible.\n* `wasm32-wasi` and `wasm32-wasip1`: Provides a sandbox with capability-based\nsecurity. This is not typically used in web browsers. [wasmtime] is an example\nof a runtime that can run programs compiled for these targets.\n* `wasm{32,64}-unknown-unknown`: Typically used for web deployments to run in\na browser via `wasm-pack`. But, crucially, not exclusively so.\n\nJiff supports all of these targets, but the nature of that support varies. Each\ntarget is discussed in the sections below.\n\n#### The `js` crate feature\n\nJiff comes with a `js` crate feature that is disabled by default. It is a\n_target activated feature_ that enables dependencies on the `js-sys` and\n`wasm-bindgen` crates. This feature is intended to be enabled only in binaries,\ntests and benchmarks when it is known that the code will be running in a\nweb context. Consequently, this feature only activates this support for the\n`wasm{32,64}-unknown-unknown` targets. It has no effect on any other target,\nincluding other WASM targets.\n\nLibrary crates should generally never enable Jiff\'s `js` feature or even\nforward it. Applications using your library can depend on Jiff directly and\nenable the feature.\n\n#### Current time\n\n* `wasm32-unknown-emscripten`: Supported via Rust\'s standard library.\n* `wasm32-wasi*`: Supported via Rust\'s standard library.\n* `wasm{32,64}-unknown-unknown`: `std::time::SystemTime::now()`, and thus\n`ZonedDateTime::now()`, panics in Jiff\'s default configuration. Enabling Jiff\'s\n`js` feature will cause Jiff to assume a web context and use JavaScript\'s\n[`Date.now`] API to determine the current time.\n\n#### IANA Time Zone Database\n\nNone of the WASM targets have a canonical installation of the IANA Time Zone\nDatabase. Because of this, and because of the importance of time zone support\nto Jiff\'s design, Jiff will automatically embed an entire copy of the IANA\nTime Zone Database into your binary on all WASM targets.\n\nThe automatic bundling is done via the Jiff crate feature\n`tzdb-bundle-platform`. This is a _target activated feature_. Namely, it is\nenabled by default, but only results in a bundled database on an enumerated set\nof platforms (where WASM is one of them). If you want to opt out of bundling\nthe database on WASM targets, you\'ll need to disable this feature.\n\nBundling the IANA Time Zone Database is not ideal, since after a new release of\nthe database, you\'ll need to wait for the `jiff-tzdb` crate to be updated. Then\nyou\'ll need to update your dependency version and re-compile your software to\nget the database updates.\n\nSome WASM targets, like `wasm32-wasip1`, can actually read the host\'s\nIANA Time Zone Database (e.g., on Unix), but this requires relaxing its\nsandbox restrictions so that the code can read system directories like\n`/usr/share/zoneinfo`. That is, it won\'t work out of the box. The same applies\nto the `wasm32-unknown-emscripten` target. (Although this author could not\nfigure out how to relax emscripten\'s sandbox.)\n\n#### System time zone\n\n* `wasm32-unknown-emscripten`: Unsupported.\n* `wasm32-wasi*`: Unsupported. But you may set the `TZ` environment variable\nvia your WASM runtime, and Jiff will respect it. For example, with [wasmtime],\nthat\'s `--env TZ=America/New_York`.\n* `wasm{32,64}-unknown-unknown`: Unsupported in Jiff\'s default configuration.\nEnabling Jiff\'s `js` feature will cause Jiff to assume a web context and use\nJavaScript\'s [`Intl.DateTimeFormat`] API to determine the system configured\nIANA time zone identifier. This time zone identifier is then used to look up\nthe time zone in Jiff\'s configured IANA Time Zone Database.\n\n[Civil time]: https://en.wikipedia.org/wiki/Civil_time\n[Time zone]: https://en.wikipedia.org/wiki/Time_zone\n[daylight saving time]: https://en.wikipedia.org/wiki/Daylight_saving_time\n[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database\n[IANA time zone identifier]: https://data.iana.org/time-zones/theory.html#naming\n[RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536\n[wasmtime]: https://wasmtime.dev/\n[POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html\n[RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339\n[RFC 9557]: https://www.rfc-editor.org/rfc/rfc9557.html\n[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html\n[Temporal]: https://tc39.es/proposal-temporal\n[issue-platform]: https://github.com/BurntSushi/jiff/issues?q=label%3Aplatform\n[issue-new]: https://github.com/BurntSushi/jiff/issues/new\n[`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation\n[`DYNAMIC_TIME_ZONE_INFORMATION`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/ns-timezoneapi-dynamic_time_zone_information\n[CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml\n[`Intl.DateTimeFormat`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions#timezone\n[`Date.now`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\n[Concatenated Time Zone Database]: https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/util/ZoneInfoDB.java\n[Go\'s standard library]: https://github.com/golang/go/blob/19e923182e590ae6568c2c714f20f32512aeb3e3/src/time/zoneinfo_android.go\n[chrono#1018]: https://github.com/chronotope/chrono/pull/1018\n[chrono#1148]: https://github.com/chronotope/chrono/pull/1148\n"include_str!("../PLATFORM.md")]
808pub mod platform {}
809#[doc = "# CHANGELOG\n\n1.0.3 (2026-11-24)\n==================\nBug fixes:\n\n* [#723](https://github.com/BurntSushi/jiff/issues/723):\n`Timestamp::from_{milli,micro}second` rejects valid values.\n\n\n1.0.2 (2026-11-21)\n==================\nBug fixes:\n\n* [#718](https://github.com/BurntSushi/jiff/issues/718):\n`ZonedDateTime::strptime` could panic on inputs near boundaries.\n* [#720](https://github.com/BurntSushi/jiff/issues/720):\nTweak how we handle folds in offset conflict resolution.\n\n\n1.0.1 (2026-11-17)\n==================\nBug fixes:\n\n* [#713](https://github.com/BurntSushi/jiff/issues/713):\n`%Z` in `Timestamp::strftime` should format as `UTC`.\n* [#714](https://github.com/BurntSushi/jiff/issues/714):\nParsing a timestamp could produce an out of bounds value.\n\n\n1.0.0 (2026-11-15)\n==================\nThis marks the Jiff 1.0 release. Barring some unforeseen major problem with the\nAPI, this release marks an indefinite commitment to 1.x.y. Consumers of this\nlibrary should feel confident about putting Jiff types into their public API.\nNew major versions of Jiff will not be made lightly.\n\nThe most significant breaking change in this release large but simple: the\n`Zoned` type has been renamed to `ZonedDateTime`. This also impacts APIs like\n`Timestamp::to_zoned`, which are now called `Timestamp::to_zoned_datetime`. The\nremaining breaking changes are pretty minor and shouldn\'t impact most users.\n\nEnhancements:\n\n* [3211f23](https://github.com/BurntSushi/jiff/commit/3211f23a7f87eceffda70031c2954a2359cb370c):\nBump MSRV to Rust 1.85.\n* [#262](https://github.com/BurntSushi/jiff/issues/262):\nUse `core::error::Error` in lieu of `std::error::Error`.\n* [#314](https://github.com/BurntSushi/jiff/issues/314):\n**BREAKING**: Make `Zoned::iso_week_date` take `&self` instead of `self`.\n* [#624](https://github.com/BurntSushi/jiff/issues/624):\nMake more methods take `&self`.\n* [#471](https://github.com/BurntSushi/jiff/issues/471):\nTurn `Custom` into a trait object.\n* [#499](https://github.com/BurntSushi/jiff/issues/499):\n**BREAKING**: Make `Offset::saturating_add` fallible.\n* [#629](https://github.com/BurntSushi/jiff/issues/629), [#626](https://github.com/BurntSushi/jiff/issues/626):\n**BREAKING**: Make `impl Sub for Timestamp` return a `SignedDuration`.\n* [#436](https://github.com/BurntSushi/jiff/issues/436):\n**BREAKING**: Seal the `ToSpan` trait.\n* [#463](https://github.com/BurntSushi/jiff/issues/463):\nProvide an accessor for an underlying `std::io::Error`.\n* [#467](https://github.com/BurntSushi/jiff/issues/467):\n**BREAKING**: Make conversions from `Timestamp` to `SystemTime` fallible.\n* [#374](https://github.com/BurntSushi/jiff/issues/374):\n**BREAKING**: Rename `Zoned` to `ZonedDateTime`.\n* [#618](https://github.com/BurntSushi/jiff/issues/618):\n**BREAKING**: Make `jiff_tzdb::VERSION` required.\n* [c03581f](https://github.com/BurntSushi/jiff/commit/c03581f405955ed4bbebfda0ae28e03120c289fa):\nAdd `Span::to_friendly` routine as a convenience for `format(\"{:#}\", span)`.\n\nDocumentation:\n\n* [#545](https://github.com/BurntSushi/jiff/issues/545):\nClarify specification labeling in formatting table.\n* [#630](https://github.com/BurntSushi/jiff/issues/630):\nClarify the use of the propleptic Gregorian calendar.\n\nPerformance:\n\n* [4d66e92](https://github.com/BurntSushi/jiff/commit/4d66e92ecdd6a012c952f7a5c0f628d0ecde662d):\nAdd `inline(never)` to `strtime` routine.\n\n0.2.46 (2026-11-15)\n===================\nBug fixes:\n\n* [#707](https://github.com/BurntSushi/jiff/issues/707):\n`jiff_core::util::ArrayStr` has an unsound API.\n\nDocumentation:\n\n* [#709](https://github.com/BurntSushi/jiff/issues/709):\nFix documentation inconsistencies.\n\nPerformance:\n\n* [#708](https://github.com/BurntSushi/jiff/issues/708):\nSkip extension parsing for plain directives in strptime.\n\n\n0.2.45 (2026-11-14)\n===================\nEnhancements:\n\n* [#483](https://github.com/BurntSushi/jiff/issues/483):\nSupport ECMAScript\'s \"primary\" time zone identifiers.\n\nBug fixes:\n\n* [#701](https://github.com/BurntSushi/jiff/issues/701):\nHandle zero span multiplication.\n* [#702](https://github.com/BurntSushi/jiff/issues/702):\nConstrain ISO week numbers to the year\'s last week.\n* [#703](https://github.com/BurntSushi/jiff/issues/703):\n`Timestamp::checked_add_seconds` produces incorrect results across the Unix epoch.\n\n\n0.2.44 (2026-11-14)\n===================\nEnhancements:\n\n* [#697](https://github.com/BurntSushi/jiff/issues/697):\nUpgrade Jiff\'s bundled IANA Time Zone Database to tzdb `2026f`.\n* [#694](https://github.com/BurntSushi/jiff/issues/694):\nMake `jiff::civil::Weekday` methods `const` where possible.\n\nBug fixes:\n\n* [#695](https://github.com/BurntSushi/jiff/issues/695):\nTimestamp subtraction assignment.\n* [#696](https://github.com/BurntSushi/jiff/issues/696):\nCorrect some boundary conditions on `Timestamp`.\n\n\n0.2.43 (2026-11-11)\n===================\nThis release includes a few new minor API additions.\n\nEnhancements:\n\n* [#651](https://github.com/BurntSushi/jiff/issues/651):\nAdd `jiff::tz::reset_system_time_zone_cache`.\n* [#653](https://github.com/BurntSushi/jiff/issues/653):\nExpose `relative` builder option on `Span*` types.\n* [#689](https://github.com/BurntSushi/jiff/issues/689):\nAdd `jiff_core::tz::posix::ParseError::is_missing_dst_transition_rule`\npredicate.\n\n\n0.2.42 (2026-11-09)\n===================\nThis release includes a couple of bug fixes where panics could occur when they\nshould not have been. Specifically in `Span::total` and `Span::checked_add`.\n\nBug fixes:\n\n* [#683](https://github.com/BurntSushi/jiff/issues/683):\nFix a panic in `Span::checked_add` when an internal addition would overflow\na `SignedDuration`\'s minimum/maximum values.\n* [#685](https://github.com/BurntSushi/jiff/issues/685):\nFix a panic in `Span::total` when a time zone transition boundary was crossed.\n\n\n0.2.41 (2026-11-08)\n===================\nThis release includes a bug fix for time zone transition lookups for timestamps\nbefore the Unix epoch with a non-zero nanosecond component.\n\nBug fixes:\n\n* [#678](https://github.com/BurntSushi/jiff/issues/678):\nFix timezone transition lookup in TZif data for negative timestamps with a\nnon-zero nanosecond component.\n\n\n0.2.40 (2026-11-07)\n===================\nThis release should help reduce the number of entries Jiff adds to `Cargo.lock`\nby default. This also improves performance for datetime<->timestamp\nconversions.\n\nEnhancements:\n\n* [#643](https://github.com/BurntSushi/jiff/issues/643):\nDon\'t add `defmt` and its dependencies to `Cargo.lock` when the `defmt`\nfeature isn\'t enabled.\n\nPerformance:\n\n* [#640](https://github.com/BurntSushi/jiff/pull/640):\nAdd branch-free implementation for part of datetime <-> timestamp conversions.\n\n\n0.2.39 (2026-11-02)\n===================\nThis release gathers a smattering of performance improvements and bug fixes.\n\nEnhancements:\n\n* [#646](https://github.com/BurntSushi/jiff/pull/646):\nAdded optional `serde` support to `jiff-sqlx`.\n* [#659](https://github.com/BurntSushi/jiff/pull/659):\nUpdate the Windows time zone names.\n* [#665](https://github.com/BurntSushi/jiff/pull/665):\nAvoid allocating IANA name during a `Zoned::strftime` call.\n* [#666](https://github.com/BurntSushi/jiff/pull/666):\nAvoid a second offset lookup when adding calendar units.\n\nBug fixes:\n\n* [#645](https://github.com/BurntSushi/jiff/issues/645):\nFix `Timestamp::from_nanosecond` panic on out-of-range input.\n* [#649](https://github.com/BurntSushi/jiff/issues/649):\nFix optional deserializers dropping null under `#[serde(flatten)]`.\n* [#652](https://github.com/BurntSushi/jiff/issues/652):\nTweak \"lossless\" wording for round-tripping `Zoned` values.\n* [#654](https://github.com/BurntSushi/jiff/issues/654):\nFixes a panic when printing some very large durations.\n* [#660](https://github.com/BurntSushi/jiff/issues/660):\nFixes a bug where parsing some very large spans gave an incorrect result.\n* [#668](https://github.com/BurntSushi/jiff/issues/668):\nFixes a panic in `Span::total` for a zero span with a calendar unit.\n\n\n0.2.38 (2026-10-06)\n===================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database]\nto `2026e`. See the [`2026e` release announcement] for more details.\n\n[`2026e` release announcement]: https://lists.iana.org/hyperkitty/list/tz-announce@iana.org/thread/VXIA4AU73OQL3OZ3ZBZHWIASIIVBGUJV/\n\n\n0.2.37 (2026-09-12)\n===================\nThis is a redux release of `0.2.36` that fixes a compilation bug.\n\nBug fixes:\n\n* [#647](https://github.com/BurntSushi/jiff/issues/647):\nFixes a compilation bug due to incorrect include paths.\n\n\n0.2.36 (2026-09-12)\n===================\nThis release has a couple bug fixes and adds opt-in integration with the\n`arbitrary` crate.\n\nEnhancements:\n\n* [#631](https://github.com/BurntSushi/jiff/issues/631):\nAdd optional `Arbitrary` trait implementations from the `arbitrary` crate.\n\nBug fixes:\n\n* [#617](https://github.com/BurntSushi/jiff/pull/617):\nFixes a bug in `jiff_core::tz::Offset` checked subtraction routine.\n* [#627](https://github.com/BurntSushi/jiff/issues/627):\nUse `serialize_some` for optional Serde helpers in `jiff::fmt::serde`.\n\n\n0.2.35 (2026-07-25)\n===================\nThis release fixes a bug in duration parsing where, e.g., `-PT0.5S` would be\nparsed as if the `-` sign didn\'t exist. This bug also affects friendly\ndurations such as `-0.5s`.\n\nBug fixes:\n\n* [#613](https://github.com/BurntSushi/jiff/issues/613):\nFixes a bug where the sign in a duration could be ignored while parsing.\n\n\n0.2.34 (2026-07-19)\n===================\nThis release contains a few small enhancements. Namely, some error messages\nfor parsing datetime values have been improved by removing some redundant\nmessaging. Additionally, the `strftime` APIs on datetime values can no longer\npanic. Instead, they\'ll silently pass through invalid formatting directives.\n\nEnhancements:\n\n* [#519](https://github.com/BurntSushi/jiff/issues/519):\nImprove some parsing error messages by removing redundancy.\n* [#585](https://github.com/BurntSushi/jiff/issues/585):\nChange `Timestamp::strftime` (and similar methods) so that they will never\npanic.\n\n\n0.2.33 (2026-07-18)\n===================\nThis release permits the use of a global time zone database in `alloc`-only\nenvironments. It also contains a massive internal refactor that introduces a\nnew `jiff-core` crate for better code sharing.\n\nEnhancements:\n\n* [#285](https://github.com/BurntSushi/jiff/issues/285):\nDecouple naming of time zones from their TZif data.\n* [#373](https://github.com/BurntSushi/jiff/issues/373):\nAdd a new `jiff-core` crate for better code sharing.\n* [#533](https://github.com/BurntSushi/jiff/issues/533):\nA bundled `TimeZoneDatabase` is now available when only `alloc` is enabled.\n\n\n0.2.32 (2026-07-08)\n===================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database]\nto `2026c`. See the [`2026c` release announcement] for more details.\n\n[`2026c` release announcement]: https://lists.iana.org//hyperkitty/list/tz-announce@iana.org/thread/NVHSX2PAQIT44U5FCCEVNJJYXQMMTJSA/\n\n\n0.2.31 (2026-06-29)\n===================\nThis release fixes a minor bug in tests that prevents the crate from running\nthrough standard build processes in Linux distributions downstream.\n\n* [#594](https://github.com/BurntSushi/jiff/pull/591):\nFix imports in recently added tests.\n\n\n0.2.30 (2026-06-29)\n===================\nThis release fixes a safety soundness bug in Jiff\'s lower level printing\nAPIs. There is also a nice performance improvement to `civil::Date::weekday`,\nwhich also improves downstread routines like `civil::Date::nth_weekday` and\ndatetime<-->timestamp conversions in some cases.\n\nEnhancements:\n\n* [#591](https://github.com/BurntSushi/jiff/pull/591):\nImprove the performance of weekday calculations from Gregorian dates by 30-50%.\n\nBug fixes:\n\n* [#592](https://github.com/BurntSushi/jiff/issues/592):\nFix safety soundness bug when using a non-empty `String` destination buffer\nwith lower level printing APIs inside of `jiff::fmt`.\n\n\n0.2.29 (2026-06-20)\n===================\nThis release adds support for [`defmt`], which is a highly efficient logging\nframework that targets resource-constrained devices, like microcontrollers.\n\nEnhancements:\n\n* [#505](https://github.com/BurntSushi/jiff/issues/505):\nAdd support for the `defmt` crate by implementing `defmt::Format` on the\nprinciple public types in Jiff.\n* [#584](https://github.com/BurntSushi/jiff/pull/584):\nAdd `Zoned::UNIX_EPOCH` as a constant.\n* [#587](https://github.com/BurntSushi/jiff/pull/587):\nChange the `Debug` output for `civil::ISOWeekDate` to match the `Debug` output\nstyle of other primitive datetime types.\n\nBug fixes:\n\n* [#525](https://github.com/BurntSushi/jiff/issues/525):\nFix a bug that prevented time zone lookups when using an on-disk time zone\ndatabase on Windows.\n* [#539](https://github.com/BurntSushi/jiff/issues/539):\nFix a bug where rendering a datetime in an error message would omit a `T`\nseparator.\n\n\n0.2.28 (2026-05-28)\n===================\nThis is a small release with a fix for test failures on 32-bit targets in\n`no-alloc` environments.\n\nBug fixes:\n\n* [#573](https://github.com/BurntSushi/jiff/issues/573):\nFix test failure on 32-bit targets in `no-alloc` environments.\n\n\n0.2.27 (2026-05-26)\n===================\nThis is a small release with a bug fix for build errors on Windows for very old\nversions of Rust.\n\nBug fixes:\n\n* [#566](https://github.com/BurntSushi/jiff/issues/566):\nFix build error on Windows for very old versions of Rust (e.g., 1.71).\n\n\n0.2.26 (2026-05-25)\n===================\nThis release has a couple enhancements.\n\nFirstly, Jiff now uses `windows-link` for calling FFI routines on Windows\ninstead of `windows-sys`. Using `windows-link` means less churn and fewer\nduplicates in the dependency graph.\n\nSecondly, a new `jiff-sqlx 0.2.0` release has been put out to support\n`sqlx 0.9.0`.\n\nEnhancements:\n\n* [#538](https://github.com/BurntSushi/jiff/pull/538):\nReplace use of `windows-sys` with `windows-link` and inline bindings.\n* [#561](https://github.com/BurntSushi/jiff/pull/561):\nUpdate `jiff-sqlx` to use `sqlx 0.9.0` and release `jiff-sqlx 0.2.0`.\n\nBug fixes:\n\n* [#548](https://github.com/BurntSushi/jiff/pull/548):\nAbsolutetize incorrect relative size terms in the documentation of `RoundMode`.\n\n\n0.2.25 (2026-05-24)\n===================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database]\nto `2026b`. See the [`2026b` release announcement] for more details.\n\n[`2026b` release announcement]: https://lists.iana.org//hyperkitty/list/tz-announce@iana.org/thread/VX2Z3CBO6KHTYZNBBKFFWM7ZCI6TVCXP/\n\n\n0.2.24 (2026-04-23)\n===================\nThis release primarily adds a new `memory_usage` routine for reporting\nheap allocation sizes for the `TimeZone` and `Zoned` types. This\nrelease also acknowledges and updates the timeline expectations for a\nJiff 1.0 release in `README.md`.\n\nEnhancements:\n\n* [#520](https://github.com/BurntSushi/jiff/issues/520):\nAdd `memory_usage` to the `TimeZone` and `Zoned` types.\n* [#535](https://github.com/BurntSushi/jiff/pull/535):\nImprove comment in `Span::checked_add` example.\n\nBug fixes:\n\n* [#541](https://github.com/BurntSushi/jiff/pull/541):\nUpdate Jiff 1.0 timeline.\n\n\n0.2.23 (2026-03-03)\n===================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database]\nto `2026a`. See the [`2026a` release announcement] for more details.\n\n[`2026a` release announcement]: https://lists.iana.org/hyperkitty/list/tz-announce@iana.org/thread/ASPLBE3A4BAEXIOQ3KZ6EJSJWBU6L53G/\n\n0.2.22 (2026-02-28)\n===================\nThis release includes a bug fix where fallible conversions from signed\ndurations to unsigned durations could panic in some cases.\n\nBug fixes:\n\n* [#526](https://github.com/BurntSushi/jiff/issues/526):\nFix a panicking bug that occurs for\n`std::time::Duration::try_from(SignedDuration::new(0, -1))`.\n\n\n0.2.21 (2026-02-22)\n===================\nThis release contains a performance improvement and a bug fix for\n`civil::Date::new` where it could panic on some inputs.\n\nBug fixes:\n\n* [#523](https://github.com/BurntSushi/jiff/issues/523):\nFix a bug where `Date::new` could panic. This was a regression introduced in\n`jiff 0.2.20`.\n\nPerformance:\n\n* [#518](https://github.com/BurntSushi/jiff/pull/518):\nImprove `Timestamp` to `civil::DateTime` conversion performance by ~15%.\n\n\n0.2.20 (2026-02-11)\n===================\nThis release contains a major internal refactor that moves off of using ranged\nintegers internally. There are also some small bug fixes and added support for\nfinding the system time zone on emscripten targets.\n\nEnhancements:\n\n* [#11](https://github.com/BurntSushi/jiff/issues/11):\nStop using ranged integers internally.\n* [#490](https://github.com/BurntSushi/jiff/issues/490):\nAdd support for retrieving the system time zone on emscripten targets.\n* [#500](https://github.com/BurntSushi/jiff/issues/500):\nUpdate comparison with the `time` crate in the Jiff documentation.\n* [#502](https://github.com/BurntSushi/jiff/issues/502):\nEnable some non-default features for the Rust Playground deployment.\n\nBug fixes:\n\n* [#485](https://github.com/BurntSushi/jiff/issues/485):\nFix bug with padding for negative integers in `strftime`.\n* [#486](https://github.com/BurntSushi/jiff/issues/486):\nMake `%^c` result in uppercase strings where appropriate.\n\n\n0.2.19 (2026-02-05)\n===================\nThis is a small release with a performance optimization (with respect to doing\nheavily contended arithmetic on `Zoned` values) and a bug fix for a panic\nthat can occur when using `%2s` in `strftime`.\n\nEnhancements:\n\n* [#491](https://github.com/BurntSushi/jiff/issues/491):\nAvoid cloning `TimeZone` for consuming operations on `Zoned`.\n\nBug fixes:\n\n* [#497](https://github.com/BurntSushi/jiff/issues/497):\nFix a panic in `timestamp.strftime(\"%2s\")`.\n\n\n0.2.18 (2026-01-05)\n===================\nThis release ships a sizeable refactor to the RFC 2822, RFC 9110, RC\n3339, RFC 9557, ISO 8601 and friendly format printers. Specifically,\nthey are now all monomorphic internally (instead of being generic over\n`jiff::fmt::Write`) and write to uninitialized buffers. This improves\nruntime performance (sometimes dramatically so), and to a more modest\ndegree, decreases binary size and improves compile times.\n\nThis release also includes a bug fix where `DateTime::MIN.to_zoned(..)`\ncould panic.\n\nEnhancements:\n\n* [#460](https://github.com/BurntSushi/jiff/pull/460):\nImprove runtime performance and binary size of RFC 2822 printer.\n* [#461](https://github.com/BurntSushi/jiff/pull/461):\nTweak behavior of printing min/max offsets in RFC 2822 and Temporal printers.\n* [#462](https://github.com/BurntSushi/jiff/pull/462):\nExport fallible constructors for `jiff::SignedDuration`.\n* [#465](https://github.com/BurntSushi/jiff/pull/465):\nImprove runtime performance and binary size of the \"friendly\" duration printer.\n* [#468](https://github.com/BurntSushi/jiff/pull/468):\nImprove runtime performance and binary size of the Temporal ISO 8601 duration\nprinter.\n* [#470](https://github.com/BurntSushi/jiff/pull/470):\nImprove runtime performance and binary size of the Temporal ISO 8601 datetime\nprinter.\n* [#474](https://github.com/BurntSushi/jiff/pull/474):\nImprove runtime performance and binary size of Jiff\'s `strftime`\nimplementation.\n* [#477](https://github.com/BurntSushi/jiff/pull/477):\nFix a bug where time zone lookups for `civil::DateTime::MIN` could panic.\n\n\n0.2.17 (2025-12-24)\n===================\nThis release contains binary size improvements to Jiff, more succinct error\nmessages and some new minor APIs.\n\nWhile Jiff 1.0 is overdue, I\'ve been doing a lot of experimenting with\nimproving Jiff\'s binary size and compile times. In particular, I want to spend\ntime doing this before Jiff 1.0 so that we don\'t box ourselves into a corner.\n(For example, some binary size improvements may require minor API breaking\nchanges.)\n\nIn this release, Jiff has switched to structured error handling internally\nin an effort to provide error predicates and also hopefully improve binary\nsizes and compile times. Overall this didn\'t have as big of an impact on\nbinary sizes or compile times as I was hoping. I did take this opportunity to\nmake Jiff\'s error messages a bit more succinct. In many cases, this involved\nde-duplicating some aspects of error messages and omitting user provided input\nin the messages. If you feel like there is a significant decrease in error\nmessage quality that isn\'t easily amended by callers providing additional\ncontext themselves, please open an issue.\n\nThis release also updates Jiff\'s bundled copy of the [IANA Time Zone Database]\nto `2025c`. See the [`2025c` release announcement] for more details.\n\nEnhancements:\n\n* [#412](https://github.com/BurntSushi/jiff/issues/412):\nAdd `Display`, `FromStr`, `Serialize` and `Deserialize` trait implementations\nfor `jiff::civil::ISOWeekDate`. These all use the ISO 8601 week date format.\n* [#418](https://github.com/BurntSushi/jiff/issues/418):\nAdd some basic predicates to `jiff::Error` for basic error introspection.\n* [#453](https://github.com/BurntSushi/jiff/pull/453),\n [#454](https://github.com/BurntSushi/jiff/pull/454):\nSwitch to structured error handling internally.\n* [#456](https://github.com/BurntSushi/jiff/pull/456),\n [#457](https://github.com/BurntSushi/jiff/pull/457),\n [#458](https://github.com/BurntSushi/jiff/pull/458):\nVarious improvements to binary size.\n\n[`2025c` release announcement]: https://lists.iana.org/hyperkitty/list/tz-announce@iana.org/thread/TAGXKYLMAQRZRFTERQ33CEKOW7KRJVAK/\n\n\n0.2.16 (2025-11-07)\n===================\nThis release contains a number of enhancements and bug fixes that have accrued\nover the last few months. Most are small polishes. A couple of the bug fixes\napply to panics that could occur when parsing invalid `TZ` strings or invalid\n`strptime` format strings.\n\nAlso, parsing into a `Span` should now be much faster (for both the ISO 8601\nand \"friendly\" duration formats).\n\nEnhancements:\n\n* [#298](https://github.com/BurntSushi/jiff/issues/298):\nAdd Serde helpers for (de)serializing `std::time::Duration` values.\n* [#396](https://github.com/BurntSushi/jiff/issues/396):\nAdd `Sub` and `Add` trait implementations for `Zoned` (in addition to the\nalready existing trait implementations for `&Zoned`).\n* [#397](https://github.com/BurntSushi/jiff/pull/397):\nAdd `BrokenDownTime::set_meridiem` and ensure it overrides the hour when\nformatting.\n* [#409](https://github.com/BurntSushi/jiff/pull/409):\nSwitch dependency on `serde` to `serde_core`. This should help speed up\ncompilation times in some cases.\n* [#430](https://github.com/BurntSushi/jiff/pull/430):\nAdd new `Zoned::series` API, making it consistent with the same API on other\ndatetime types.\n* [#432](https://github.com/BurntSushi/jiff/pull/432):\nWhen `lenient` mode is enabled for `strftime`, Jiff will no longer error when\nthe formatting string contains invalid UTF-8.\n* [#432](https://github.com/BurntSushi/jiff/pull/432):\nFormatting of `%y` and `%g` no longer fails based on the specific year value.\n* [#432](https://github.com/BurntSushi/jiff/pull/432):\nParsing of `%s` is now a bit more consistent with other fields. Moreover,\n`BrokenDownTime::{to_timestamp,to_zoned}` will now prefer timestamps parsed\nwith `%s` over any other fields that have been parsed.\n* [#433](https://github.com/BurntSushi/jiff/pull/433):\nAllow parsing just a `%s` into a `Zoned` via the `Etc/Unknown` time zone.\n\nBug fixes:\n\n* [#386](https://github.com/BurntSushi/jiff/issues/386):\nFix a bug where `2087-12-31T23:00:00Z` in the `Africa/Casablanca` time zone\ncould not be round-tripped (because its offset was calculated incorrectly as\na result of not handling \"permanent DST\" POSIX time zones).\n* [#407](https://github.com/BurntSushi/jiff/issues/407):\nFix a panic that occurred when parsing an empty string as a POSIX time zone.\n* [#410](https://github.com/BurntSushi/jiff/issues/410):\nFix a panic that could occur when parsing `%:` via `strptime` APIs.\n* [#414](https://github.com/BurntSushi/jiff/pull/414):\nUpdate some parts of the documentation to indicate that `TimeZone::unknown()`\nis a fallback for `TimeZone::system()` (instead of the `jiff 0.1` behavior of\nusing `TimeZone::UTC`).\n* [#423](https://github.com/BurntSushi/jiff/issues/423):\nFix a panicking bug when reading malformed TZif data.\n* [#426](https://github.com/BurntSushi/jiff/issues/426):\nFix a panicking bug when parsing century (`%C`) via `strptime`.\n* [#445](https://github.com/BurntSushi/jiff/pull/445):\nFixed bugs with parsing durations like `-9223372036854775808s`\nand `-PT9223372036854775808S`.\n\nPerformance:\n\n* [#445](https://github.com/BurntSushi/jiff/pull/445):\nParsing into `Span` or `SignedDuration` is now a fair bit faster in some cases.\n\n\n0.2.15 (2025-06-13)\n===================\nThis release fixes a bug where error values were being constructed during\nparsing even in the success case. This was a regression introduced in `0.2.14`\nas a result of trying to improve compilation times. Thankfully, fixing this\nregression doesn\'t seem to meaningfully impact the amount of IR generated by\ncompiling Jiff.\n\nBug fixes:\n\n* [#385](https://github.com/BurntSushi/jiff/pull/385):\nFixes a performance regression for parsing.\n\n\n0.2.14 (2025-05-20)\n===================\nThis release includes a smattering of bug fixes, and hopefully a small\nimprovement to the time it takes to compile Jiff. Also, in this release, when\n`TZ` is set to a non-empty but invalid value, Jiff will always fall back to\n`Etc/Unknown` when using `TimeZone::system()`. This differs from previous\nbehavior where Jiff would, in this case, attempt to read the system\'s default\ntime zone. This change brings Jiff into consistency with existing Unix tooling\nlike `date`, and is also arguably a better failure mode. That is, when `TZ` is\nset but invalid, we shouldn\'t silently fall back to the default system time\nzone, but instead do something that indicates something has potentially gone\nwrong.\n\nEnhancements:\n\n* [#364](https://github.com/BurntSushi/jiff/issues/364):\nJiff now falls back to `Etc/Unknown` for invalid `TZ` values.\n* [#379](https://github.com/BurntSushi/jiff/pull/379):\nImprove compilation times.\n\nBug fixes:\n\n* [#365](https://github.com/BurntSushi/jiff/issues/365):\nFixes a compile error in Jiff when only the `tzdb-concatenated` feature was\nenabled.\n* [#366](https://github.com/BurntSushi/jiff/issues/366):\nFixes slow initial `Zoned::now()` in environments where `/usr/share/zoneinfo`\nis on a very slow file system (like CI environments).\n* [#376](https://github.com/BurntSushi/jiff/issues/376):\nAvoids searching for a tzdb at `/usr/share/zoneinfo` on Windows.\n\n\n0.2.13 (2025-05-05)\n===================\nThis release fixes a bug in a corner case where `TimeZone::following` could\nsometimes omit the last time zone transition. This could only happen in time\nzones that once had daylight saving time, but ended it. This did not have an\nimpact on other Jiff APIs that handle daylight saving time.\n\nBug fixes:\n\n* [#362](https://github.com/BurntSushi/jiff/issues/362):\nFix a bug where `TimeZone::following` could omit the last historical time zone\ntransition.\n\n\n0.2.12 (2025-05-03)\n===================\nThis release fixes a couple bugs in Jiff\'s parser. In particular, a regression\nwas introduced in `jiff 0.2.11` where its RFC 2822 parser could panic on some\ninputs. Previous releases of Jiff are unaffected.\n\nBug fixes:\n\n* [#357](https://github.com/BurntSushi/jiff/issues/357):\nFix a bug where parsing `1970-06-01T00-00:45:00[Africa/Monrovia]` succeeded\nbut it should fail.\n* [#359](https://github.com/BurntSushi/jiff/issues/359):\nFix a bug where the RFC 2822 parser could panic on some inputs.\n\n\n0.2.11 (2025-05-01)\n===================\nThis release includes new APIs for customizing Jiff\'s `strtime` behavior along\nwith a few minor bug fixes. Jiff\'s `strtime` formatting API has also been\noptimized. It\'s about twice as fast as it was.\n\nThis release also coincides with the publication of `jiff-icu 0.2.0-beta.2`,\nwhich has support for `icu 2.0.0-beta.2`.\n\nEnhancements:\n\n* [#338](https://github.com/BurntSushi/jiff/pull/338):\nAdd support for the `%c`, `%r`, `%X` and `%x` conversion specifiers.\n* [#341](https://github.com/BurntSushi/jiff/issues/341):\nAdd support for `%q` in `jiff::fmt::strtime` (prints quarter of year).\n* [#342](https://github.com/BurntSushi/jiff/issues/342):\nAdd support for `%::z` and `%:::z` in `jiff::fmt::strtime`.\n* [#344](https://github.com/BurntSushi/jiff/issues/344):\nAdd support for `%N` in `jiff::fmt::strtime` (alias for `%9f`).\n* [#350](https://github.com/BurntSushi/jiff/issues/350):\nAdd a \"lenient\" mode for `strtime` formatting APIs that ignores most errors.\n\nBug fixes:\n\n* [#328](https://github.com/BurntSushi/jiff/issues/328):\nDocument default precision behavior of `Display` impls for datetime types.\n* [#340](https://github.com/BurntSushi/jiff/issues/340):\nAllow whitespace in more places in RFC 2822 parser (improves spec compliance).\n* [#346](https://github.com/BurntSushi/jiff/issues/346):\n`TimeZone::get(\"UTC\")` should now always return `TimeZone::UTC`.\n\nPerformance:\n\n* [#338](https://github.com/BurntSushi/jiff/pull/338):\nJiff\'s `strftime` APIs are now approximately twice as fast as they were.\nPerformance should be comparable to `chrono` and `time`\'s prebuilt APIs.\n\n\n0.2.10 (2025-04-21)\n===================\nThis release includes a bug fix for parsing `Tuesday` when using `%A` via\nJiff\'s `strptime` APIs. Specifically, it would recognize `Tueday` instead of\n`Tuesday`.\n\nBug fixes:\n\n* [#333](https://github.com/BurntSushi/jiff/issues/333):\nFix typo in `strptime` parsing from `Tueday` to `Tuesday`.\n\n\n0.2.9 (2025-04-19)\n==================\nThis release includes a bug fix that, in debug mode, could result in datetime\ntypes having different hashes for the same value. This could cause problems,\nfor example, if you are using datetimes as keys in a hash map. This problem\ndidn\'t exist when Jiff was compiled in release mode.\n\nThis release also improves the panic message shown when the `js` feature isn\'t\nenabled and the current time is requested on `wasm32-unknown-unknown` targets.\n\nEnhancements:\n\n* [#296](https://github.com/BurntSushi/jiff/issues/296):\nProvide a better panic message when `Zoned::now()` fails on WASM.\n\nBug fixes:\n\n* [#330](https://github.com/BurntSushi/jiff/issues/330):\nFix bug where `Hash` on datetime types could yield different hash values for\nthe same underlying date/time.\n\n\n0.2.8 (2025-04-13)\n==================\nThis release fixes a bug where the constructors on `SignedDuration`\nfor floating point durations could panic (in debug mode) or produce\nincorrect results (in release mode). This bug only impacts users of\nthe `try_from_secs_{f32,f64}` and `from_secs_{f32,f64}` methods on\n`SignedDuration`.\n\nEnhancements:\n\n* [#326](https://github.com/BurntSushi/jiff/pull/326):\nAdd an alternate `Debug` impl for `SignedDuration` that only shows its second\nand nanosecond components (while using only one component when the other is\nzero).\n\nBug fixes:\n\n* [#324](https://github.com/BurntSushi/jiff/issues/324):\nFix a bug that could produce a panic or incorrect results in\n`SignedDuration::(try_)?from_secs_{f32,f64}`.\n\n\n0.2.7 (2025-04-13)\n==================\nThis release includes a bug fix that changes how an empty but set `TZ`\nenvironment variable is interpreted (as indistinguishable from `TZ=UTC`).\nThis also includes a new enabled by default create feature, `perf-inline`,\nwhich allows toggling Jiff\'s use of `inline(always)`. This may help improve\ncompile times or decrease binary size.\n\nEnhancements:\n\n* [#320](https://github.com/BurntSushi/jiff/pull/320):\nRemove some internal uses of generics to mildly improve compile times.\n* [#321](https://github.com/BurntSushi/jiff/pull/321):\nAdd `perf-inline` crate feature for controlling `inline(always)` annotations.\n\nBug fixes:\n\n* [#311](https://github.com/BurntSushi/jiff/issues/311):\nMake `TZ=` indistinguishable from `TZ=UTC`.\n\n\n0.2.6 (2025-04-07)\n==================\nThis release includes a few bug fixes and support for discovering the IANA Time\nZone Database automatically on Illumos.\n\nEnhancements:\n\n* [#315](https://github.com/BurntSushi/jiff/issues/315):\nAdd support for automatically finding the tzdb on Illumos.\n\nBug fixes:\n\n* [#305](https://github.com/BurntSushi/jiff/issues/305):\nFixed `Zoned` rounding on days with DST time zone transitions.\n* [#309](https://github.com/BurntSushi/jiff/issues/309):\nFixed bug where `TimeZone::preceding` could omit historical time zone\ntransitions for time zones that have eliminated DST in the present.\n* [#312](https://github.com/BurntSushi/jiff/issues/312):\nFixed `nth_weekday_in_month`, where it would sometimes incorrectly return an\nerror.\n\n\n0.2.5 (2025-03-22)\n==================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database] to\n`2025b`. See the [`2025b` release announcement] for more details.\n\nEnhancements:\n\n* [#300](https://github.com/BurntSushi/jiff/pull/300):\nUpdate `jiff-tzdb` to `2025b`.\n\n[`2025b` release announcement]: https://lists.iana.org/hyperkitty/list/tz-announce@iana.org/thread/6JVHNHLB6I2WAYTQ75L6KEPEQHFXAJK3/\n\n\n0.2.4 (2025-03-10)\n==================\nThis is another small release that fixes a problem where Jiff could break\nbuilds if they relied on inference for integer comparisons. Specifically, Jiff\nuses internal trait impls to make comparing its internal ranged integers\nmore convenient. But Rust the language has no concept of \"internal\" trait\nimpls, and thus this can impact type inference. If code was written in a way\nthat relies on a singular trait impl that is available, then adding Jiff to\nthe project can cause it to break.\n\nThis isn\'t arguably Jiff\'s fault per se, but since these trait impls were just\nabout internal convenience and not essential to Jiff\'s design, we adopt a\npragmatic approach and just remove them.\n\nBug fixes:\n\n* [#293](https://github.com/BurntSushi/jiff/issues/293):\nRemove internal trait impls that can cause breaks due to inference failures.\n\n\n0.2.3 (2025-03-07)\n==================\nThis is a small release that fixes a bug in the handling of POSIX time zones\nin some cases. Specifically, the implementation of `Date::yesterday` was wrong\nwhen the date was the first of the month. This was a regression introduced in\n`0.2.2` and was not present in older releases. More test coverage has been\nadded.\n\nBug fixes:\n\n* [#290](https://github.com/BurntSushi/jiff/issues/290):\nFix bug in implementation of `Date::yesterday`.\n\n\n0.2.2 (2025-03-06)\n==================\nThis release of Jiff includes a new opt-in proc macro for embedding a\n`TimeZone` into your binary. Just enable Jiff\'s `static` feature, and this will\nprint the current time in the `America/New_York` time zone:\n\n```rust,ignore\nuse jiff::{\n tz::{self, TimeZone},\n Timestamp,\n};\n\nfn main() {\n static TZ: TimeZone = tz::get!(\"America/New_York\");\n let zdt = Timestamp::now().to_zoned(TZ.clone());\n println!(\"{zdt}\");\n}\n```\n\nThis enables `TimeZone` to be meaningfully used in core-only environments,\neven when dynamic memory allocation isn\'t available.\n\nThis release also features a number of performance improvements for time zone\nlookups. In some cases, the improvement is significant (by an order of\nmagnitude).\n\nAdditionally, the IANA Time Zone Database embedded into `jiff-tzdb` now\nuses \"rearguard\" semantics. This means that the boolean flag indicating\nwhether daylight saving time is active or not (only accessible via\n`TimeZone::to_offset_info`) will respect the actual definition of\ndaylight saving time. (This is relevant, for example, for time zones like\n`Europe/Dublin`, where their summer time is _legally_ known as their standard\ntime, but is in effect daylight saving time.)\n\nEnhancements:\n\n* [#256](https://github.com/BurntSushi/jiff/issues/256):\nAdd `tz::{get,include}` macros for time zone support in core-only environments.\n* [#258](https://github.com/BurntSushi/jiff/issues/258):\nSwitch to `rearguard` tzdb data in `jiff-tzdb` and document it.\n* [#259](https://github.com/BurntSushi/jiff/pull/259):\nDe-duplicate TZif data in `jiff-tzdb`.\n* [#273](https://github.com/BurntSushi/jiff/issues/273):\nAdd \"crate features\" documentation to `jiff-sqlx` and `jiff-diesel`.\n* [#277](https://github.com/BurntSushi/jiff/issues/277):\nDocument semver guarantee for error conditions on `Timestamp` constructors.\n* [#277](https://github.com/BurntSushi/jiff/pull/287):\nGreatly optimize time zone lookups (for both timestamps and civil datetimes).\n\nBug fixes:\n\n* [#261](https://github.com/BurntSushi/jiff/issues/261):\nImprove the documentation for `ZonedWith::nanosecond` and\n`ZonedWith::subsec_nanosecond`.\n\n\n0.2.1 (2025-02-16)\n==================\nThis release includes a massive number of optimizations that significantly\nimproves performance in some cases. If you had a workload whose performance\nwith Jiff was underwhelming, please give it a try. I welcome questions via\n[Discussions on GitHub].\n\nThis release also provides a new API, `Timestamp::constant`, for constructing\n`Timestamp` values in a `const` context.\n\nEnhancements:\n\n* [#235](https://github.com/BurntSushi/jiff/discussions/235),\n [#255](https://github.com/BurntSushi/jiff/discussions/255),\n [#266](https://github.com/BurntSushi/jiff/pull/266):\nA massive number of performance improvements. Jiff should now generally be\nfaster than `chrono` and `time`.\n* [#263](https://github.com/BurntSushi/jiff/issues/263):\nAdd `Timestamp::constant` for constructing timestamps in `const` context.\n\n\n0.2.0 (2025-02-10)\n==================\nThis is a new semver incompatible release of Jiff. It contains several breaking\nchanges. I expect most users of Jiff to be able to upgrade without any changes.\nThe fundamental API organization of Jiff has not changed.\n\nSome of the highlights of this release include reducing footguns and better\necosystem integration.\n\nFor reducing footguns, APIs on `Span` will no longer implicitly assume that\ndays are always 24 hours long. And `Span` no longer implements `PartialEq` or\n`Eq` (instead favoring `span.fieldwise()` to create a value that supports naive\nfieldwise comparison). Moreover, when using `TimeZone::system()` (perhaps via\n`Zoned::now()`), if the system time zone could not be detected, then a special\n`Etc/Unknown` time zone will be used instead. This avoids erroring, but also\nsurfaces itself to make it clearer that something has (perhaps) gone wrong.\n\nAs for ecosystem integration, this release coincides with the publication\nof the [`jiff-icu`], [`jiff-sqlx`] and [`jiff-diesel`] crates. `jiff-icu`\nintegrates with the [ICU4X project], and is now the recommended way to use\nJiff to work with non-Gregorian calendars or to localize datetimes for end\nusers. `jiff-sqlx` and `jiff-diesel` provide wrapper types that implement the\nnecessary traits to make it ergonomic to store and retrieve Jiff values in a\ndatabase using [SQLx] or [Diesel], respectively.\n\nUnless something unexpected happens, my plan is for the next breaking change\nrelease to be Jiff 1.0 in about 6 months. Once Jiff 1.0 is out, I plan to\ncommit to it indefinitely.\n\n**BREAKING CHANGES**:\n\nThis is an exhaustive list of breaking changes. Changes with the bolded\n**RUNTIME** prefix are changes that will not be caught by the Rust compiler.\nThat is, they are changes in runtime behavior.\n\n* [#28](https://github.com/BurntSushi/jiff/issues/28):\nThe deprecated `intz` routines on `Zoned`, `Timestamp`, `civil::DateTime` and\n`civil::Date` have been removed. You can use `in_tz` instead. This change was\nmade because many found the name `intz` to be unclear.\n* [#32](https://github.com/BurntSushi/jiff/issues/32):\nThe `PartialEq` and `Eq` trait implementations on `Span` have been removed.\nIdeally these shouldn\'t have been used, but if you do need them, please use\n`Span::fieldwise` to create a `SpanFieldwise`, which does have the `PartialEq`\nand `Eq` traits implemented. These were removed on `Span` itself because they\nmade it very easy to commit subtle bugs.\n* [#36](https://github.com/BurntSushi/jiff/issues/36):\nTurn panics during `Timestamp::saturing_add` into errors. Callers adding\nspans that are known to contain units of hours or smaller are guaranteed that\nthis will not return an error.\n* **RUNTIME** [#48](https://github.com/BurntSushi/jiff/issues/48):\nOn `Span` APIs, days are no longer silently assumed to always be 24 hours when\na relative datetime is not provided. Instead, to perform operations on units\nof days or bigger, callers must either provide a relative date or opt into\ninvariant 24-hour days with `SpanRelativeTo::days_are_24_hours`. Shortcuts have\nbeen added to the span builders. For example, `SpanTotal::days_are_24_hours`.\n* **RUNTIME** [#147](https://github.com/BurntSushi/jiff/issues/147):\nChange the behavior of the deprecated `%V` conversion specifier in\n`jiff::fmt::strtime` from formatting an IANA time zone identifier to formatting\nan ISO 8601 week number. To format an IANA time zone identifier, use `%Q` or\n`%:Q` (which were introduced in `jiff 0.1`).\n* **RUNTIME** [#212](https://github.com/BurntSushi/jiff/issues/212):\nWhen parsing into a `Zoned` with a civil time corresponding to a gap, we treat\nall offsets as invalid and return an error. Previously, we would accept the\noffset as given. This brings us into line with Temporal\'s behavior. For\nexample, previously Jiff accepted `2006-04-02T02:30-05[America/Indiana/Vevay]`\nbut will now return an error. This is desirable for cases where a datetime in\nthe future is serialized before a change in the daylight saving time rules.\nFor more examples, see `jiff::fmt::temporal::DateTimeParser::offset_conflict`\nfor details on how to change Jiff\'s default behavior. This behavior change also\napplies to `tz::OffsetConflict::PreferOffset`.\n* **RUNTIME** [#213](https://github.com/BurntSushi/jiff/issues/213):\nTweak the semantics of `tz::TimeZoneDatabase` so that it only initializes one\ninternal tzdb instead of trying to find as many as possible. It is unlikely\nthat you\'ll be impacted by this change, but it\'s meant to make the semantics\nbe a bit more sensible. (In `jiff 0.1`, it was in theory possible for one tz\nlookup to succeed in the system zoneinfo and then another tz lookup to fail\nin zoneinfo but succeed automatically via the bundled copy. But this seems\nconfusing and possibly not desirable. Hence the change.)\n* [#218](https://github.com/BurntSushi/jiff/issues/218):\nIn order to make naming a little more consistent between `Zoned`\nand `civil::Date`, the `civil::Date::to_iso_week_date` and\n`civil::ISOWeekDate::to_date` APIs were renamed to `civil::Date::iso_week_date`\nand `civil::ISOWeekDate::date`.\n* [#220](https://github.com/BurntSushi/jiff/issues/220):\nRemove `Span::to_duration` for converting a `Span` to a `std::time::Duration`\nand rename `Span::to_jiff_duration` to `Span::to_duration`. This prioritizes\n`SignedDuration` as the \"primary\" non-calendar duration type in Jiff. And makes\nit more consistent with APIs like `Zoned::duration_since`. For non-calendar\nspans, the `TryFrom<Span> for std::time::Duration` still exists. For calendar\ndurations, use `Span::to_duration` and then convert the `SignedDuration` to\n`std::time::Duration`. Additionally, `Timestamp::from_jiff_duration` and\n`Timestamp::as_jiff_duration` were renamed to `Timestamp::from_duration` and\n`Timestamp::as_duration`, respectively. The old deprecated routines on the\nunsigned `std::time::Duration` have been removed.\n* [#221](https://github.com/BurntSushi/jiff/issues/221):\nChange the type of the value yielded by the `jiff::tz::TimeZoneNameIter`\niterator from `String` to `jiff::tz::TimeZoneName`. This opaque type is more\nAPI evolution friendly. To access the string, either use `TimeZoneName`\'s\n`Display` trait implementation, or its `as_str` method.\n* [#222](https://github.com/BurntSushi/jiff/issues/222):\nSplit `TimeZone::to_offset` into two methods. One that just returns the\noffset, and another, `TimeZone::to_offset_info`, which includes the offset,\nDST status and time zone abbreviation. The extra info is rarely needed and\nis sometimes more costly to compute. Also, make the lifetime of the time\nzone abbreviation returned by `TimeZoneTransition::abbreviation` tied to\nthe transition instead of the time zone (for future API flexibility, likely\nin core-only environments). This change was overall motivated by wanting to\ndo less work in the common case (where we only need the offset), and for\nreducing the size of a `TimeZone` considerably in core-only environments.\nCallers previously using `TimeZone::to_offset` to get DST status and time zone\nabbreviation should now use `TimeZone::to_offset_info`.\n* **RUNTIME** [#230](https://github.com/BurntSushi/jiff/issues/230):\nWhen `TimeZone::system()` cannot find a system configured time zone, `jiff\n0.1` would automatically fall back to `TimeZone::UTC` (with a WARN-level log\nmessage). In `jiff 0.2`, the fall back is now to `TimeZone::unknown()`, which\nhas a special `Etc/Unknown` identifier (as specified by Unicode and reserved by\nthe IANA time zone database). The fallback otherwise still behaves as if it\nwere `TimeZone::UTC`. This helps surface error conditions related to finding\nthe system time zone without causing unrecoverable failure.\n\nEnhancements:\n\n* [#136](https://github.com/BurntSushi/jiff/issues/136):\nWhen the special `SpanRelativeTo::days_are_24_hours()` marker is used, weeks\nwill also be treated as invariant. That is, seven 24-hour days. In all cases,\nworking with years and months still requires a relative date.\n* [#228](https://github.com/BurntSushi/jiff/issues/228):\nIt is now possible to forcefully use a bundled copy of the IANA time zone\ndatabase without relying on disabling crate features. This can be done by\nenabling the `tzdb-bundle-always` crate feature and explicitly creating a\n`jiff::tz::TimeZoneDatabase::bundled()` database. Once in hand, you must use\nAPIs like `TimeZoneDatabase::get` to create a `TimeZone` and avoid any APIs\nthat implicitly use the global time zone database (like `Timestamp::in_tz` or\neven `Zoned::from_str`).\n* [#238](https://github.com/BurntSushi/jiff/pull/238):\nAdd integration with the ICU4X project via the [`jiff-icu`] crate. `jiff-icu`\nprovides traits for easily converting between datetime types defined in Jiff\nand datetime types defined in ICU4X.\n* [#240](https://github.com/BurntSushi/jiff/pull/240):\nAdd integration with the SQLx project via the [`jiff-sqlx`] crate. `jiff-sqlx`\nprovides wrapper types that implement the necessary traits in SQLx for\nreasonably ergonomic integration. This includes PostgreSQL and SQLite support,\nbut not MySQL support. (It\'s not clear if it\'s possible at present to provide\nMySQL support for SQLx for datetime types outside of SQLx itself.)\n* [#241](https://github.com/BurntSushi/jiff/pull/241):\nAdd integration with the Diesel project via the [`jiff-diesel`] crate.\n`jiff-diesel` provides wrapper types that implement the necessary traits in\nDiesel for reasonably ergonomic integration. This includes MySQL, PostgreSQL\nand SQLite support.\n\n\n0.1.29 (2025-02-02)\n===================\nThis release includes a few small enhancements and a bug fix. In particular,\nthere is now Serde support for `TimeZone` and the `ISOWeekDate` API has been\nfilled out a bit more.\n\nUnless a serious issue is uncovered, my plan is that this will be the last\nrelease before `jiff 0.2`.\n\nEnhancements:\n\n* [#89](https://github.com/BurntSushi/jiff/issues/89):\nOpt-in support for using Serde with `jiff::tz::TimeZone` has been added.\n* [#227](https://github.com/BurntSushi/jiff/issues/227):\nThe `civil::ISOWeekDate` API has been beefed up with a few convenience methods.\n* [#233](https://github.com/BurntSushi/jiff/issues/233):\nAdd `tz::Offset::round` for rounding time zone offsets.\n\nBug fixes:\n\n* [#231](https://github.com/BurntSushi/jiff/issues/231):\nUse more flexible offset equality when parsing offsets with fractional minutes.\n\n\n0.1.28 (2025-01-27)\n===================\nThis is a small release that just removes the dev-dependency on `serde_yml`.\nIt has been replaced with the deprecated `serde_yaml`. See\n[this post about `serde_yml` shenanigans](https://x.com/davidtolnay/status/1883906113428676938)\nfor why this was done. Note that this was only a dev-dependency and thus doesn\'t\nimpact folks using Jiff.\n\nBug fixes:\n\n* [#225](https://github.com/BurntSushi/jiff/pull/225):\nRemove dependency on `serde_yml` in favor of `serde_yaml`.\n\n\n0.1.27 (2025-01-25)\n===================\nThis is a small release with a bug fix for precision loss in some cases when\ndoing arithmetic on `Timestamp` or `Zoned`.\n\nBug fixes:\n\n* [#223](https://github.com/BurntSushi/jiff/issues/223):\nFix the check for fractional seconds before taking the fast path.\n\n\n0.1.26 (2025-01-23)\n===================\nThis is a small release with another deprecation and a new API for doing\nprefix parsing via `strptime`. There\'s also a bug fix for a corner case\nwhen dealing with daylight saving time gaps with the `Zoned::with` API.\n\nDeprecations:\n\n* [#210](https://github.com/BurntSushi/jiff/pull/210):\n Deprecate `ISOWeekDate::to_date` in favor of `ISOWeekDate::date`.\n\nEnhancements:\n\n* [#209](https://github.com/BurntSushi/jiff/issues/209):\n Add `fmt::strtime::BrokenDownTime::parse_prefix` for parsing only a prefix.\n\nBug fixes:\n\n* [#211](https://github.com/BurntSushi/jiff/issues/211):\n Fix unintuitive behavior of `Zoned::with` when time falls in a DST gap.\n\n\n0.1.25 (2025-01-21)\n===================\nThis release contains a number of deprecations in preparation for a `jiff 0.2`\nrelease. The deprecations are meant to facilitate a smoother transition. The\ndeprecations, when possible, come with new APIs that will permit users to write\nforward compatible code that will work in both `jiff 0.1` and `jiff 0.2`.\n\nThis release also includes a handful of new conversion specifiers in Jiff\'s\n`strftime` and `strptime` APIs. This improves compatibility with the analogous\nimplementation with GNU libc.\n\nDeprecations:\n\n* [#28](https://github.com/BurntSushi/jiff/issues/28):\nThe `intz` methods on `Zoned`, `Timestamp`, `civil::DateTime` and `civil::Date`\nhave been deprecated in favor of `in_tz`.\n* [#32](https://github.com/BurntSushi/jiff/issues/32):\nThe `Eq` and `PartialEq` trait implementations on `Span` have been deprecated\nin favor of using the new `SpanFieldwise` type.\n* [#48](https://github.com/BurntSushi/jiff/issues/48):\nSilently assuming days are always 24 hours in some `Span` APIs has now been\ndeprecated. This will become an error in `jiff 0.2`. To continue assuming\ndays are 24 hours without a relative reference date, you can use the new\n`SpanRelativeTo::days_are_24_hours` API. In `jiff 0.1`, you\'ll seen a\nWARN-level log message emitted if you\'re code will be broken by `jiff 0.2`.\n* [#147](https://github.com/BurntSushi/jiff/issues/147):\nBoth `%V` and `%:V` have been deprecated in favor of `%Q` and `%:Q`. In\n`jiff 0.2`, `%V` will correspond to the ISO 8601 week number and `%:V` will\nresult in an error. This change was made to improve compatibility with other\n`strtime` implementations. `%V` and `%:V` continue to correspond to IANA\ntime zone identifiers in `jiff 0.1`, but using them for parsing or formatting\nwill result in a WARN-level deprecation message.\n\nEnhancements:\n\n* [#147](https://github.com/BurntSushi/jiff/issues/147):\nAdds a number of new conversion specifiers to Jiff\'s `strftime` and\n`strptime` APIs. Specifically, `%C`, `%G`, `%g`, `%j`, `%k`, `%l`, `%n`, `%R`,\n`%s`, `%t`, `%U`, `%u`, `%W`, `%w`. Their behavior should match the\ncorresponding specifiers in GNU libc.\n\n\n0.1.24 (2025-01-16)\n===================\nThis release updates Jiff\'s bundled copy of the [IANA Time Zone Database] to\n`2025a`. See the [`2025a` release announcement] for more details.\n\nEnhancements:\n\n* [#206](https://github.com/BurntSushi/jiff/pull/206):\nUpdate `jiff-tzdb` to `2025a`.\n\n[`2025a` release announcement]: https://lists.iana.org/hyperkitty/list/tz-announce@iana.org/thread/MWII7R3HMCEDNUCIYQKSSTYYR7UWK4OQ/\n\n\n0.1.23 (2025-01-13)\n===================\nThis release includes some bug fixes, particularly for compilation on\n`aarch64-linux-android`. There are also some minor enhancements, such as making\n`Zoned::iso_week_date` a convenience function for `civil::Date::iso_week_date`,\nin line with similar functions.\n\nMy current plan is to make a reasonably quick transition to `jiff 0.2` with a\nfew pending breaking changes. I will be making some `jiff 0.1` releases with\ndeprecations in order to make the transition as smooth as possible. If all goes\nwell with `jiff 0.2`, then my plan is still to do a Jiff 1.0 release in the\nSummer of 2025.\n\nDeprecations:\n\n* [#197](https://github.com/BurntSushi/jiff/discussions/197):\n`Date::to_iso_week_date` has been deprecated in favor of `Date::iso_week_date`.\n\nEnhancements:\n\n* [#196](https://github.com/BurntSushi/jiff/discussions/196):\nImprove ISO week date documentation regarding weekday offsets.\n* [#197](https://github.com/BurntSushi/jiff/discussions/197):\nAdd `Zoned::iso_week_date`, `DateTime::iso_week_date` and\n`Date::iso_week_date`.\n\nBug fixes:\n\n* [#200](https://github.com/BurntSushi/jiff/issues/200):\nFix compilation failure on Android in a Termux shell.\n* [#202](https://github.com/BurntSushi/jiff/pull/202):\nRe-add license files to crate artifact.\n\n\n0.1.22 (2025-01-12)\n===================\nThis release adds support for Android. This support means that Jiff will\nautomatically read its special concatenated time zone database, and will\nread the `persist.sys.timezone` property to determine the system\'s current\ntime zone.\n\nSee [PLATFORM] for more specific information about Android support.\n\nNote that this release also removed all non-essential files (including tests\nand test data) for the artifact uploaded to crates.io. If you need or want\nthese files, please open a new issue.\n\nEnhancements:\n\n* [#140](https://github.com/BurntSushi/jiff/issues/140):\nAdd support for the Android platform.\n\n\n0.1.21 (2025-01-04)\n===================\nThis release includes a new API for setting the unit designator label in a\nfriendly formatted duration for zero-length durations.\n\nEnhancements:\n\n* [#192](https://github.com/BurntSushi/jiff/issues/192):\nAdd option to the friendly printer for setting the unit when writing a\nzero-length duration.\n\n\n0.1.20 (2025-01-03)\n===================\nThis release includes a new type, `Pieces`, in the `jiff::fmt::temporal`\nsub-module. This exposes the individual components of a parsed Temporal\nISO 8601 datetime string. It allows users of Jiff to circumvent the checks\nin the higher level parsing routines that prevent you from shooting yourself\nin the foot.\n\nFor example, parsing into a `Zoned` will return an error for raw RFC 3339\ntimestamps like `2025-01-03T22:03-05` because there is no time zone annotation.\nWithout a time zone, Jiff cannot do time zone aware arithmetic and rounding.\nInstead, such a datetime can only be parsed into a `Timestamp`. This lower\nlevel `Pieces` API now permits users of Jiff to parse this string into its\ncomponent parts and assemble it into a `Zoned` if they so choose.\n\nEnhancements:\n\n* [#188](https://github.com/BurntSushi/jiff/issues/188):\nAdd `fmt::temporal::Pieces` for granular datetime parsing and formatting.\n\n\n0.1.19 (2025-01-02)\n===================\nThis releases includes a UTF-8 related bug fix and a few enhancements.\n\nFirstly, a `Span`\'s default `Display` implementation now writes uppercase\nunit designator labels. That means you\'ll get `P1Y2M3DT4H5M6S` instead\nof `P1y2m3dT4h5m6s` by default. You can restore previous behavior via\n`jiff::fmt::temporal::SpanPrinter::lowercase`. This change was made to improve\ninteroperability.\n\nSecondly, `SignedDuration` now supports rounding via `SignedDuration::round`.\nNote that it only supports rounding time units (hours or smaller). In order to\nround with calendar units, you\'ll still need to use a `Span`.\n\nEnhancements:\n\n* [#130](https://github.com/BurntSushi/jiff/issues/130):\nDocument value ranges for methods like `year`, `day`, `hour` and so on.\n* [#187](https://github.com/BurntSushi/jiff/issues/187):\nAdd a rounding API (for time units only) on `SignedDuration`.\n* [#190](https://github.com/BurntSushi/jiff/issues/190):\n`Span` and `SignedDuration` now use uppercase unit designator labels in their\ndefault ISO 8601 `Display` implementation.\n\nBug fixes:\n\n* [#155](https://github.com/BurntSushi/jiff/issues/155):\nRelax `strftime` format strings from ASCII-only to all of UTF-8.\n\n\n0.1.18 (2024-12-31)\n===================\nThis release includes a few minor enhancements. Namely, the ability to iterate\nover time zone transitions (in the future or the past), and some improvements\nto failure modes when `Timestamp` and `Span` arithmetic fails.\n\nEnhancements:\n\n* [#144](https://github.com/BurntSushi/jiff/issues/144):\nAdd APIs for iterating over the transitions of a time zone.\n* [#145](https://github.com/BurntSushi/jiff/issues/145):\nImprove docs and error messages around fallible `Timestamp` arithmetic.\n\n\n0.1.17 (2024-12-31)\n===================\nThis release enhances Jiff\'s support for `no_std` environments by making its\n`alloc` feature optional. When `alloc` is disabled, only fixed offset time\nzones are supported and error messages are significantly degraded. If you have\ncore-only use cases for Jiff, I\'d love to hear about them on the issue tracker.\n\nEnhancements:\n\n* [#162](https://github.com/BurntSushi/jiff/issues/162):\nSupport platforms that do not have atomics in `std`.\n* [#168](https://github.com/BurntSushi/jiff/issues/168):\nJiff now supports disabling the `alloc` feature, which enables core-only mode.\n* [#169](https://github.com/BurntSushi/jiff/issues/169):\nAdd `TimeZone::to_fixed_offset` for accessing an invariant offset if possible.\n\n\n0.1.16 (2024-12-26)\n===================\nThis release includes a new `jiff::fmt::friendly` module for formatting and\nparsing durations in a more human readable format than what ISO 8601 specifies.\nISO 8601 remains the \"default\" duration format in Jiff due to its widespread\nsupport. Here are some examples:\n\n```text\n40d\n40 days\n1y1d\n1yr 1d\n3d4h59m\n3 days, 4 hours, 59 minutes\n3d 4h 59m\n2h30m\n2h 30m\n1mo\n1w\n1 week\n1w4d\n1 wk 4 days\n1m\n0.0021s\n0s\n0d\n0 days\n3 mins 34s 123ms\n3 mins 34.123 secs\n3 mins 34,123s\n1y1mo1d1h1m1.1s\n1yr 1mo 1day 1hr 1min 1.1sec\n1 year, 1 month, 1 day, 1 hour, 1 minute 1.1 seconds\n1 year, 1 month, 1 day, 01:01:01.1\n```\n\nTo quickly demonstrate this new feature, here\'s a simple CLI program using\nClap:\n\n```ignore\nuse clap::Parser;\nuse jiff::{Span, Zoned};\n\n#[derive(Parser, Debug)]\n#[command(version, about, long_about = None)]\nstruct Args {\n duration: Span,\n}\n\nfn main() {\n let args = Args::parse();\n println!(\"adding duration to now: {}\", &Zoned::now() + args.duration);\n}\n```\n\nAnd running the program:\n\n```text\n$ cargo run -q -- \'1 year, 2 months, 5 hours\'\nadding duration to now: 2026-02-26T18:58:22-05:00[America/New_York]\n$ cargo run -q -- \'P1Y2MT5H\' # ISO 8601 durations are supported too!\nadding duration to now: 2026-02-26T19:00:57-05:00[America/New_York]\n```\n\nWith Jiff, you should no longer need to pull in crates like\n[`humantime`](https://docs.rs/humantime) and\n[`humantime-serde`](https://docs.rs/humantime-serde)\nto accomplish a similar task.\n\nWhile this new format doesn\'t support any kind of internationalization, the\nprevalence of the `humantime` crate suggests there\'s a desire for something\nlike this. The \"friendly\" format is meant to service all the same use cases\nas `humantime` does for durations, but in a way that doesn\'t let you shoot\nyourself in the foot.\n\nThe new \"friendly\" format is now the default for the `Debug` implementations\nof both `Span` and `SignedDuration`. It\'s also available via the \"alternate\"\n`Display` implementations for `Span` and `SignedDuration` as well. Moreover,\nthe `FromStr` trait implementations for both `Span` and `SignedDuration` will\nparse _both_ the ISO 8601 duration and this new \"friendly\" format. Finally,\nwhen `serde` integration is enabled, the `Deserialize` implementations for\n`SignedDuration` and `Span` also automatically parse either ISO 8601 or the\nfriendly format. For serialization, ISO 8601 remains the default, but the\n`jiff::fmt::serde` module provides easy to use helpers to switch to the\nfriendly format.\n\nThe `jiff::fmt::friendly` module documentation provides many more details,\nincluding a complete grammar for the format.\n\nEnhancements:\n\n* [#143](https://github.com/BurntSushi/jiff/pull/143):\nAdd `Hash` implementation for `Zoned` and `Timestamp`.\n\nBug fixes:\n\n* [#60](https://github.com/BurntSushi/jiff/issues/60):\nUse a better `Debug` output format for `SignedDuration` and `Span`.\n* [#111](https://github.com/BurntSushi/jiff/issues/111):\nAdd a new \"friendly\" duration format.\n* [#138](https://github.com/BurntSushi/jiff/issues/138):\nFix deserialization in `serde_yml` and `serde_yaml` crates.\n* [#161](https://github.com/BurntSushi/jiff/pull/161):\nFix `serde` dependency configuration so that it builds in no-std mode.\n\n\n0.1.15 (2024-11-30)\n===================\nThis release fixes a bug where Jiff would sometimes fail to parse TZif files\n(found, typically, in `/usr/share/zoneinfo` on Unix systems). This occurred\nwhen the TZif file contained a time zone transition outside the range of Jiff\'s\n`Timestamp` type (which is `-9999-01-01` to `9999-12-31`). The bug fix works by\nclamping the out-of-range transitions to Jiff\'s supported range.\n\nThis bug only seems to occur in some environments where their TZif files\ncontain more extreme values than what is typically found.\n\nBug fixes:\n\n* [#163](https://github.com/BurntSushi/jiff/issues/163):\nFix a bug where Jiff would fail to parse some TZif files.\n\n\n0.1.14 (2024-11-01)\n===================\nThis release introduces new APIs to the RFC 2822 printer that explicitly\nprint timestamps in a format strictly compatible with [RFC 9110].\n\nEnhancements:\n\n* [#151](https://github.com/BurntSushi/jiff/issues/151):\nAdd `rfc2822::DateTimePrinter::timestamp_to_rfc9110_string` method.\n\n\n0.1.13 (2024-09-07)\n===================\nThis release introduces a new `jiff::tz::TimeZone::try_system` API. It is like\n`TimeZone::system`, but returns an error instead of an automatic fall back to\nUTC when the system time zone could not be discovered.\n\nThis also includes an update to the bundled [IANA Time Zone Database] to the\n`2024b` release in the `jiff-tzdb` crate. As a reminder, the bundled database\nis not used or included on Unix platforms by default. See [PLATFORM] for more\ndetails.\n\nEnhancements:\n\n* [#65](https://github.com/BurntSushi/jiff/issues/65):\nAdd `TimeZone::try_system` for fallibly determining the system\'s time zone.\n* [#125](https://github.com/BurntSushi/jiff/pull/125):\nUpdate to the `2024b` release of the [IANA Time Zone Database].\n\n\n0.1.12 (2024-08-31)\n===================\nThis release introduces some new minor APIs that support formatting\n`Timestamp` values as RFC 3339 strings with a specific offset.\n\nPreviously, using the standard formatting routines that Jiff provides, it was\nonly possible to format a `Timestamp` using Zulu time. For example:\n\n```rust,ignore\nuse jiff::Timestamp;\n\nassert_eq!(\n Timestamp::UNIX_EPOCH.to_string(),\n \"1970-01-01T00:00:00Z\",\n);\n```\n\nThis is fine most use cases, but it can be useful on occasion to format\na `Timestamp` with a specific offset. While this isn\'t as expressive\nas formatting a datetime with a time zone (e.g., with an IANA time\nzone identifier), it may be useful in contexts where you just want to\n\"hint\" at what a user\'s local time is. To that end, there is a new\n`Timestamp::display_with_offset` method that makes this possible:\n\n```rust,ignore\nuse jiff::{tz, Timestamp};\n\nassert_eq!(\n Timestamp::UNIX_EPOCH.display_with_offset(tz::offset(-5)).to_string(),\n \"1969-12-31T19:00:00-05:00\",\n);\n```\n\nA corresponding API was added to `jiff::fmt::temporal::DateTimePrinter` for\nlower level use.\n\nMoreover, this release also includes new convenience APIs on the Temporal and\nRFC 2822 printer types for returning strings. For example, previously, if you\nwere using the RFC 2822 printer to format a `Timestamp`, you had to do this:\n\n```rust,ignore\nuse jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};\n\nlet mut buf = String::new();\nDateTimePrinter::new().print_timestamp(&Timestamp::UNIX_EPOCH, &mut buf).unwrap();\nassert_eq!(buf, \"Thu, 1 Jan 1970 00:00:00 -0000\");\n```\n\nBut now you can just do this:\n\n```rust,ignore\nuse jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};\n\nassert_eq!(\n DateTimePrinter::new().timestamp_to_string(&Timestamp::UNIX_EPOCH).unwrap(),\n \"Thu, 1 Jan 1970 00:00:00 -0000\",\n);\n```\n\nEnhancements:\n\n* [#122](https://github.com/BurntSushi/jiff/pull/122):\nSupport formatting `Timestamp` to an RFC 3339 string with a specific offset.\n\n\n0.1.11 (2024-08-28)\n===================\nThis release includes a few small enhancements that have been requested over\nthe last several weeks. The biggest enhancement is a new `jiff::fmt::serde`\nsub-module. It provides convenience routines similar to Chrono\'s\n`chrono::serde` sub-module for serializing and deserializing between a\n`jiff::Timestamp` and an integer number of seconds, milliseconds, microseconds\nor nanoseconds. For example:\n\n```rust,ignore\nuse jiff::Timestamp;\n\n#[derive(serde::Serialize, serde::Deserialize)]\nstruct Record {\n #[serde(with = \"jiff::fmt::serde::timestamp::second::required\")]\n timestamp: Timestamp,\n}\n\nlet json = r#\"{\"timestamp\":1517644800}\"#;\nlet got: Record = serde_json::from_str(&json).unwrap();\nassert_eq!(got.timestamp, Timestamp::from_second(1517644800).unwrap());\nassert_eq!(serde_json::to_string(&got).unwrap(), json);\n```\n\nIf you need to support optional timestamps via `Option<Timestamp>`, then use\n`jiff::fmt::serde::timestamp::second::optional` instead. Similarly, if you\nneed to support milliseconds instead of seconds, then replace `second` with\n`millisecond` in the module path.\n\nEnhancements:\n\n* [#78](https://github.com/BurntSushi/jiff/issues/78):\nAdd `BrokenDownTime::set_{offset,iana_time_zone}` APIs.\n* [#93](https://github.com/BurntSushi/jiff/issues/93):\nAdd note about using `Timestamp::now().to_zoned()` instead of\n`Zoned::now().with_time_zone()`.\n* [#101](https://github.com/BurntSushi/jiff/issues/101):\nAdd new `jiff::fmt::serde` module for integration with integer timestamps.\n* [#117](https://github.com/BurntSushi/jiff/pull/117):\nRemove `unsafe` usage in `libm` functions (applicable only to no-std users).\n\n\n0.1.10 (2024-08-23)\n===================\nThis release features a small bug fix where Jiff will detect an IANA time\nzone identifier in some cases where it wouldn\'t before. While Jiff would\npreviously read the symlink metadata on `/etc/localtime` by default to discover\nthe system configured time zone on Unix systems, it *wouldn\'t* do so when\n`TZ=/etc/localtime`. There\'s really no reason not to, so this release of Jiff\nis fixed to use symlink sniffing on file paths provided by the `TZ` environment\nvariable.\n\nBug fixes:\n\n* [#113](https://github.com/BurntSushi/jiff/issues/113):\nWhen `TZ=/etc/localtime`, use symlink metadata to detect IANA identifier.\n\n\n0.1.9 (2024-08-23)\n==================\nThis release introduces new options for controlling the precision\nof fractional seconds when printing `Zoned`, `Timestamp`,\n`civil::DateTime` or `civil::Time` values. This is principally exposed\nvia `jiff::fmt::temporal::DateTimePrinter::precision`, but it\'s also\navailable via the standard library\'s formatting machinery. For example,\nif `zdt` is a `jiff::Zoned`, then `format!(\"{zdt:.6}\")` will format\nit into a string with microsecond precision, even if its fractional\ncomponent is zero.\n\nEnhancements:\n\n* [#92](https://github.com/BurntSushi/jiff/issues/92):\nSupport setting the precision of fractional seconds when printing datetimes.\n\n\n0.1.8 (2024-08-19)\n==================\nThis releases fixes a build error in Jiff\'s `alloc`-only configuration. This\nregression was introduced in `jiff 0.1.6`.\n\nBug fixes:\n\n* [#108](https://github.com/BurntSushi/jiff/issues/108):\nUse `core::time::Duration` everywhere instead of `std::time::Duration`.\n\n\n0.1.7 (2024-08-18)\n==================\nThis release relaxes Jiff\'s dependency on `windows-sys` to include multiple\nsemver incompatible releases. The purpose of this relaxation is to enable\nJiff to work with different versions of `windows-sys` in the hopes that this\nreduces the likelihood that multiple copies of `windows-sys` are included in\nyour dependency tree.\n\nDependencies:\n\n* [#106](https://github.com/BurntSushi/jiff/pull/106):\nRelax `windows-sys` dependency constraint to `>=0.52.0, <=0.59.*`.\n\n\n0.1.6 (2024-08-18)\n==================\nThis release includes a new top-level type, `SignedDuration`, that provides a\nnear exact replica of `std::time::Duration`, but signed. It is meant to provide\nalternative APIs for working with durations at a lower level than what `Span`\nprovides, and to facilitate better integration with the standard library.\n\nA `SignedDuration` has also been integrated with all of Jiff\'s datetime types.\nFor example, previously, `Zoned::checked_add` only accepted a concrete\n`jiff::Span`. But now it accepts a `jiff::Span`, `jiff::SignedDuration` or even\na `std::time::Duration`. Moreover, all of the `until` and `since` APIs on\ndatetime types have been ported and copied to return `SignedDuration` under the\n`duration_until` and `duration_since` names.\n\nThis marks an initial integration phase with `SignedDuration`. It is planned\nto integrate it more with the datetime types. Currently, there are integrations\non `Timestamp` and `Span`, but more will be added in the future.\n\nOverall, folks should still use `Span`. That is the intended default duration\ntype in Jiff and will continue to be. Users of Jiff may find `SignedDuration`\nuseful in contexts where speed is important or when one needs to integrate\nwith the standard library.\n\nThis release also includes a few related deprecations as the APIs involving\n`std::time::Duration` are phased out in favor of `SignedDuration`.\n\nDeprecations:\n\n* `Timestamp::as_duration`: replaced with `as_jiff_duration`, which will be\nrenamed to `as_duration` in `jiff 0.2`.\n* `Timestamp::from_duration`: replaced with `from_jiff_duration`, which will be\nrenamed to `from_duration` in `jiff 0.2`.\n* `Timestamp::from_signed_duration`: replaced with `from_jiff_duration`.\n* `Span::to_duration`: replaced with `to_jiff_duration`, which will be renamed\nto `to_duration` in `jiff 0.2`.\n\nBasically, all of the above APIs either accept or return a\n`std::time::Duration`. To avoid breaking changes at this point, new methods\nfor `SignedDuration` were added. For example, `Timestamp::as_jiff_duration`.\nIn `jiff 0.2`, the above deprecated methods will be removed and replaced with\nequivalent methods that accept or return a `SignedDuration` instead. Callers\ncan then convert between a `SignedDuration` and a `std::time::Duration` using\nappropriate `TryFrom` trait implementations.\n\nEnhancements:\n\n* [#21](https://github.com/BurntSushi/jiff/issues/21):\nAdd new top-level `SignedDuration` type.\n* [#90](https://github.com/BurntSushi/jiff/issues/90):\nImprove error message when using `Span` with >=day units with a `Timestamp`.\n\nPerformance:\n\n* [#104](https://github.com/BurntSushi/jiff/pull/104)\nOptimize offset calculations in time zones without DST.\n* [#105](https://github.com/BurntSushi/jiff/pull/105)\nOptimize offset calculations for timestamps after last DST rule change.\n\n\n0.1.5 (2024-08-09)\n==================\nThis release includes some improvements and bug fixes, particularly for Jiff\'s\n`strtime` APIs.\n\nEnhancements:\n\n* [#63](https://github.com/BurntSushi/jiff/issues/63):\nAdd link to original Chrono maintainer\'s commentary in `DESIGN.md`.\n* [#75](https://github.com/BurntSushi/jiff/issues/75):\nAdd support for `%V` for formatting _and_ parsing IANA time zone identifiers.\n* [#79](https://github.com/BurntSushi/jiff/pull/79):\nAdd `devcontainer.json` to support GitHub Codespaces.\n* [#85](https://github.com/BurntSushi/jiff/pull/85):\nSet correct ranges for internal tracking in return value of `days_in_month`.\n\nBug fixes:\n\n* [#59](https://github.com/BurntSushi/jiff/issues/59):\nFixes a bug where some `Span`s could not be roundtripped through ISO 8601.\n* [#71](https://github.com/BurntSushi/jiff/issues/71):\nTweak wording in documentation of \"printf\"-style API.\n* [#73](https://github.com/BurntSushi/jiff/issues/73):\nMake it so `%.Nf` only formats to `N` decimal places.\n* [#77](https://github.com/BurntSushi/jiff/pull/77):\nDisable optimizations when running tests.\n\n\n0.1.4 (2024-08-01)\n==================\nThis release includes a small improvement for `strptime` that permits\n`%Y%m%d` to parse `20240730` correctly.\n\nEnhancements:\n\n* [#62](https://github.com/BurntSushi/jiff/issues/62):\nTweak `strptime` so that things like `%Y` aren\'t unceremoniously greedy.\n\n\n0.1.3 (2024-07-30)\n==================\nThis release features support for `wasm32-unknown-unknown`. That is, when\nJiff\'s new `js` crate feature is enabled, Jiff will automatically use\nJavaScript APIs to determine the current time and time zone.\n\nEnhancements:\n\n* [#58](https://github.com/BurntSushi/jiff/pull/58):\nAdd WASM support and a new `PLATFORM.md` guide.\n\n\n0.1.2 (2024-07-28)\n==================\nThis release features a few new APIs that a need for arose while experimenting\nwith actually using Jiff in real projects. Namely, the `jiff::fmt::strtime`\nmodule now has `%f` and `%.f` directives for parsing and formatting fractional\nseconds. And both `jiff::fmt::rfc2822` and `jiff::fmt::strtime` now have\nsupport for skipping weekday checks during parsing. (Previously, Jiff required\nthat an English weekday be consistent with the date parsed, and there was no\nway to opt out. While this is still the default behavior, callers can disable\nthis check.)\n\nEnhancements:\n\n* [#52](https://github.com/BurntSushi/jiff/pull/52):\nImprove documentation for `Span` getter methods.\n* [#53](https://github.com/BurntSushi/jiff/pull/53):\nAdd support for skipping weekday checking when parsing datetimes.\n* [#55](https://github.com/BurntSushi/jiff/pull/55):\nAdd support for fractional seconds in `jiff::fmt::strtime`.\n\nBug fixes:\n\n* [#49](https://github.com/BurntSushi/jiff/pull/49):\nFix informational regex describing ISO 8601 format.\n* [#51](https://github.com/BurntSushi/jiff/pull/51):\nExplicitly allow new deny-by-default lint `ambiguous_negative_literals`.\n\n\n0.1.1 (2024-07-25)\n==================\nThis is a new semver compatible release. The principle addition are APIs for\nconverting between a `jiff::Span` and a `std::time::Duration`. Specifically,\nthere are now `TryFrom<Span> for Duration` and `TryFrom<Duration> for Span`\ntrait implementations. There is also a `Span::to_duration`, which requires a\nrelative date, for converting spans with non-uniform units (like months) to a\n`Duration`.\n\nEnhancements:\n\n* [#21](https://github.com/BurntSushi/jiff/issues/21),\n [#40](https://github.com/BurntSushi/jiff/issues/40):\nAdds APIs for converting between `Span` and `std::time::Duration`.\n\nBug fixes:\n\n* [#36](https://github.com/BurntSushi/jiff/issues/36):\nSaturating arithmetic for `Timestamp` panics with day-or-greater units.\n* [#38](https://github.com/BurntSushi/jiff/issues/38):\nFix some bugs in the micro-benchmarks.\n* [#39](https://github.com/BurntSushi/jiff/issues/39):\nDocument that the RFC 2822 parser is not technically fully spec compliant.\n\n\n0.1.0 (2024-07-21)\n==================\nThe initial release of Jiff.\n\n[IANA Time Zone Database]: https://www.iana.org/time-zones\n[PLATFORM]: PLATFORM.md\n[RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.7-15\n[`jiff-icu`]: https://docs.rs/jiff-icu\n[`jiff-sqlx`]: https://docs.rs/jiff-sqlx\n[`jiff-diesel`]: https://docs.rs/jiff-diesel\n[ICU4X project]: https://github.com/unicode-org/icu4x\n[SQLx]: https://github.com/launchbadge/sqlx\n[Diesel]: https://github.com/diesel-rs/diesel\n[Discussions on GitHub]: https://github.com/BurntSushi/jiff/discussions\n[`defmt`]: https://github.com/BurntSushi/jiff/issues/587\n"include_str!("../CHANGELOG.md")]
810pub mod changelog {}
811}
812813#[cfg(test)]
814mod tests {
815use super::*;
816817#[cfg(feature = "std")]
818 #[test]
819fn now_works() {
820let _ = crate::logging::Logger::init();
821822let zdt = ZonedDateTime::now();
823std::println!("{zdt}");
824 }
825826#[cfg(feature = "std")]
827 #[test]
828fn ranges() {
829use crate::util::b;
830831dbg!((b::SpanYears::MIN, b::SpanYears::MAX));
832dbg!((b::SpanMonths::MIN, b::SpanMonths::MAX));
833dbg!((b::SpanWeeks::MIN, b::SpanWeeks::MAX));
834dbg!((b::SpanDays::MIN, b::SpanDays::MAX));
835dbg!((b::SpanHours::MIN, b::SpanHours::MAX));
836dbg!((b::SpanMinutes::MIN, b::SpanMinutes::MAX));
837dbg!((b::SpanSeconds::MIN, b::SpanSeconds::MAX));
838dbg!((b::SpanMilliseconds::MIN, b::SpanMilliseconds::MAX));
839dbg!((b::SpanMicroseconds::MIN, b::SpanMicroseconds::MAX));
840dbg!((b::SpanNanoseconds::MIN, b::SpanNanoseconds::MAX));
841dbg!((b::UnixEpochSeconds::MIN, b::UnixEpochSeconds::MAX));
842dbg!((b::UnixEpochDays::MIN, b::UnixEpochDays::MAX));
843 }
844845#[cfg(feature = "std")]
846 #[test]
847fn maximally_long_span() {
848use crate::{fmt::friendly, util::b};
849850let span = Span::new()
851 .years(b::SpanYears::MAX)
852 .months(b::SpanMonths::MAX)
853 .weeks(b::SpanWeeks::MAX)
854 .days(b::SpanDays::MAX)
855 .hours(b::SpanHours::MAX)
856 .minutes(b::SpanMinutes::MAX)
857 .seconds(b::SpanSeconds::MAX)
858 .milliseconds(b::SpanMilliseconds::MAX)
859 .microseconds(b::SpanMicroseconds::MAX)
860 .nanoseconds(b::SpanNanoseconds::MAX)
861 .negate();
862std::println!("{span}");
863std::println!("{span:#}");
864865let long_printer = friendly::SpanPrinter::new()
866 .designator(friendly::Designator::Verbose)
867 .spacing(friendly::Spacing::BetweenUnitsAndDesignators)
868 .comma_after_designator(true);
869std::println!("{}", long_printer.span_to_string(&span));
870 }
871872#[cfg(feature = "std")]
873 #[test]
874fn maximally_long_duration() {
875let sdur = SignedDuration::MIN;
876std::println!("{sdur}");
877std::println!("{sdur:#}");
878 }
879}