{"article":{"slug":"jiff-1-0-a-datetime-library-for-rust","title":"Jiff 1.0: A datetime library for Rust","subtitle":null,"summary":"Andrew Gallant (BurntSushi) announces the Jiff 1.0 release, a Rust datetime library that puts time zone handling front and center, with a tour of its API and comparisons to Temporal.","content_type":"announcement","language":"en","canonical_url":"https://burntsushi.net/jiff/","author":{"name":"Andrew Gallant","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Andrew Gallant's Blog","url":"https://burntsushi.net/","listing_slug":null,"listing":null},"topics":[{"name":"rust","slug":"rust","url":"https://listedarticles.com/topics/rust"},{"name":"open-source","slug":"open-source","url":"https://listedarticles.com/topics/open-source"},{"name":"developer-tools","slug":"developer-tools","url":"https://listedarticles.com/topics/developer-tools"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":9637,"reading_minutes":42,"published_at":"2026-11-16T19:49:26.092Z","added_at":"2026-11-16T19:49:26.092Z","updated_at":"2026-11-16T19:49:26.092Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/jiff-1-0-a-datetime-library-for-rust","markdown_url":"https://listedarticles.com/articles/jiff-1-0-a-datetime-library-for-rust.md","example":false,"citation":"Andrew Gallant, Andrew Gallant's Blog. \"Jiff 1.0: A datetime library for Rust.\" 16 Nov 2026. https://burntsushi.net/jiff/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://burntsushi.net/jiff/"},"body_markdown":"# Jiff 1.0: A datetime library for Rust\n\n[Jiff](https://github.com/BurntSushi/jiff) is a datetime library for Rust that encourages you to jump into the\n[pit of success](https://blog.codinghorror.com/falling-into-the-pit-of-success/). Jiff automatically handles many common problems related to\ndaylight saving time by putting time zone handling front and center into the\nAPI. Jiff has already seen widespread [adoption](https://crates.io/crates/jiff/reverse_dependencies) in the Rust ecosystem.\n\nJiff is pronounced like “gif” with a soft “g,” as in “gem.”\n\nThis blog announces the Jiff 1.0 release by giving a tour of its API.\n\n**Target audience**: Rust programmers who need convenient datetime handling.\n\n## Table of Contents\n\n- [The Jiff 1.0 Commitment](#the-jiff-10-commitment)\n- [Introduction](#introduction)\n  - [Follow Along](#follow-along)\n  - [Terms](#terms)\n  - [The DateTime Onion](#the-datetime-onion)\n  - [Defining a time zone](#defining-a-time-zone)\n  - [Durations](#durations)\n  - [When should I use Jiff?](#when-should-i-use-jiff)\n- [Parsing and Formatting](#parsing-and-formatting)\n  - [`FromStr` and `Display`](#fromstr-and-display)\n  - [The “friendly” Duration Format](#the-friendly-duration-format)\n  - [`strptime` and `strftime`](#strptime-and-strftime)\n  - [The `jiff::fmt` module](#the-jifffmt-module)\n  - [Locale Sensitive Formatting via ICU4X Integration](#locale-sensitive-formatting-via-icu4x-integration)\n- [Date Manipulation](#date-manipulation)\n  - [Date Basics](#date-basics)\n  - [Date Arithmetic](#date-arithmetic)\n  - [Date Rounding](#date-rounding)\n  - [Other Calendars](#other-calendars)\n  - [Which DateTime Type Do I Use?](#which-datetime-type-do-i-use)\n- [Span Manipulation](#span-manipulation)\n- [Conclusion](#conclusion)\n  - [Motivation](#motivation)\n  - [Inspiration](#inspiration)\n\n## The Jiff 1.0 Commitment\n\nJiff is already used in production in many projects: uv, Cargo, Starship, fd,\nNushell, mise, Jujutsu, uutils/coreutils and even as the basis for a Temporal\nimplementation in AWS LLRT. It is time to call it 1.0.\n\nUnless some significant defect is found in Jiff’s API, my plan is to commit\nto Jiff 1.0 indefinitely. This is important because the intent is for Jiff\nto be an ecosystem building block that appears in the public API of other\nlibraries. This makes Jiff an attractive *public* dependency, which means\nsemver incompatible releases are likely to cause significant pain in the\necosystem. They will not be made lightly.\n\nTo see a list of breaking changes between Jiff 0.2 and Jiff 1.0, please\nconsult the [CHANGELOG](https://github.com/BurntSushi/jiff/blob/master/CHANGELOG.md#100-2026-11-15).\n\n## Introduction\n\nIn programming, a datetime library’s core functionality rests at the\nintersection of a computer system’s concept of time and a human’s concept of\ntime. The prevailing notion of system time is [Unix time](https://en.wikipedia.org/wiki/Unix_time). A human’s concept\nof time is far more complex, but the most popular such model is the [Gregorian\ncalendar](https://en.wikipedia.org/wiki/Gregorian_calendar) coupled with either a 12-hour or 24-hour clock. At the core of every\ndatetime library rests some routine for converting between these concepts.\n\nA datetime library typically provides much more than this. Indeed, datetime\nhandling has [historically been very difficult](https://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time). My own belief is\nthat the difficulty comes from *poor modeling of the domain*. Instead of\nencapsulating the complexity inside a reusable bundle of code, many datetime\nlibraries pass some or all of the complexity on to its users. Jiff instead\ntries hard to encapsulate the complexity and make it difficult for users to\ndo something wrong. ([Jiff is not the first to do this!](#inspiration))\n\nIn this section of the blog, we’ll do some very basic introductions.\n\n### Follow Along\n\nTo follow along with the examples in this blog, create a new Cargo project\nwith dependencies on `jiff` and `anyhow`:\n\n```\nmkdir jiff-playground\ncd jiff-playground\ncargo init --bin\ncargo add jiff anyhow\n$EDITOR src/main.rs\n```\n\nMost examples are a complete self-contained Rust program. Just copy the code\nand replace whatever is in `src/main.rs`. Then run the program:\n\n```\ncargo run\n```\n\n### Terms\n\nI am loath to present a dictionary. However, the datetime domain is littered\nwith confusable terms, so I think it’s important to orient ourselves on a\nshared vocabulary. I’ve kept this section as small as possible. (Some terms,\nlike “time zone,” are omitted here because they are best defined through\nexploration in the sections that follow.)\n\n- [Civil time](https://en.wikipedia.org/wiki/Civil_time): The time you see on your clock. And in general, the time that\n  the humans in your approximate geographic vicinity also see. That is, civil\n  time is a human coordinated agreement for communicating time in a particular\n  geographic region. Civil time is also known as: local time, plain time, naive\n  time, clock time and others.\n- [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time): An abbreviation for *Coordinated Universal Time*; it is a time\n  standard that serves as the basis for civil time around the world. It was\n  originally intended to roughly correspond to [mean solar time](https://en.wikipedia.org/wiki/Solar_time#Mean_solar_time).\n- [TAI](https://en.wikipedia.org/wiki/International_Atomic_Time): An abbreviation for *International Atomic Time*; it is a time standard\n  as measured by atomic clocks. It isn’t directly connected to mean solar time.\n- [Leap second](https://en.wikipedia.org/wiki/Leap_second): An adjustment to TAI to bring it closer to mean solar time\n  and thus forming the basis of UTC.\n- [Unix time](https://en.wikipedia.org/wiki/Unix_time): UTC, but ignoring leap seconds.\n\nTAI and leap seconds won’t be a feature of this blog, but they are listed here\nin order to convey the difference between Unix time and UTC.\n\n### The DateTime Onion\n\nAs a way to transition into some of the core types of Jiff, I’ve come to think\nof its datetime types like an onion. In reverse order, we can build up\nits layers all the way to a `ZonedDateTime`. So let’s start with more terms,\nbut this time, they are also types in Jiff:\n\n- A [`civil::Date`](https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html) is a plain Gregorian date, unattached to any specific\n  location.\n- A [`civil::Time`](https://docs.rs/jiff/1.*/jiff/civil/struct.Time.html) is a plain time on a clock, to nanosecond precision,\n  unattached to any specific location.\n- A [`civil::DateTime`](https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html) combines a `civil::Date` and a `civil::Time` to provide\n  both a Gregorian date and a time on a clock. It is also unattached to any\n  specific location.\n- A [`Timestamp`](https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html) is an unambiguous specific instant in time regardless of\n  geographic location, represented as the number of nanoseconds since the Unix\n  epoch.\n- A [`TimeZone`](https://docs.rs/jiff/1.*/jiff/tz/struct.TimeZone.html) is a set of rules for mapping a `Timestamp` to a\n  `civil::DateTime`, and vice versa, in a specific geographic region.\n- A [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html) combines a `Timestamp`, a `civil::DateTime` and a\n  `TimeZone` to represent a specific instant in time in a specific geographic\n  location.\n\nTo make this a bit more concrete, we can see what this looks like in code.\nSince a time zone can map from a civil datetime to an instant in time, one way\nto create a zoned datetime requires only a civil datetime and a time zone:\n\n```\nuse jiff::civil;\n\nfn main() -> anyhow::Result<()> {\n    let date = civil::date(2026, 11, 1);\n    let time = civil::time(17, 30, 0, 0);\n    let datetime = date.to_datetime(time);\n    // zdt is an initialism for \"ZonedDateTime\"\n    let zdt = datetime.in_tz(\"America/New_York\")?;\n\n    assert_eq!(zdt.timestamp().as_second(), 1793572200);\n\n    Ok(())\n}\n```\n\nAnother way to create a zoned datetime requires only a timestamp and a time\nzone. This is because time zones can *also* map a timestamp to a particular\ncivil datetime:\n\n```\nuse jiff::{civil, Timestamp};\n\nfn main() -> anyhow::Result<()> {\n    let timestamp = Timestamp::from_second(1793572200)?;\n    let zdt = timestamp.in_tz(\"America/New_York\")?;\n\n    // This is a shortcut for creating a civil datetime.\n    // The previous example spells it out a bit more verbosely\n    // for clarity.\n    let expected = civil::date(2026, 11, 1).at(17, 30, 0, 0);\n    assert_eq!(zdt.datetime(), expected);\n\n    Ok(())\n}\n```\n\nNotice how we get the equivalent zoned datetime in both cases, but we come at\nit from different directions. In the first case, we start with a time that we\nmight see on our clocks and calendars. In the second case, we start with a\nparticular instant in time that we might get from a database or file system or\nsome other system call.\n\n### Defining a time zone\n\nThere is one piece missing from the zoned datetime onion examples: the\ntime zone *offset*. An offset represents the amount of time one must\nadjust UTC time in order to get civil time. For example, consider the time\n`2026-11-01T22:30:00` in UTC. In order to get the civil datetime for someone\nliving in New York, one would subtract 5 hours:\n\n```\n2026-11-01T22:30:00 - 05:00 = 2026-11-01T17:30:00\n```\n\nIndeed, every zoned datetime has an offset associated with it:\n\n```\nuse jiff::{civil, tz, Timestamp};\n\nfn main() -> anyhow::Result<()> {\n    let timestamp = Timestamp::from_second(1793572200)?;\n    let zdt = timestamp.in_tz(\"America/New_York\")?;\n    assert_eq!(zdt.offset().seconds(), -(5 * 60 * 60));\n\n    let dt = civil::date(2026, 11, 1).at(17, 30, 0, 0);\n    let zdt = dt.in_tz(\"America/New_York\")?;\n    assert_eq!(zdt.offset(), tz::offset(-5));\n\n    Ok(())\n}\n```\n\n> **NOTE**: The `America/New_York` string you see in the above example is an\n> IANA Time Zone Database Identifier. The [IANA Time Zone Database](https://www.iana.org/time-zones) is a\n> collection of time zone definitions that can be referenced by a short\n> identifier string. Examples: `Australia/Sydney`, `Asia/Tokyo`,\n> `Europe/Berlin`.\n\nWhen a civil datetime is combined with an offset, then what you get is always\nan instant in time.\n\nWith the concept of an offset introduced, we can now give a more precise\ndefinition of a time zone. A time zone **is a geographic region in which civil\nclocks agree** and which provides the following:\n\n- A mapping from an instant in time to an offset from UTC. The offset applied\n  to an instant yields a civil datetime.\n- A mapping from a civil datetime to a possibly ambiguous offset from UTC.\n  The offset applied to a civil datetime yields an instant.\n\nBoth mappings have been demonstrated in prior examples, but the mapping\nfrom civil datetime to an offset seems to be rather complicated due to some\npotential ambiguity. When does that ambiguity arise? An ambiguous offset occurs\nwhen the civil datetime either doesn’t correspond to a valid clock time in this\ntime zone (e.g., when clocks are moved ahead for [daylight saving time](https://en.wikipedia.org/wiki/Daylight_saving_time)) or\nwhere there could be multiple valid clock times (e.g., when clocks are moved\nbackward for [daylight saving time](https://en.wikipedia.org/wiki/Daylight_saving_time)).\n\nLet’s look at some examples. In this first example, we’ll take a look at times\naround the daylight saving time transition from summer time to standard time\nin New York. In New York, the clocks were “set back” by an hour at exactly 2AM.\nThis caused the 1AM hour to repeat itself.\n\n```\nuse jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -> anyhow::Result<()> {\n    let tz = TimeZone::get(\"America/New_York\")?;\n\n    // During summer time, New York's offset from UTC is -04:00.\n    let zdt = date(2026, 11, 1).at(0, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // During standard time, New York's offset from UTC is -05:00.\n    let zdt = date(2026, 11, 1).at(2, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // But what does 01:30AM mean? Is it the first repetition or the second?\n    // Jiff automatically chooses the first by default.\n    let zdt = date(2026, 11, 1).at(1, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    Ok(())\n}\n```\n\nThe above example shows how Jiff resolves the ambiguity when a “fold” occurs,\nor when there is a time zone transition that moves the civil time backwards.\nBut we can actually dig down into lower level APIs to change how that ambiguity\nis resolved. By default, Jiff uses a “compatible” strategy that always selects\nthe first repetition of a time in a fold. But other strategies can be selected\nby using APIs on a `TimeZone` directly:\n\n```\nuse jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -> anyhow::Result<()> {\n    let tz = TimeZone::get(\"America/New_York\")?;\n    let dt = date(2026, 11, 1).at(1, 30, 0, 0);\n\n    // The same that Jiff uses by default.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).compatible()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the earlier datetime.\n    // For a fold, this is the same as the\n    // default \"compatible\" strategy.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).earlier()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the later datetime.\n    // For a fold, this selects the second\n    // occurrence of the 1AM hour!\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).later()?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // Always returns an error when there\n    // is any ambiguity.\n    assert_eq!(\n        tz.to_ambiguous_zoned_datetime(dt)\n            .unambiguous()\n            .unwrap_err()\n            .to_string(),\n        \"error converting datetime to instant in time zone America/New_York: \\\n         datetime is ambiguous \\\n         since it falls into a fold between offsets -04 and -05\",\n    );\n\n    Ok(())\n}\n```\n\nThe same idea applies to *gaps*, or time zone transitions where there’s some\ncivil time that gets skipped on civil clocks. For example, on March 8, 2026\nat 2AM, civil time skipped ahead to 3AM:\n\n```\nuse jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -> anyhow::Result<()> {\n    let tz = TimeZone::get(\"America/New_York\")?;\n    let dt = date(2026, 3, 8).at(2, 30, 0, 0);\n\n    // The \"compatible\" strategy selects\n    // the later time in the case of gaps.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).compatible()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the earlier datetime.\n    // For a gap, this selects the hour\n    // before the gap.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).earlier()?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // Always selects the later datetime.\n    // For a gap, this is the same as the\n    // default \"compatible\" strategy.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).later()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always returns an error when there\n    // is any ambiguity.\n    assert_eq!(\n        tz.to_ambiguous_zoned_datetime(dt)\n            .unambiguous()\n            .unwrap_err()\n            .to_string(),\n        \"error converting datetime to instant in time zone America/New_York: \\\n         datetime is ambiguous \\\n         since it falls into a gap between offsets -05 and -04\",\n    );\n\n    Ok(())\n}\n```\n\n### Durations\n\nThere are two remaining core types, both representing some notion of a\nduration:\n\n- [`Span`](https://docs.rs/jiff/1.*/jiff/struct.Span.html) is a powerful hybrid duration that combines both calendar units\n  (years, months, weeks, days) and physical time units (hours, minutes, seconds,\n  milliseconds, microseconds, nanoseconds). It is a beefy type that preserves the\n  individual unit values.\n- [`SignedDuration`](https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html) is a signed version of [`std::time::Duration`](https://doc.rust-lang.org/nightly/std/time/struct.Duration.html) and always\n  corresponds to a 96-bit integer number of nanoseconds. It can only represent\n  physical time (units of hours or smaller) and not calendar units (units of days\n  or greater).\n\nA `Span` is the preferred duration type to use whenever possible. Here’s a\nsimple example that shows how to get the number of days between two civil\ndates:\n\n```\nuse jiff::civil::date;\n\nfn main() -> anyhow::Result<()> {\n    let d1 = date(2024, 2, 1);\n    let d2 = date(2024, 3, 1);\n    let span = d2 - d1;\n    assert_eq!(span.get_days(), 29);\n    // or, equivalently:\n    assert_eq!(d1.until(d2)?.get_days(), 29);\n\n    // Flipping d1 and d2 gives the same result,\n    // but negative.\n    let span = d1 - d2;\n    assert_eq!(span.get_days(), -29);\n\n    Ok(())\n}\n```\n\nDurations can also be added to dates:\n\n```\nuse jiff::{civil::date, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let d1 = date(2024, 2, 1);\n    // This convenient syntax comes from the\n    // `ToSpan` extension trait.\n    let span = 29.days();\n    assert_eq!(d1.checked_add(span)?, date(2024, 3, 1));\n\n    Ok(())\n}\n```\n\nGenerally speaking, whenever there is an operation involving a `Span`, there is\nan equivalent operation available with `SignedDuration`:\n\n```\nuse jiff::{civil::date, SignedDuration};\n\nfn main() -> anyhow::Result<()> {\n    let dt1 = date(2024, 2, 1).at(17, 30, 0, 0);\n    let sdur = SignedDuration::from_mins(90);\n    assert_eq!(dt1.checked_add(sdur)?, date(2024, 2, 1).at(19, 0, 0, 0));\n\n    Ok(())\n}\n```\n\nNotice that in the above example, we actually switched from using a\n`civil::Date` to a `civil::DateTime`. This was done to show how physical time\nunits can be added. But note that the same can be accomplished with a `Span`,\nbecause it combines all units:\n\n```\nuse jiff::{civil::date, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let dt1 = date(2024, 2, 1).at(17, 30, 0, 0);\n    let span = 1.hour().minutes(30);\n    assert_eq!(dt1.checked_add(span)?, date(2024, 2, 1).at(19, 0, 0, 0));\n\n    // Calendar and physical time units can\n    // be combined!\n    let span = 1.month().hours(1).minutes(30);\n    assert_eq!(dt1.checked_add(span)?, date(2024, 3, 1).at(19, 0, 0, 0));\n\n    Ok(())\n}\n```\n\nIn brief, use a `Span` when you can. But when it’s too bulky or too slow, use\na `SignedDuration`. One of the key benefits of a `Span` is that since it\nrepresents each unit value distinctly, one can preserve the original meaning\nof a duration. For example, it’s common to represent the runtime of films in\nminutes, even when the duration exceeds one hour. Indeed, a span of 2 hours\nis a distinct span from a span of 120 minutes:\n\n```\nuse jiff::ToSpan;\n\nfn main() -> anyhow::Result<()> {\n    let span1 = 2.hours();\n    let span2 = 120.minutes();\n    // This means the spans are distinct values\n    // in memory.\n    assert_ne!(span1.fieldwise(), span2.fieldwise());\n\n    Ok(())\n}\n```\n\nThe [`Span::fieldwise`](https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.fieldwise) routine converts a `Span` into a value whose units can\nbe compared in a field-by-field fashion. To compare spans based on the actual\nphysical duration they represent, use [`Span::compare`](https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.compare):\n\n```\nlet span1 = 2.hours();\nlet span2 = 120.minutes();\nassert!(span1.compare(span2)?.is_eq());\n```\n\nThis was a very brief introduction to durations in Jiff. They are *a lot* more\npowerful than what is shown here. You might even try playing with the examples\nabove to explore its nooks and crannies. We’ll cover their API in more detail\nin a later section.\n\n### When should I use Jiff?\n\nJiff isn’t always the right thing to use. Sometimes you can get by with\nsomething simpler.\n\nFirst and foremost, if you’re *measuring* the time something takes in a\nprogram, you should almost certainly be using monotonic time. This is\navailable via [`std::time::Instant`](https://doc.rust-lang.org/nightly/std/time/struct.Instant.html):\n\n```\nuse std::time::{Duration, Instant};\n\nfn main() -> anyhow::Result<()> {\n    let start = Instant::now();\n\n    // do some serious work\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = Instant::now().duration_since(start);\n    println!(\"{elapsed:?}\");\n\n    Ok(())\n}\n```\n\nIf you do need to compute elapsed time using your system clock, then Jiff\nis very convenient for that:\n\n```\nuse std::time::Duration;\n\nuse jiff::Timestamp;\n\nfn main() -> anyhow::Result<()> {\n    // assume `start` came from somewhere\n    // over a network\n    let start = Timestamp::now();\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = Timestamp::now().duration_since(start);\n    println!(\"{elapsed}\");\n\n    Ok(())\n}\n```\n\nBut you don’t actually need Jiff for this. A [`std::time::SystemTime`](https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html) will\nwork perfectly fine:\n\n```\nuse std::time::{Duration, SystemTime};\n\nfn main() -> anyhow::Result<()> {\n    // assume `start` came from somewhere\n    // over a network\n    let start = SystemTime::now();\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = SystemTime::now().duration_since(start)?;\n    println!(\"{elapsed:?}\");\n\n    Ok(())\n}\n```\n\nWhere Jiff starts to become useful is when you need something beyond just an\ninteger number of seconds since the Unix epoch. For example, some very hairy\nmath is required in order to convert a `SystemTime` into an RFC 3339 timestamp\nlike `2026-11-14T21:34:00Z`.\n\nAs long as you can live in UTC completely, don’t care about local time and can\nwork with Unix timestamps only, then the Rust standard library won’t steer you\nwrong.\n\n## Parsing and Formatting\n\nConversion to and from strings is a major part of Jiff. Jiff’s focus is\nprimarily on interoperability via the following:\n\n- [RFC 3339](https://www.rfc-editor.org/info/rfc3339/) specifies a format for fixed offset instants in time, in terms of\n  a human readable civil datetime. For example, `2026-11-12T15:36:00-05:00`. This\n  is the serialization format used by [`Timestamp`](https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html).\n- [RFC 9557](https://www.rfc-editor.org/info/rfc9557/) extends and updates RFC 3339 to add time zone information.\n  For example, `2026-11-12T15:36:00-05:00[America/New_York]`. This is the\n  serialization format used by [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html).\n- [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) covers mostly everything else, including durations and\n  civil datetimes. For example, `P5Y3MT20H` is an ISO 8601 duration and\n  `2026-11-12T15:30:00` is an ISO 8601 civil datetime whose corresponding instant\n  in time is unknown.\n\nWhat Jiff actually implements is the\n[Temporal RFC 9557 / ISO 8601](https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar) grammar for flexible parsing of datetimes from\nstrings. For most use cases, it suffices to think in terms of RFC 3339,\nRFC 9557 or ISO 8601. But Jiff does support parsing strings that aren’t valid\nin any of those three specifications. For example, `2026-11-12[America/New_York]`\nparses as if it was `2026-11-12T00:00:00[America/New_York]`.\n\nIn this section, we’ll take a tour of how Jiff does datetime formatting and\nprinting.\n\n### `FromStr` and `Display`\n\nEvery datetime and duration type in Jiff implements the standard library\n[`FromStr`](https://doc.rust-lang.org/nightly/std/str/trait.FromStr.html) and [`Display`](https://doc.rust-lang.org/nightly/std/fmt/trait.Display.html) traits. This means that it’s natural to parse\ndatetimes:\n\n```\nlet ts: Timestamp = \"2026-10-31T05:15:00Z\".parse()?;\n```\n\nand print them:\n\n```\nprintln!(\"{ts}\");\n```\n\nParsing is flexible, so even if there are components missing, parsing still\nsucceeds. For example, without minutes or seconds, those components default to\nzero:\n\n```\nlet dt: civil::DateTime = \"2026-10-31T05\".parse()?;\nassert_eq!(dt.to_string(), \"2026-10-31T05:00:00\");\n```\n\nAnother example of flexible parsing is that if a string *contains* another date\ntype, then one can parse that. For example, one can parse a date out of an\nISO 8601 datetime:\n\n```\nlet d: civil::Date = \"2026-10-31T05:30\".parse()?;\nassert_eq!(d.to_string(), \"2026-10-31\");\n```\n\nA [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html) always uses [RFC 9557](https://www.rfc-editor.org/info/rfc9557/) syntax, which includes the IANA time\nzone identifier:\n\n```\nlet zdt: ZonedDateTime = \"2026-10-31T05:30[Australia/Sydney]\".parse()?;\n// While the string we parsed didn't have any offset,\n// one was automatically added by consulting the time\n// zone definition for the civil datetime provided.\nassert_eq!(zdt.to_string(), \"2026-10-31T05:30:00+11:00[Australia/Sydney]\");\n```\n\nIf you want to print a zoned datetime using only [RFC 3339](https://www.rfc-editor.org/info/rfc3339/) syntax, then you\ncan do so by formatting the timestamp directly with the zoned datetime’s\noffset:\n\n```\nlet zdt: ZonedDateTime = \"2026-10-31T05:30[Australia/Sydney]\".parse()?;\nassert_eq!(\n    zdt.timestamp().display_with_offset(zdt.offset()).to_string(),\n    \"2026-10-31T05:30:00+11:00\",\n);\n```\n\nThe [`Span`](https://docs.rs/jiff/1.*/jiff/struct.Span.html) and [`SignedDuration`](https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html) types also support the `FromStr` and\n`Display` traits via the ISO 8601 duration format. For example:\n\n```\nuse jiff::{SignedDuration, Span};\n\nfn main() -> anyhow::Result<()> {\n    let duration = \"PT5H30M\";\n\n    let span: Span = duration.parse()?;\n    assert_eq!(span.to_string(), \"PT5H30M\");\n\n    let sdur: SignedDuration = duration.parse()?;\n    assert_eq!(sdur.to_string(), \"PT5H30M\");\n\n    Ok(())\n}\n```\n\nSince a `Span` is a hybrid duration that also supports calendar units, it can\nparse durations with calendar units and physical time units. A `SignedDuration`\ncan only parse durations with physical time units:\n\n```\nuse jiff::{SignedDuration, Span};\n\nfn main() -> anyhow::Result<()> {\n    let duration = \"P11Y2M28DT5H30M\";\n\n    let span: Span = duration.parse()?;\n    assert_eq!(span.to_string(), \"P11Y2M28DT5H30M\");\n\n    let err = duration.parse::<SignedDuration>().unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        \"parsing ISO 8601 duration in this context requires \\\n         that the duration contain a time component \\\n         and no components of days or greater\",\n    );\n\n    Ok(())\n}\n```\n\nThe ISO 8601 duration format does, however, have some shortcomings that we’ll\ndiscuss in the next section.\n\n### The “friendly” Duration Format\n\nBecause ISO 8601 duration strings enjoy broad support, it is the default in\nJiff for both `Span` and `SignedDuration`. However, it has two important\nshortcomings:\n\n1. It is difficult to read. For example, in `P11Y2M28DT5H30M`, the lack of\n   whitespace makes the unit values and the unit labels all run together.\n2. An ISO 8601 duration cannot unambiguously represent all possible `Span`\n   values.\n\nThe second shortcoming is best seen with an example. Consider a `Span` that is\n2000 milliseconds. If you convert this to an ISO 8601 duration string and then\nparse it back, you end up with 2 seconds instead:\n\n```\nuse jiff::{Span, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let original = 2000.milliseconds();\n    assert_eq!(original.to_string(), \"PT2S\");\n\n    let got: Span = \"PT2S\".parse()?;\n\n    // The spans have different unit values!\n    assert_eq!(original.get_seconds(), 0);\n    assert_eq!(original.get_milliseconds(), 2000);\n    assert_eq!(got.get_seconds(), 2);\n    assert_eq!(got.get_milliseconds(), 0);\n\n    Ok(())\n}\n```\n\nThis might not be desirable for cases where you want a span’s string format\nto faithfully represent all possible distinct values of a span.\n\nFor these two reasons, Jiff comes with its own bespoke “friendly” duration\nformat. The friendly format is non-lossy *and* is meant to be easier to read\nfor English speakers than the ISO 8601 duration format. Here are some examples\nthat are all valid friendly durations:\n\n```\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\nParsing a friendly duration is as easy as parsing an ISO 8601 duration: the\n`FromStr` implementations on both `Span` and `SignedDuration` support ISO 8601\ndurations and friendly durations simultaneously:\n\n```\nlet span: Span = \"6y 10mo 3d 23h\".parse()?;\n// Recall that `Span::fieldwise` permits\n// equality comparisons on `Span` in a\n// unit-by-unit fashion.\nassert_eq!(span.fieldwise(), 6.years().months(10).days(3).hours(23));\n```\n\nPrinting a friendly duration does require a bit more effort, since it isn’t\nthe default. Instead of `Span::to_string()`, one can use the “alternative”\nsyntax via Rust’s formatting machinery:\n\n```\nlet span = 2000.milliseconds();\n// This also demonstrates that our unit\n// values are preserved.\nassert_eq!(format!(\"{span:#}\"), \"2000ms\");\n```\n\nOne can also use a lower level friendly printer to customize its output.\nFor example, here’s how to write a span in the friendly format to an existing\n`String` using more spacing, longer unit labels and commas separating each\nunit:\n\n```\nuse jiff::{fmt::friendly, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    static PRINTER: friendly::SpanPrinter = friendly::SpanPrinter::new()\n        .comma_after_designator(true)\n        .spacing(friendly::Spacing::BetweenUnitsAndDesignators)\n        .designator(friendly::Designator::Verbose);\n\n    let span = 6.years().months(10).days(3).hours(23);\n    let mut buf = String::new();\n    PRINTER.print_span(&span, &mut buf)?;\n    assert_eq!(buf, \"6 years, 10 months, 3 days, 23 hours\");\n\n    Ok(())\n}\n```\n\nSee the [`jiff::fmt::friendly`](https://docs.rs/jiff/1.*/jiff/fmt/friendly/index.html) module for a lot more detail, including a\ngrammar that precisely specifies the format supported.\n\n### `strptime` and `strftime`\n\nThe [POSIX `strptime`](https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html) and [POSIX `strftime`](https://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html) routines are far from the ideal\nway to format and parse datetimes, but they are ubiquitous and most programmers\nare familiar with them. Because of their ubiquity, and because of the utility\nof being able to format and parse bespoke datetime formats, Jiff provides\nimplementations of these routines that are mostly POSIX compatible.\n\nEvery datetime type in Jiff comes with `strptime` and `strftime` routines.\nFor example, to parse a civil date in the US `month/day/year` format:\n\n```\nlet date = civil::Date::strptime(\"%m/%d/%Y\", \"11/13/2026\")?;\nassert_eq!(date.to_string(), \"2026-11-13\");\n```\n\nOr to format a zoned datetime in a convenient to read representation for\nEnglish speakers:\n\n```\nlet zdt = civil::date(2026, 11, 13).at(17, 30, 0, 0).in_tz(\"Australia/Sydney\")?;\nassert_eq!(\n    zdt.strftime(\"%a, %b %d, %Y %H:%M %Z\").to_string(),\n    \"Fri, Nov 13, 2026 17:30 AEDT\",\n);\n```\n\nCallers can also use lower level APIs from [`jiff::fmt::strtime`](https://docs.rs/jiff/1.*/jiff/fmt/strtime/index.html) to get access\nto each parsed component individually:\n\n```\nuse jiff::{civil, fmt::strtime::BrokenDownTime};\n\nfn main() -> anyhow::Result<()> {\n    let tm = BrokenDownTime::parse(\n        \"%a, %b %d, %Y %H:%M\",\n        \"Fri, Nov 13, 2026 17:30\",\n    )?;\n    assert_eq!(tm.weekday(), Some(civil::Weekday::Friday));\n    assert_eq!(tm.month(), Some(11));\n    assert_eq!(tm.day(), Some(13));\n    assert_eq!(tm.year(), Some(2026));\n    assert_eq!(tm.hour(), Some(17));\n    assert_eq!(tm.minute(), Some(30));\n    assert_eq!(tm.second(), None);\n\n    Ok(())\n}\n```\n\n### The `jiff::fmt` module\n\nWhile the above tour should cover most use cases, there are sometimes reasons\nfor exerting more control over parsing or formatting. Or for supporting\nalternate formats like RFC 2822. The [`jiff::fmt`](https://docs.rs/jiff/1.*/jiff/fmt/index.html) module is meant to cover\nthese use cases at the cost of more complex APIs. For example, consider parsing\nan [RFC 2822](https://www.rfc-editor.org/info/rfc2822/) datetime string from a `&[u8]` (which lets callers avoid a UTF-8\nvalidation check):\n\n```\nuse jiff::fmt::rfc2822;\n\nfn main() -> anyhow::Result<()> {\n    static PARSER: rfc2822::DateTimeParser = rfc2822::DateTimeParser::new();\n\n    let data = b\"Sat, 13 Jul 2024 15:09:59 -0400\";\n    let ts = PARSER.parse_timestamp(data)?;\n    assert_eq!(ts.to_string(), \"2024-07-13T19:09:59Z\");\n    Ok(())\n}\n```\n\nAnother example shows how to change the default disambiguation strategy when\nthe provided civil datetime is ambiguous. For example, Sydney, Australia moved\nthe clocks backwards at `2026-04-05T03:00:00` local time. That is, they went\nfrom UTC offset `+11` to UTC offset `+10`. So what happens if we try to parse\na time on the clock that is repeated as a result?\n\n```\nuse jiff::ZonedDateTime;\n\nfn main() -> anyhow::Result<()> {\n    let zdt: ZonedDateTime = \"2026-04-05T02:30[Australia/Sydney]\".parse()?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+11:00[Australia/Sydney]\");\n    Ok(())\n}\n```\n\nHere, the first occurrence of `02:30` is selected, just before Sydney leaves\ndaylight saving time. Now, the data itself can actually select the desired\noffset:\n\n```\nuse jiff::ZonedDateTime;\n\nfn main() -> anyhow::Result<()> {\n    let zdt: ZonedDateTime =\n        \"2026-04-05T02:30+11:00[Australia/Sydney]\".parse()?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+11:00[Australia/Sydney]\");\n\n    let zdt: ZonedDateTime =\n        \"2026-04-05T02:30+10:00[Australia/Sydney]\".parse()?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+10:00[Australia/Sydney]\");\n\n    Ok(())\n}\n```\n\nBut this happens because *there is no ambiguity* in the data. Since the offset\nis supplied, the exact instant in time is known. Going back to\n`2026-04-05T02:30[Australia/Sydney]`, which *is* ambiguous because it could\nrefer to two different instants in time, how do we modify the strategy for\nresolving that ambiguity? We can’t using the standard library `FromStr` trait,\nso we instead have to construct our own parser manually, just like we did for\n[RFC 2822](https://www.rfc-editor.org/info/rfc2822/) parsing above. This example shows how to do that and all of the\ndifferent disambiguation options. Remember, UTC offset +11:00 corresponds to\nthe first occurrence of `2026-04-05T02:30` on the clocks of folks in Sydney\nwhile UTC offset +10:00 corresponds to the second occurrence.\n\n```\nuse jiff::{fmt::temporal::DateTimeParser, tz::Disambiguation};\n\nfn main() -> anyhow::Result<()> {\n    let string = \"2026-04-05T02:30[Australia/Sydney]\";\n\n    // \"compatible\" is the default strategy, which selects\n    // the earlier time in a fold (usually moving from daylight\n    // saving time to standard time) and the later time in a\n    // gap (usually moving from standard time to daylight\n    // saving time).\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Compatible);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+11:00[Australia/Sydney]\");\n\n    // \"earlier\" always selects the first occurrence\n    // in a fold, or the time before a gap.\n    // So this is the same as compatible in this case,\n    // since our civil time is in a fold.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Earlier);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+11:00[Australia/Sydney]\");\n\n    // \"later\" always selects the second occurrence\n    // in a fold, or the time after a gap.\n    // So this is different from \"compatible\" for a\n    // fold. Notice that the UTC +10:00 offset is\n    // chosen.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Later);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), \"2026-04-05T02:30:00+10:00[Australia/Sydney]\");\n\n    // \"reject\" means that if the instant is ambiguous,\n    // then an error is returned.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Reject);\n    let err = parser.parse_zoned_datetime(string).unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        \"error converting datetime to instant \\\n         in time zone Australia/Sydney: \\\n         datetime is ambiguous since it falls \\\n         into a fold between offsets +11 and +10\",\n    );\n\n    Ok(())\n}\n```\n\nThe [`jiff::fmt`](https://docs.rs/jiff/1.*/jiff/fmt/index.html) module contains lots of other goodies that we won’t cover\nhere, including, but not limited to:\n\n- The ability to format directly into an existing allocation.\n- Parsing a datetime into its individual components.\n- Helpers for [`serde`](https://serde.rs/) integration.\n\n### Locale Sensitive Formatting via ICU4X Integration\n\nNo section on datetime formatting would be complete without addressing locales.\nIn this context, a locale is a set of user preferences used for formatting\ndatetimes. This is useful when you want to present a datetime to an end user\nthat doesn’t expect standard formats from [RFC 3339](https://www.rfc-editor.org/info/rfc3339/), [RFC 9557](https://www.rfc-editor.org/info/rfc9557/) or [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).\n\nJiff itself does not provide any facilities for dealing with locales. Instead,\nusers can opt into this support via the [ICU4X](https://docs.rs/icu) project. To make conversions\nbetween Jiff and ICU4X, the [`jiff-icu`](https://docs.rs/jiff-icu) integration crate can be used.\n\nHere’s an example showing how to format a zoned datetime in the `fr-LA` locale:\n(You’ll need to run `cargo add icu jiff-icu` to your project for this to work.)\n\n```\nuse icu::{\n    calendar::Iso,\n    datetime::{fieldsets, DateTimeFormatter},\n    locale::locale,\n    time::{zone::models::AtTime, TimeZoneInfo},\n};\nuse jiff::ZonedDateTime;\nuse jiff_icu::ConvertFrom as _;\n\nfn main() -> anyhow::Result<()> {\n    // Firstly, do a conversion from Jiff's zoned datetime to ICU's.\n    let jiff_zdt: ZonedDateTime =\n        \"2024-09-10T23:37:20-04[America/New_York]\".parse()?;\n    let icu_zdt =\n        icu::time::ZonedDateTime::<Iso, TimeZoneInfo<AtTime>>::convert_from(\n            &jiff_zdt,\n        );\n\n    // Second, create a datetime formatter for the fr-LA locale:\n    let formatter = DateTimeFormatter::try_new(\n        locale!(\"fr-LA\").into(),\n        fieldsets::YMDET::medium().with_zone(fieldsets::zone::SpecificLong),\n    )?;\n\n    // Thirdly, format the zoned datetime.\n    assert_eq!(\n        formatter.format(&icu_zdt).to_string(),\n        \"mar. 10 sept. 2024, 23:37:20 heure d’été de l’Est nord-américain\",\n    );\n\n    Ok(())\n}\n```\n\nThe ICU4X API has a lot of options for customizing datetime formatting.\nExploring it further is outside the scope of this blog.\n\n## Date Manipulation\n\nJiff provides many methods on its datetime types to make using them as\ncomfortable and error-free as possible.\n\n### Date Basics\n\nEvery datetime type provides a `new` constructor that lets callers build it\nfrom its constituent parts. In most cases, this constructor is fallible. For\nexample:\n\n```\nuse jiff::civil::Date;\n\nfn main() -> anyhow::Result<()> {\n    let d = Date::new(2024, 2, 29)?;\n    // All datetime types have convenient\n    // accessors for each of their components.\n    assert_eq!(d.year(), 2024);\n    assert_eq!(d.month(), 2);\n    assert_eq!(d.day(), 29);\n\n    let err = Date::new(2025, 2, 29).unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        \"parameter 'day' for `2025-02` is invalid, must be in range `1..=28`\",\n    );\n\n    Ok(())\n}\n```\n\nBecause creating dates is so common, there is a shorthand for doing so when\nyou know the inputs are valid:\n\n```\nlet d = const { civil::date(2024, 2, 29) };\nassert_eq!(d.year(), 2024);\nassert_eq!(d.month(), 2);\nassert_eq!(d.day(), 29);\n```\n\nThat is, `civil::date` is a const function that will panic if its inputs are\ninvalid. It should only be used with inputs that are known to be valid.\nIt would, for example, be inappropriate to use this with user provided values.\nBecause of the `const` block above, if you try to provide invalid values,\nyou’ll get a compiler error.\n\nFor datetime types that represent an instant in time (i.e., `ZonedDateTime` and\n`Timestamp`), there is also a `now()` constructor for getting the current time:\n\n```\nuse jiff::{Timestamp, ZonedDateTime};\n\nfn main() -> anyhow::Result<()> {\n    let now = Timestamp::now();\n    println!(\"{now}\");\n    // Example output: 2026-11-15T14:17:21.80099287Z\n\n    // This will automatically fetch your system's configured time zone.\n    let now = ZonedDateTime::now();\n    println!(\"{now}\");\n    // Example output: 2026-11-15T09:17:21.80102125-05:00[America/New_York]\n\n    Ok(())\n}\n```\n\nIn addition to constructors, new date values can be constructed from old\ndate values using the `Date::with` API:\n\n```\nlet d1 = const { civil::date(2024, 2, 29) };\n// This API doesn't break just because 31\n// is supplied before a month that has 31\n// days. Any order is fine! This is because\n// errors are deferred until `build()` is\n// called.\nlet d2 = d1.with().day(31).month(3).build()?;\nassert_eq!(d2.to_string(), \"2024-03-31\");\n```\n\nOnce you have a date, there are oodles of APIs available:\n\n```\nlet d = civil::date(2025, 7, 10);\nassert_eq!(d.weekday(), civil::Weekday::Thursday);\nassert_eq!(d.first_of_year(), civil::date(2025, 1, 1));\nassert_eq!(d.last_of_year(), civil::date(2025, 12, 31));\nassert_eq!(d.first_of_month(), civil::date(2025, 7, 1));\nassert_eq!(d.last_of_month(), civil::date(2025, 7, 31));\nassert_eq!(d.yesterday()?, civil::date(2025, 7, 9));\nassert_eq!(d.tomorrow()?, civil::date(2025, 7, 11));\n```\n\nMoreover, because of the [datetime onion](#the-datetime-onion), all of these\nAPIs are also available on [`civil::DateTime`](https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html) and [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html):\n\n```\nlet create_zdt =\n    |date: civil::Date| -> Result<ZonedDateTime, jiff::Error> {\n        date.at(0, 0, 0, 0).in_tz(\"America/New_York\")\n    };\n\nlet zdt = create_zdt(civil::date(2025, 7, 10))?;\nassert_eq!(zdt.weekday(), civil::Weekday::Thursday);\nassert_eq!(zdt.first_of_year()?, create_zdt(civil::date(2025, 1, 1))?);\nassert_eq!(zdt.last_of_year()?, create_zdt(civil::date(2025, 12, 31))?);\nassert_eq!(zdt.first_of_month()?, create_zdt(civil::date(2025, 7, 1))?);\nassert_eq!(zdt.last_of_month()?, create_zdt(civil::date(2025, 7, 31))?);\nassert_eq!(zdt.yesterday()?, create_zdt(civil::date(2025, 7, 9))?);\nassert_eq!(zdt.tomorrow()?, create_zdt(civil::date(2025, 7, 11))?);\n```\n\nThese routines on `ZonedDateTime` also take time zone transitions into account.\nFor example, `ZonedDateTime` knows that `tomorrow()` doesn’t always add 24\nhours:\n\n```\n// On 2024-11-03 at 2AM in New York, time was rolled\n// back 1 hour in the transition from daylight saving\n// time to standard time. That means 2024-11-03 was\n// actually 25 hours long in New York.\nlet zdt =\n    civil::date(2024, 11, 2).at(17, 25, 0, 0).in_tz(\"America/New_York\")?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(tomorrow.datetime(), civil::date(2024, 11, 3).at(17, 25, 0, 0));\n\n// The physical time difference between them is 25 hours!\nlet span = tomorrow - zdt;\nassert_eq!(format!(\"{span:#}\"), \"25h\");\n```\n\n> **NOTE**: We’ll talk about date arithmetic in the next section.\n\nWhen `ZonedDateTime::tomorrow()` (among other APIs that produce a\n`ZonedDateTime`) would land in a gap or a fold, the “compatible” disambiguation\nstrategy is chosen automatically:\n\n```\n// For a zoned datetime that lands\n// in a fold, the earlier instant is\n// chosen by default.\nlet zdt =\n    civil::date(2024, 11, 2).at(1, 30, 0, 0).in_tz(\"America/New_York\")?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(\n    tomorrow.to_string(),\n    \"2024-11-03T01:30:00-04:00[America/New_York]\"\n);\n\n// And for a gap, the later instant\n// is chosen by default.\nlet zdt =\n    civil::date(2024, 3, 9).at(2, 30, 0, 0).in_tz(\"America/New_York\")?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(\n    tomorrow.to_string(),\n    \"2024-03-10T03:30:00-04:00[America/New_York]\"\n);\n```\n\nTo override this behavior, you can drop down to civil datetimes, perform the\noperation, and then use `TimeZone::to_ambiguous_zoned_datetime` to control the\nexact disambiguation strategy:\n\n```\n// For a zoned datetime that lands\n// in a fold, the earlier instant is\n// chosen by default. But let's say\n// we want the later instant.\nlet zdt =\n    civil::date(2024, 11, 2).at(1, 30, 0, 0).in_tz(\"America/New_York\")?;\nlet tomorrow = zdt\n    .time_zone()\n    .to_ambiguous_zoned_datetime(zdt.datetime().tomorrow()?)\n    .later()?;\nassert_eq!(\n    tomorrow.to_string(),\n    // Notice that the offset is now -05,\n    // which corresponds to the later\n    // instant.\n    \"2024-11-03T01:30:00-05:00[America/New_York]\"\n);\n```\n\nThere are a few other methods of note on date types that are worth mentioning.\nFirst is the ability to query for things like, “The Thursday after next” or\n“The last Sunday of the month.” The former can be answered by the `nth_weekday`\nAPI:\n\n```\nlet zdt1 = civil::date(2024, 7, 10).in_tz(\"America/New_York\")?;\nassert_eq!(zdt1.weekday(), civil::Weekday::Wednesday);\n// Not this Thursday, but the next!\nlet zdt2 = zdt1.nth_weekday(2, civil::Weekday::Thursday)?;\nassert_eq!(zdt2.weekday(), civil::Weekday::Thursday);\nassert_eq!(zdt2.date(), civil::date(2024, 7, 18));\n```\n\nWhile the latter can be answered by the `nth_weekday_of_month` API:\n\n```\nlet zdt1 = civil::date(2024, 7, 10).in_tz(\"America/New_York\")?;\nassert_eq!(zdt1.weekday(), civil::Weekday::Wednesday);\n// The last Sunday of this month.\nlet zdt2 = zdt1.nth_weekday_of_month(-1, civil::Weekday::Sunday)?;\nassert_eq!(zdt2.weekday(), civil::Weekday::Sunday);\nassert_eq!(zdt2.date(), civil::date(2024, 7, 28));\n```\n\nFinally, users can access a convenient time series iterator via `series`:\n\n```\nuse jiff::{civil, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let start = civil::date(2024, 7, 10).in_tz(\"America/New_York\")?;\n    let mut dates = vec![];\n    // Every week for 8 weeks.\n    for zdt in start.series(1.week()).take(8) {\n        dates.push(zdt);\n    }\n    assert_eq!(\n        dates,\n        vec![\n            civil::date(2024, 7, 10).in_tz(\"America/New_York\")?,\n            civil::date(2024, 7, 17).in_tz(\"America/New_York\")?,\n            civil::date(2024, 7, 24).in_tz(\"America/New_York\")?,\n            civil::date(2024, 7, 31).in_tz(\"America/New_York\")?,\n            civil::date(2024, 8, 7).in_tz(\"America/New_York\")?,\n            civil::date(2024, 8, 14).in_tz(\"America/New_York\")?,\n            civil::date(2024, 8, 21).in_tz(\"America/New_York\")?,\n            civil::date(2024, 8, 28).in_tz(\"America/New_York\")?,\n        ]\n    );\n\n    Ok(())\n}\n```\n\nAll of these methods are also available on [`civil::Date`](https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html) and\n[`civil::DateTime`](https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html), which should make it very natural to move between them.\n\n### Date Arithmetic\n\nAll datetime types in Jiff support adding and subtracting durations, and\nfinding the span of time between two datetime values. Let’s start with a\n[`civil::Date`](https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html):\n\n```\nuse jiff::{civil, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let d1 = civil::date(2024, 7, 30);\n    let d2 = d1 + 2.days();\n    assert_eq!(d2, civil::date(2024, 8, 1));\n\n    Ok(())\n}\n```\n\nHere we make use of the `std::ops::Add` trait implementation for `civil::Date`.\nThe downside of using this, though, is that if the date value goes out of\nrange, then it panics. That may or may not be acceptable. But if you’re dealing\nwith user inputs, then you should use `Date::checked_add` instead:\n\n```\nuse jiff::{civil, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let d1 = civil::date(2024, 7, 30);\n    let d2 = d1.checked_add(2.days())?;\n    assert_eq!(d2, civil::date(2024, 8, 1));\n\n    Ok(())\n}\n```\n\nLet’s take a look at a few other examples involving months and years:\n\n```\nlet d = civil::date(2024, 5, 31);\nassert_eq!(d.checked_add(1.month())?, civil::date(2024, 6, 30));\nassert_eq!(d.checked_add(2.months())?, civil::date(2024, 7, 31));\n\nlet d = civil::date(2025, 1, 31);\nassert_eq!(d.checked_add(1.month())?, civil::date(2025, 2, 28));\n\nlet d = civil::date(2024, 2, 29);\nlet span = 1.year().months(2).days(5);\nassert_eq!(d.checked_add(span)?, civil::date(2025, 5, 4));\n```\n\nAs with other methods on `Date`, they are also available on `ZonedDateTime`:\n\n```\nlet d = civil::date(2024, 5, 31).at(13, 45, 0, 0).in_tz(\"America/New_York\")?;\nassert_eq!(\n    d.checked_add(1.month())?,\n    civil::date(2024, 6, 30).at(13, 45, 0, 0).in_tz(\"America/New_York\")?\n);\n```\n\nIf we take a look at the type signature for [`ZonedDateTime::checked_add`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html#method.checked_add), we\ncan see that it’s actually polymorphic:\n\n```\npub fn checked_add<A: Into<ZonedDateTimeArithmetic>>(\n    &self,\n    duration: A,\n) -> Result<ZonedDateTime, Error>\n```\n\nSpecifically, it accepts anything that can be converted into a\n[`ZonedDateTimeArithmetic`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTimeArithmetic.html). In this case, there are `From` trait\nimplementations for the following types:\n\n- [`Span`](https://docs.rs/jiff/1.*/jiff/struct.Span.html)\n- [`SignedDuration`](https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html)\n- [`std::time::Duration`](https://doc.rust-lang.org/nightly/std/time/struct.Duration.html)\n\nThis means that `ZonedDateTime::checked_add` can accept any one of these\nduration values:\n\n```\nuse jiff::{civil, SignedDuration};\n\nfn main() -> anyhow::Result<()> {\n    let d =\n        civil::date(2024, 5, 31).at(13, 45, 0, 0).in_tz(\"America/New_York\")?;\n    assert_eq!(\n        d.checked_add(SignedDuration::from_mins(45))?,\n        civil::date(2024, 5, 31).at(14, 30, 0, 0).in_tz(\"America/New_York\")?\n    );\n\n    Ok(())\n}\n```\n\nThis type of polymorphism is common in Jiff. Here, it is merely used to\nprovide a convenient way to use multiple duration types. But as we’ll see,\nit’s also used to provide an extension point for configuration options that\ncontrol how the operation works.\n\nIn addition to adding or subtracting durations from datetime values, one can\nalso compute the duration between two datetime values. For example, to get the\nnumber of days between two dates:\n\n```\nuse jiff::{civil, ToSpan};\n\nfn main() -> anyhow::Result<()> {\n    let d1 = civil::date(2024, 5, 31);\n    let d2 = civil::date(2024, 9, 30);\n    assert_eq!(d2 - d1, 122.days().fieldwise());\n\n    Ok(())\n}\n```\n\nSimilarly, we can use [`Date::until`](https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html#method.until) to compute the span between dates:\n\n```\nlet d1 = civil::date(2024, 5, 31);\nlet d2 = civil::date(2024, 9, 30);\nassert_eq!(d1.until(d2)?, 122.days().fieldwise());\n```\n\nLike with `Date::checked_add`, this routine is also available at\n[`ZonedDateTime::until`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html#method.until):\n\n```\nlet zdt1 = civil::date(2024, 5, 31).in_tz(\"America/New_York\")?;\nlet zdt2 = civil::date(2024, 9, 30).in_tz(\"America/New_York\")?;\nassert_eq!(zdt1.until(&zdt2)?, 2928.hours().fieldwise());\n```\n\nNotice though that hours, instead of days, are returned. This is because two\n`ZonedDateTime` values might be in different time zones. Since a `ZonedDateTime`\nis fundamentally an instant in time, and because days might be of varying length\ndepending on the time zone, defaulting to hours as the largest possible unit\nmeans subtracting two zoned datetimes will always succeed. However, we can\nrequest larger units in the duration returned by passing additional options.\nNotably, `ZonedDateTime::until` is polymorphic:\n\n```\npub fn until<'a, A: Into<ZonedDateTimeDifference<'a>>>(\n    &self,\n    other: A,\n) -> Result<Span, Error>\n```\n\nThat is, callers aren’t just limited to passing a `ZonedDateTime` here, but\n*anything* that can be converted to a [`ZonedDateTimeDifference`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTimeDifference.html). Here is\none such example, where we can override the largest units returned in the\nduration:\n\n```\nuse jiff::{civil, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let zdt1 = civil::date(2024, 5, 31).in_tz(\"America/New_York\")?;\n    let zdt2 = civil::date(2024, 9, 30).in_tz(\"America/New_York\")?;\n    assert_eq!(\n        zdt1.until((Unit::Month, &zdt2))?,\n        3.months().days(30).fieldwise()\n    );\n\n    Ok(())\n}\n```\n\nA `ZonedDateTimeDifference` provides much more powerful configuration options\nfor rounding the span returned. Take this example, which produces a span with\nmany unit values:\n\n```\nuse jiff::{civil::date, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let zdt1 =\n        date(2024, 5, 15).at(14, 30, 54, 0).in_tz(\"America/New_York\")?;\n    let zdt2 = date(2024, 5, 31)\n        .at(19, 13, 27, 123_456_789)\n        .in_tz(\"America/New_York\")?;\n    assert_eq!(\n        zdt1.until((Unit::Day, &zdt2))?,\n        16.days()\n            .hours(4)\n            .minutes(42)\n            .seconds(33)\n            .milliseconds(123)\n            .microseconds(456)\n            .nanoseconds(789)\n            .fieldwise(),\n    );\n\n    Ok(())\n}\n```\n\nThis might be *too* much precision to show to an end user. Instead, perhaps\nwe’d like to *round* the span to the nearest half-hour. We can do this by\nbuilding a `ZonedDateTimeDifference` explicitly and configuring its options:\n\n```\nuse jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -> anyhow::Result<()> {\n    let zdt1 =\n        date(2024, 5, 15).at(14, 30, 54, 0).in_tz(\"America/New_York\")?;\n    let zdt2 = date(2024, 5, 31)\n        .at(19, 13, 27, 123_456_789)\n        .in_tz(\"America/New_York\")?;\n    let difference = ZonedDateTimeDifference::new(&zdt2)\n        .largest(Unit::Day)\n        .smallest(Unit::Minute)\n        .increment(30)\n        .mode(RoundMode::HalfExpand);\n    assert_eq!(\n        zdt1.until(difference)?,\n        16.days().hours(4).minutes(30).fieldwise(),\n    );\n\n    Ok(())\n}\n```\n\nNote also that rounding a span takes time zone transitions like daylight saving\ntime into account. For example, let’s take `2024-11-02 17:30` and\n`2024-11-03 04:45` in New York. Because New York stopped daylight saving time\nat 2AM on 2024-11-03, the amount of physical time between them is 12 hours and\n15 minutes:\n\n```\nlet zdt1 = date(2024, 11, 2).at(17, 30, 0, 0).in_tz(\"America/New_York\")?;\nlet zdt2 = date(2024, 11, 3).at(4, 45, 0, 0).in_tz(\"America/New_York\")?;\nassert_eq!(zdt2 - zdt1, 12.hours().minutes(15).fieldwise());\n```\n\nNormally, if we rounded to the nearest day, this would round up to 1 day. But\nsince the midpoint of this particular day is actually 12 hours and 30 minutes,\nthis duration will round down to 0 days when we request it:\n\n```\nuse jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -> anyhow::Result<()> {\n    let zdt1 = date(2024, 11, 2).at(17, 30, 0, 0).in_tz(\"America/New_York\")?;\n    let zdt2 = date(2024, 11, 3).at(4, 45, 0, 0).in_tz(\"America/New_York\")?;\n    let difference = ZonedDateTimeDifference::new(&zdt2)\n        .largest(Unit::Day)\n        .smallest(Unit::Day)\n        .mode(RoundMode::HalfExpand);\n    assert_eq!(zdt1.until(difference)?, 0.days().fieldwise());\n\n    Ok(())\n}\n```\n\nNext we’ll continue our discussion of rounding, but when applied to datetimes\nthemselves.\n\n### Date Rounding\n\nDate rounding in Jiff is limited to units of days or lower. Therefore, it’s\nonly available on [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html), [`Timestamp`](https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html), [`civil::DateTime`](https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html),\n[`civil::Time`](https://docs.rs/jiff/1.*/jiff/civil/struct.Time.html) but not [`civil::Date`](https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html).\n\nA common example for rounding a datetime is to reduce precision. For example,\na system clock might provide nanosecond precision, but maybe we only care about\nthe nearest half-hour:\n\n```\nuse jiff::{civil::date, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let zdt = date(2024, 11, 2)\n        .at(17, 46, 20, 123_456_789)\n        .in_tz(\"America/New_York\")?;\n    assert_eq!(\n        zdt.to_string(),\n        \"2024-11-02T17:46:20.123456789-04:00[America/New_York]\"\n    );\n\n    // Round to the nearest half hour.\n    let rounded = zdt.round((Unit::Minute, 30))?;\n    assert_eq!(\n        rounded.to_string(),\n        \"2024-11-02T18:00:00-04:00[America/New_York]\"\n    );\n\n    Ok(())\n}\n```\n\nAs with rounding spans, rounding a `ZonedDateTime` is aware of time zone\ntransitions:\n\n```\nlet zdt = date(2024, 11, 3)\n    .at(11, 45, 20, 123_456_789)\n    .in_tz(\"America/New_York\")?;\n\n// Round to the nearest day.\nlet rounded = zdt.round(Unit::Day)?;\nassert_eq!(\n    rounded.to_string(),\n    \"2024-11-04T00:00:00-05:00[America/New_York]\"\n);\n```\n\nNotice that in the above example, our time of 11:45AM is *before* noon, yet the\nresult still rounds *up* to the next day. This is because the midpoint for this\nday is 11:30AM since, by 11:30AM, 12.5 hours have already elapsed because of\nthe repeated 1AM hour in the move away from daylight saving time in New York.\n\n### Other Calendars\n\nJiff itself doesn’t support any calendars other than the proleptic Gregorian\ncalendar. One can instead use the [ICU4X](https://docs.rs/icu) crate to work in non-Gregorian\ncalendars, and convert between datetime types using the [`jiff-icu`](https://docs.rs/jiff-icu) crate:\n(Use `cargo add icu jiff-icu` to make this example work.)\n\n```\nuse icu::{\n    calendar::{types::Month, Date as IcuDate},\n    time::{DateTime as IcuDateTime, Time as IcuTime},\n};\nuse jiff::civil::DateTime;\nuse jiff_icu::ConvertTryFrom as _;\n\nfn main() -> anyhow::Result<()> {\n    // Firstly, create an ICU datetime using the Hebrew calendar.\n    let datetime = IcuDateTime {\n        date: IcuDate::try_new_hebrew_v2(5785, Month::new(5), 4)?,\n        time: IcuTime::try_new(17, 30, 0, 0)?,\n    };\n\n    // Secondly, convert it to a civil datetime.\n    // This will automatically use ICU to convert\n    // the date from the Hebrew calendar to the\n    // Gregorian (or ISO) calendar.\n    let zdt = DateTime::convert_try_from(datetime)?;\n    assert_eq!(zdt.to_string(), \"2025-02-02T17:30:00\");\n    Ok(())\n}\n```\n\nThe ICU4X API supports [many more calendars](https://docs.rs/icu_calendar/latest/icu_calendar/).\n\n### Which DateTime Type Do I Use?\n\nThere are 3 potentially confusable datetime types in Jiff:\n\n- [`civil::DateTime`](https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html)\n- [`Timestamp`](https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html)\n- [`ZonedDateTime`](https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html)\n\nWhen should you use each one versus the other?\n\nTo a first approximation, if you *can* use a `ZonedDateTime`, then that is\nprobably the type you want to reach for. It represents a specific instant in\ntime in a particular geographic location. That is, it has both a `Timestamp`\nand a [`TimeZone`](https://docs.rs/jiff/1.*/jiff/tz/struct.TimeZone.html).\n\nIf you only ever need to work in UTC or just deal with system time, then a\n`Timestamp` is probably the right choice. This is useful for representing a\nspecific instant in time that is not connected to any time zone.\n\nA `civil::DateTime` is useful in contexts where you don’t care about a specific\ninstant in time and when calcuations should be done independent of time zone.\nFor example, when parsing datetime information from a user interface datetime\npicker.\n\nRemember that both a `civil::DateTime` and a `Timestamp` can be converted to a\n`ZonedDateTime` by supplying a time zone.\n\n## Span Manipulation\n\nWe’ve already seen how to add spans to datetime values and how to get spans\nas a difference between datetime values. But we haven’t yet explored the APIs\navailable on a `Span` itself.\n\nFirst and foremost, we can build a `Span` through its constructor, which\nreturns a `Span` with all of its units set to `0`:\n\n```\nuse jiff::Span;\n\nlet span = Span::new();\n```\n\nA `Span` is both `Copy` and immutable. We can create new spans through method\nchaining:\n\n```\nlet span = Span::new().hours(1).minutes(30);\nassert_eq!(span.to_string(), \"PT1H30M\");\n```\n\nOr we can use the `ToSpan` convenience trait, which adds methods on integer\ntypes for constructing spans:\n\n```\nuse jiff::ToSpan;\n\nlet span = 1.hour().minutes(30);\nassert_eq!(span.to_string(), \"PT1H30M\");\n```\n\nNote though that methods like `Span::hours` and `ToSpan::hours` will panic\nwhen the integer is outside the limits of what `Span` supports. This is fine\nwhen your spans are literals in your program, since a panic would indicate a\nbug. But if your inputs come from an end user, it’s better to use fallible\nmethods:\n\n```\nlet span = Span::new().try_hours(1)?.try_minutes(30)?;\nassert_eq!(span.to_string(), \"PT1H30M\");\n```\n\nSpans preserve each individual unit value. This means that 90 minutes and 1\nhour 30 minutes, while they represent the same duration, are actually different\nvalues in memory:\n\n```\nlet span1 = 1.hour().minutes(30);\nlet span2 = 90.minutes();\nassert_eq!(span1.to_string(), \"PT1H30M\");\nassert_eq!(span2.to_string(), \"PT90M\");\n```\n\nThis permits callers maximum flexibility when it comes to representing\ndurations. This makes it possible to represent durations in a specific unit\neven when they add up to larger units. For example, the runtime duration of\nfilms is typically conveyed in minutes, even when the runtime exceeds one hour.\nThis can be adjusted programmatically using `Span::round`:\n\n```\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span1 = 1.hour().minutes(30);\n    let span2 = span1.round(SpanRound::new().largest(Unit::Minute))?;\n    assert_eq!(span2.to_string(), \"PT90M\");\n\n    Ok(())\n}\n```\n\nYou can go the other way as well:\n\n```\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span1 = 90.minutes();\n    let span2 = span1.round(SpanRound::new().largest(Unit::Hour))?;\n    assert_eq!(span2.to_string(), \"PT1H30M\");\n\n    Ok(())\n}\n```\n\nNeither of these examples do actual rounding, despite the name of the API.\nInstead, since we’re only setting the largest unit, this API is doing unit\nbalancing. Unit balancing is when all unit values rollover into larger units\nup until the largest configured unit. This works even for calendar units too,\nbut you need to provide a relative date:\n\n```\nuse jiff::{civil, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 2756.hours();\n    let dt = civil::date(2020, 1, 1).at(0, 0, 0, 0);\n    let round = SpanRound::new().largest(Unit::Year).relative(dt);\n    assert_eq!(span.round(round)?.to_friendly(), \"3mo 23d 20h\");\n    Ok(())\n}\n```\n\nWithout a relative date, it’s not possible to know how many hours are in a\nsingle month. That is, once calendar units are involved, a span cannot be\ninterpreted as a physical duration of time until some context is applied.\n\nThe same even applies to days themselves, since days can sometimes be more or\nless than 24 hours. Take the above example. What happens if we use a zoned\ndatetime as our relative date instead?\n\n```\nuse jiff::{civil, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 2756.hours();\n    let zdt = civil::date(2020, 1, 1).at(0, 0, 0, 0).in_tz(\"Europe/Rome\")?;\n    let round = SpanRound::new().largest(Unit::Year).relative(&zdt);\n    assert_eq!(span.round(round)?.to_friendly(), \"3mo 23d 21h\");\n    Ok(())\n}\n```\n\nNotice that the duration’s hour component changed from `20` to `21`. Why?\nBecause we started with 2756 hour in both cases and because `2020-03-29` in\nRome was only 23 hours long (in a move from standard time to daylight saving\ntime). That means that one of those days in `3mo 23d` was only 23 hours long.\nSo an extra hour needed to be added to make up for it.\n\nThe `round` API can also do actual rounding:\n\n```\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 2.hours().minutes(30);\n    let round = SpanRound::new().smallest(Unit::Hour);\n    assert_eq!(span.round(round)?.to_friendly(), \"3h\");\n    Ok(())\n}\n```\n\nYou can also change its rounding mode from the default (“half-expand”, or like\nyou were taught rounding in school) to truncation (or one of several other\nmodes):\n\n```\nuse jiff::{RoundMode, SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 2.hours().minutes(30);\n    let round = SpanRound::new().smallest(Unit::Hour).mode(RoundMode::Trunc);\n    assert_eq!(span.round(round)?.to_friendly(), \"2h\");\n    Ok(())\n}\n```\n\nOne can also specify a rounding increment to round to the nearest unit value.\nFor example, to the nearest half-hour:\n\n```\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 2.hours().minutes(31);\n    let round = SpanRound::new().smallest(Unit::Minute).increment(30);\n    assert_eq!(span.round(round)?.to_friendly(), \"2h 30m\");\n    Ok(())\n}\n```\n\nBecause a `Span` value cannot easily be compared correctly based purely on its\nvalue in memory, a dedicated comparison [`Span::compare`](https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.compare) routine is provided:\n\n```\nlet span1 = 2.hours();\nlet span2 = 120.minutes();\nassert!(span1.compare(span2)?.is_eq());\n```\n\nAlso, one can convert a `Span` to a floating point value in terms of any unit.\nFor example:\n\n```\nuse jiff::{ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 90.minutes();\n    assert_eq!(span.total(Unit::Hour)?, 1.5);\n    Ok(())\n}\n```\n\nConverting to calendar units requires a relative date for the same reasons\ndiscussed above:\n\n```\nuse jiff::{civil, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 24.hours();\n    assert_eq!(\n        span.total((Unit::Month, civil::date(2026, 6, 1)))?,\n        0.03333333333333333\n    );\n    assert_eq!(\n        span.total((Unit::Month, civil::date(2026, 7, 1)))?,\n        0.03225806451612903\n    );\n    Ok(())\n}\n```\n\n## Conclusion\n\nSo far, we’ve explored a good chunk of Jiff’s API. We didn’t talk about every\nnook and cranny, but I think we’ve covered the most important pieces.\n\nWe’ll wrap up by briefly discussing motivation and inspiration.\n\n### Motivation\n\nWhenever I needed datetime handling in Rust, I always got confused. Should I\nuse `chrono` or `time`? How do I get my local time from a timestamp? How do I\nuse my system’s time zone database? How do I do calendar arithmetic?\n\nBefore I started working on Jiff, this confusion got annoying enough for me to\nconsider writing my own crate. I felt like the APIs of both `chrono` and `time`\ncould be improved upon. I personally found the domain quite interesting and so\nset out to build something better.\n\nWhy not improve on an existing solution, like `chrono` or `time`, instead of\nadding yet another choice into the ecosystem? I do think there are material\ndownsides of having too many choices, but I had concluded that both `chrono`\nand `time` (in 2024) had reached a local maximum. Moreover, in 2024, I was not\nan expert in datetime handling. It took building a datetime library to become\none. So convincing crate maintainers to go in a radically different direction\nwould have been a tall order.\n\nJiff’s [design](https://docs.rs/jiff/1.*/jiff/_documentation/design/index.html) and [comparison](https://docs.rs/jiff/1.*/jiff/_documentation/comparison/index.html) documentation contain much more detail\nregarding the motivation and specific examples between Jiff, `chrono` and\n`time`.\n\n### Inspiration\n\nJiff is heavily inspired by [Temporal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal), which is JavaScript’s standard library\nsolution for date and time management. Jiff inherits API design, functionality\nand even parsing/formatting of datetime values. Note though that Jiff is not\nand does not aim to be a 100% compatible implementation of the Temporal\nspecification. Jiff is meant to be a Rust ecosystem library first and foremost.\n\nWith that said, if you’re familiar with Temporal and Rust, then it’s likely\nyou’ll find Jiff to be a relatively straightforward translation of Temporal’s\nAPI to Rust. This example shows how to use Temporal to round a calendar span\nto the nearest number of days relative to a date:\n\n```\nconst duration = Temporal.Duration.from({ months: 1, days: 1, hours: 1 });\nconst roundedDuration = duration.round({\n  largestUnit: \"days\",\n  smallestUnit: \"days\",\n  relativeTo: Temporal.PlainDateTime.from(\"2022-01-01\"),\n});\nconsole.log(roundedDuration); // \"P32D\"\n```\n\nAnd here’s the equivalent operation in Jiff:\n\n```\nuse jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -> anyhow::Result<()> {\n    let span = 1.month().days(1).hours(1);\n    let rounded_span = span.round(\n        SpanRound::new()\n            .largest(Unit::Day)\n            .smallest(Unit::Day)\n            .relative(\"2022-01-01\".parse::<jiff::civil::Date>()?),\n    )?;\n    assert_eq!(rounded_span.to_string(), \"P32D\");\n    Ok(())\n}\n```\n\nThe main difference between these examples is that Jiff’s duration type is\nnamed `Span` instead of `Duration`. This was done to avoid confusion with\nRust’s standard library `std::time::Duration` type.\n\nHere are some other differences:\n\n- Temporal’s `Instant` type in Jiff is named `Timestamp` in order to avoid\n  confusion with Rust’s standard library `std::time::Instant` type.\n- Temporal’s “plain” date and time types are called “civil” in Jiff.\n- Jiff only supports the Gregorian calendar.\n- Jiff’s datetime range only extends to +/- 9999, whereas Temporal’s range is\n  larger.\n\nIt’s easy to say that without Temporal, Jiff wouldn’t exist in its current\nform today.\n","body_html":"<h1 id=\"jiff-1-0-a-datetime-library-for-rust\">Jiff 1.0: A datetime library for Rust</h1>\n<p><a href=\"https://github.com/BurntSushi/jiff\" rel=\"nofollow ugc noopener\">Jiff</a> is a datetime library for Rust that encourages you to jump into the\n<a href=\"https://blog.codinghorror.com/falling-into-the-pit-of-success/\" rel=\"nofollow ugc noopener\">pit of success</a>. Jiff automatically handles many common problems related to\ndaylight saving time by putting time zone handling front and center into the\nAPI. Jiff has already seen widespread <a href=\"https://crates.io/crates/jiff/reverse_dependencies\" rel=\"nofollow ugc noopener\">adoption</a> in the Rust ecosystem.</p>\n<p>Jiff is pronounced like “gif” with a soft “g,” as in “gem.”</p>\n<p>This blog announces the Jiff 1.0 release by giving a tour of its API.</p>\n<p><strong>Target audience</strong>: Rust programmers who need convenient datetime handling.</p>\n<h2 id=\"table-of-contents\">Table of Contents</h2>\n<ul><li><a href=\"#the-jiff-10-commitment\">The Jiff 1.0 Commitment</a></li><li><a href=\"#introduction\">Introduction</a><ul><li><a href=\"#follow-along\">Follow Along</a></li><li><a href=\"#terms\">Terms</a></li><li><a href=\"#the-datetime-onion\">The DateTime Onion</a></li><li><a href=\"#defining-a-time-zone\">Defining a time zone</a></li><li><a href=\"#durations\">Durations</a></li><li><a href=\"#when-should-i-use-jiff\">When should I use Jiff?</a></li></ul></li><li><a href=\"#parsing-and-formatting\">Parsing and Formatting</a><ul><li><a href=\"#fromstr-and-display\"><code>FromStr</code> and <code>Display</code></a></li><li><a href=\"#the-friendly-duration-format\">The “friendly” Duration Format</a></li><li><a href=\"#strptime-and-strftime\"><code>strptime</code> and <code>strftime</code></a></li><li><a href=\"#the-jifffmt-module\">The <code>jiff::fmt</code> module</a></li><li><a href=\"#locale-sensitive-formatting-via-icu4x-integration\">Locale Sensitive Formatting via ICU4X Integration</a></li></ul></li><li><a href=\"#date-manipulation\">Date Manipulation</a><ul><li><a href=\"#date-basics\">Date Basics</a></li><li><a href=\"#date-arithmetic\">Date Arithmetic</a></li><li><a href=\"#date-rounding\">Date Rounding</a></li><li><a href=\"#other-calendars\">Other Calendars</a></li><li><a href=\"#which-datetime-type-do-i-use\">Which DateTime Type Do I Use?</a></li></ul></li><li><a href=\"#span-manipulation\">Span Manipulation</a></li><li><a href=\"#conclusion\">Conclusion</a><ul><li><a href=\"#motivation\">Motivation</a></li><li><a href=\"#inspiration\">Inspiration</a></li></ul></li></ul>\n<h2 id=\"the-jiff-1-0-commitment\">The Jiff 1.0 Commitment</h2>\n<p>Jiff is already used in production in many projects: uv, Cargo, Starship, fd,\nNushell, mise, Jujutsu, uutils/coreutils and even as the basis for a Temporal\nimplementation in AWS LLRT. It is time to call it 1.0.</p>\n<p>Unless some significant defect is found in Jiff’s API, my plan is to commit\nto Jiff 1.0 indefinitely. This is important because the intent is for Jiff\nto be an ecosystem building block that appears in the public API of other\nlibraries. This makes Jiff an attractive <em>public</em> dependency, which means\nsemver incompatible releases are likely to cause significant pain in the\necosystem. They will not be made lightly.</p>\n<p>To see a list of breaking changes between Jiff 0.2 and Jiff 1.0, please\nconsult the <a href=\"https://github.com/BurntSushi/jiff/blob/master/CHANGELOG.md#100-2026-11-15\" rel=\"nofollow ugc noopener\">CHANGELOG</a>.</p>\n<h2 id=\"introduction\">Introduction</h2>\n<p>In programming, a datetime library’s core functionality rests at the\nintersection of a computer system’s concept of time and a human’s concept of\ntime. The prevailing notion of system time is <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow ugc noopener\">Unix time</a>. A human’s concept\nof time is far more complex, but the most popular such model is the <a href=\"https://en.wikipedia.org/wiki/Gregorian_calendar\" rel=\"nofollow ugc noopener\">Gregorian\ncalendar</a> coupled with either a 12-hour or 24-hour clock. At the core of every\ndatetime library rests some routine for converting between these concepts.</p>\n<p>A datetime library typically provides much more than this. Indeed, datetime\nhandling has <a href=\"https://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time\" rel=\"nofollow ugc noopener\">historically been very difficult</a>. My own belief is\nthat the difficulty comes from <em>poor modeling of the domain</em>. Instead of\nencapsulating the complexity inside a reusable bundle of code, many datetime\nlibraries pass some or all of the complexity on to its users. Jiff instead\ntries hard to encapsulate the complexity and make it difficult for users to\ndo something wrong. (<a href=\"#inspiration\">Jiff is not the first to do this!</a>)</p>\n<p>In this section of the blog, we’ll do some very basic introductions.</p>\n<h3 id=\"follow-along\">Follow Along</h3>\n<p>To follow along with the examples in this blog, create a new Cargo project\nwith dependencies on <code>jiff</code> and <code>anyhow</code>:</p>\n<pre><code>mkdir jiff-playground\ncd jiff-playground\ncargo init --bin\ncargo add jiff anyhow\n$EDITOR src/main.rs</code></pre>\n<p>Most examples are a complete self-contained Rust program. Just copy the code\nand replace whatever is in <code>src/main.rs</code>. Then run the program:</p>\n<pre><code>cargo run</code></pre>\n<h3 id=\"terms\">Terms</h3>\n<p>I am loath to present a dictionary. However, the datetime domain is littered\nwith confusable terms, so I think it’s important to orient ourselves on a\nshared vocabulary. I’ve kept this section as small as possible. (Some terms,\nlike “time zone,” are omitted here because they are best defined through\nexploration in the sections that follow.)</p>\n<ul><li><p><a href=\"https://en.wikipedia.org/wiki/Civil_time\" rel=\"nofollow ugc noopener\">Civil time</a>: The time you see on your clock. And in general, the time that</p><p>the 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.</p></li><li><p><a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"nofollow ugc noopener\">UTC</a>: An abbreviation for <em>Coordinated Universal Time</em>; it is a time</p><p>standard that serves as the basis for civil time around the world. It was\noriginally intended to roughly correspond to <a href=\"https://en.wikipedia.org/wiki/Solar_time#Mean_solar_time\" rel=\"nofollow ugc noopener\">mean solar time</a>.</p></li><li><p><a href=\"https://en.wikipedia.org/wiki/International_Atomic_Time\" rel=\"nofollow ugc noopener\">TAI</a>: An abbreviation for <em>International Atomic Time</em>; it is a time standard</p><p>as measured by atomic clocks. It isn’t directly connected to mean solar time.</p></li><li><p><a href=\"https://en.wikipedia.org/wiki/Leap_second\" rel=\"nofollow ugc noopener\">Leap second</a>: An adjustment to TAI to bring it closer to mean solar time</p><p>and thus forming the basis of UTC.</p></li><li><a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow ugc noopener\">Unix time</a>: UTC, but ignoring leap seconds.</li></ul>\n<p>TAI and leap seconds won’t be a feature of this blog, but they are listed here\nin order to convey the difference between Unix time and UTC.</p>\n<h3 id=\"the-datetime-onion\">The DateTime Onion</h3>\n<p>As a way to transition into some of the core types of Jiff, I’ve come to think\nof its datetime types like an onion. In reverse order, we can build up\nits layers all the way to a <code>ZonedDateTime</code>. So let’s start with more terms,\nbut this time, they are also types in Jiff:</p>\n<ul><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html\" rel=\"nofollow ugc noopener\"><code>civil::Date</code></a> is a plain Gregorian date, unattached to any specific</p><p>location.</p></li><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Time.html\" rel=\"nofollow ugc noopener\"><code>civil::Time</code></a> is a plain time on a clock, to nanosecond precision,</p><p>unattached to any specific location.</p></li><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html\" rel=\"nofollow ugc noopener\"><code>civil::DateTime</code></a> combines a <code>civil::Date</code> and a <code>civil::Time</code> to provide</p><p>both a Gregorian date and a time on a clock. It is also unattached to any\nspecific location.</p></li><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html\" rel=\"nofollow ugc noopener\"><code>Timestamp</code></a> is an unambiguous specific instant in time regardless of</p><p>geographic location, represented as the number of nanoseconds since the Unix\nepoch.</p></li><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/tz/struct.TimeZone.html\" rel=\"nofollow ugc noopener\"><code>TimeZone</code></a> is a set of rules for mapping a <code>Timestamp</code> to a</p><p><code>civil::DateTime</code>, and vice versa, in a specific geographic region.</p></li><li><p>A <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a> combines a <code>Timestamp</code>, a <code>civil::DateTime</code> and a</p><p><code>TimeZone</code> to represent a specific instant in time in a specific geographic\nlocation.</p></li></ul>\n<p>To make this a bit more concrete, we can see what this looks like in code.\nSince a time zone can map from a civil datetime to an instant in time, one way\nto create a zoned datetime requires only a civil datetime and a time zone:</p>\n<pre><code>use jiff::civil;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let date = civil::date(2026, 11, 1);\n    let time = civil::time(17, 30, 0, 0);\n    let datetime = date.to_datetime(time);\n    // zdt is an initialism for &quot;ZonedDateTime&quot;\n    let zdt = datetime.in_tz(&quot;America/New_York&quot;)?;\n\n    assert_eq!(zdt.timestamp().as_second(), 1793572200);\n\n    Ok(())\n}</code></pre>\n<p>Another way to create a zoned datetime requires only a timestamp and a time\nzone. This is because time zones can <em>also</em> map a timestamp to a particular\ncivil datetime:</p>\n<pre><code>use jiff::{civil, Timestamp};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let timestamp = Timestamp::from_second(1793572200)?;\n    let zdt = timestamp.in_tz(&quot;America/New_York&quot;)?;\n\n    // This is a shortcut for creating a civil datetime.\n    // The previous example spells it out a bit more verbosely\n    // for clarity.\n    let expected = civil::date(2026, 11, 1).at(17, 30, 0, 0);\n    assert_eq!(zdt.datetime(), expected);\n\n    Ok(())\n}</code></pre>\n<p>Notice how we get the equivalent zoned datetime in both cases, but we come at\nit from different directions. In the first case, we start with a time that we\nmight see on our clocks and calendars. In the second case, we start with a\nparticular instant in time that we might get from a database or file system or\nsome other system call.</p>\n<h3 id=\"defining-a-time-zone\">Defining a time zone</h3>\n<p>There is one piece missing from the zoned datetime onion examples: the\ntime zone <em>offset</em>. An offset represents the amount of time one must\nadjust UTC time in order to get civil time. For example, consider the time\n<code>2026-11-01T22:30:00</code> in UTC. In order to get the civil datetime for someone\nliving in New York, one would subtract 5 hours:</p>\n<pre><code>2026-11-01T22:30:00 - 05:00 = 2026-11-01T17:30:00</code></pre>\n<p>Indeed, every zoned datetime has an offset associated with it:</p>\n<pre><code>use jiff::{civil, tz, Timestamp};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let timestamp = Timestamp::from_second(1793572200)?;\n    let zdt = timestamp.in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(zdt.offset().seconds(), -(5 * 60 * 60));\n\n    let dt = civil::date(2026, 11, 1).at(17, 30, 0, 0);\n    let zdt = dt.in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(zdt.offset(), tz::offset(-5));\n\n    Ok(())\n}</code></pre>\n<blockquote><p><strong>NOTE</strong>: The <code>America/New_York</code> string you see in the above example is an\nIANA Time Zone Database Identifier. The <a href=\"https://www.iana.org/time-zones\" rel=\"nofollow ugc noopener\">IANA Time Zone Database</a> is a\ncollection of time zone definitions that can be referenced by a short\nidentifier string. Examples: <code>Australia/Sydney</code>, <code>Asia/Tokyo</code>,\n<code>Europe/Berlin</code>.</p></blockquote>\n<p>When a civil datetime is combined with an offset, then what you get is always\nan instant in time.</p>\n<p>With the concept of an offset introduced, we can now give a more precise\ndefinition of a time zone. A time zone <strong>is a geographic region in which civil\nclocks agree</strong> and which provides the following:</p>\n<ul><li><p>A mapping from an instant in time to an offset from UTC. The offset applied</p><p>to an instant yields a civil datetime.</p></li><li><p>A mapping from a civil datetime to a possibly ambiguous offset from UTC.</p><p>The offset applied to a civil datetime yields an instant.</p></li></ul>\n<p>Both mappings have been demonstrated in prior examples, but the mapping\nfrom civil datetime to an offset seems to be rather complicated due to some\npotential ambiguity. When does that ambiguity arise? An ambiguous offset occurs\nwhen the civil datetime either doesn’t correspond to a valid clock time in this\ntime zone (e.g., when clocks are moved ahead for <a href=\"https://en.wikipedia.org/wiki/Daylight_saving_time\" rel=\"nofollow ugc noopener\">daylight saving time</a>) or\nwhere there could be multiple valid clock times (e.g., when clocks are moved\nbackward for <a href=\"https://en.wikipedia.org/wiki/Daylight_saving_time\" rel=\"nofollow ugc noopener\">daylight saving time</a>).</p>\n<p>Let’s look at some examples. In this first example, we’ll take a look at times\naround the daylight saving time transition from summer time to standard time\nin New York. In New York, the clocks were “set back” by an hour at exactly 2AM.\nThis caused the 1AM hour to repeat itself.</p>\n<pre><code>use jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let tz = TimeZone::get(&quot;America/New_York&quot;)?;\n\n    // During summer time, New York&#39;s offset from UTC is -04:00.\n    let zdt = date(2026, 11, 1).at(0, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // During standard time, New York&#39;s offset from UTC is -05:00.\n    let zdt = date(2026, 11, 1).at(2, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // But what does 01:30AM mean? Is it the first repetition or the second?\n    // Jiff automatically chooses the first by default.\n    let zdt = date(2026, 11, 1).at(1, 30, 0, 0).to_zoned_datetime(tz.clone())?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    Ok(())\n}</code></pre>\n<p>The above example shows how Jiff resolves the ambiguity when a “fold” occurs,\nor when there is a time zone transition that moves the civil time backwards.\nBut we can actually dig down into lower level APIs to change how that ambiguity\nis resolved. By default, Jiff uses a “compatible” strategy that always selects\nthe first repetition of a time in a fold. But other strategies can be selected\nby using APIs on a <code>TimeZone</code> directly:</p>\n<pre><code>use jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let tz = TimeZone::get(&quot;America/New_York&quot;)?;\n    let dt = date(2026, 11, 1).at(1, 30, 0, 0);\n\n    // The same that Jiff uses by default.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).compatible()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the earlier datetime.\n    // For a fold, this is the same as the\n    // default &quot;compatible&quot; strategy.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).earlier()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the later datetime.\n    // For a fold, this selects the second\n    // occurrence of the 1AM hour!\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).later()?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // Always returns an error when there\n    // is any ambiguity.\n    assert_eq!(\n        tz.to_ambiguous_zoned_datetime(dt)\n            .unambiguous()\n            .unwrap_err()\n            .to_string(),\n        &quot;error converting datetime to instant in time zone America/New_York: \\\n         datetime is ambiguous \\\n         since it falls into a fold between offsets -04 and -05&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<p>The same idea applies to <em>gaps</em>, or time zone transitions where there’s some\ncivil time that gets skipped on civil clocks. For example, on March 8, 2026\nat 2AM, civil time skipped ahead to 3AM:</p>\n<pre><code>use jiff::{\n    civil::date,\n    tz::{offset, TimeZone},\n};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let tz = TimeZone::get(&quot;America/New_York&quot;)?;\n    let dt = date(2026, 3, 8).at(2, 30, 0, 0);\n\n    // The &quot;compatible&quot; strategy selects\n    // the later time in the case of gaps.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).compatible()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always selects the earlier datetime.\n    // For a gap, this selects the hour\n    // before the gap.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).earlier()?;\n    assert_eq!(zdt.offset(), offset(-5));\n\n    // Always selects the later datetime.\n    // For a gap, this is the same as the\n    // default &quot;compatible&quot; strategy.\n    let zdt = tz.to_ambiguous_zoned_datetime(dt).later()?;\n    assert_eq!(zdt.offset(), offset(-4));\n\n    // Always returns an error when there\n    // is any ambiguity.\n    assert_eq!(\n        tz.to_ambiguous_zoned_datetime(dt)\n            .unambiguous()\n            .unwrap_err()\n            .to_string(),\n        &quot;error converting datetime to instant in time zone America/New_York: \\\n         datetime is ambiguous \\\n         since it falls into a gap between offsets -05 and -04&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<h3 id=\"durations\">Durations</h3>\n<p>There are two remaining core types, both representing some notion of a\nduration:</p>\n<ul><li><p><a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html\" rel=\"nofollow ugc noopener\"><code>Span</code></a> is a powerful hybrid duration that combines both calendar units</p><p>(years, months, weeks, days) and physical time units (hours, minutes, seconds,\nmilliseconds, microseconds, nanoseconds). It is a beefy type that preserves the\nindividual unit values.</p></li><li><p><a href=\"https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html\" rel=\"nofollow ugc noopener\"><code>SignedDuration</code></a> is a signed version of <a href=\"https://doc.rust-lang.org/nightly/std/time/struct.Duration.html\" rel=\"nofollow ugc noopener\"><code>std::time::Duration</code></a> and always</p><p>corresponds to a 96-bit integer number of nanoseconds. It can only represent\nphysical time (units of hours or smaller) and not calendar units (units of days\nor greater).</p></li></ul>\n<p>A <code>Span</code> is the preferred duration type to use whenever possible. Here’s a\nsimple example that shows how to get the number of days between two civil\ndates:</p>\n<pre><code>use jiff::civil::date;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d1 = date(2024, 2, 1);\n    let d2 = date(2024, 3, 1);\n    let span = d2 - d1;\n    assert_eq!(span.get_days(), 29);\n    // or, equivalently:\n    assert_eq!(d1.until(d2)?.get_days(), 29);\n\n    // Flipping d1 and d2 gives the same result,\n    // but negative.\n    let span = d1 - d2;\n    assert_eq!(span.get_days(), -29);\n\n    Ok(())\n}</code></pre>\n<p>Durations can also be added to dates:</p>\n<pre><code>use jiff::{civil::date, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d1 = date(2024, 2, 1);\n    // This convenient syntax comes from the\n    // `ToSpan` extension trait.\n    let span = 29.days();\n    assert_eq!(d1.checked_add(span)?, date(2024, 3, 1));\n\n    Ok(())\n}</code></pre>\n<p>Generally speaking, whenever there is an operation involving a <code>Span</code>, there is\nan equivalent operation available with <code>SignedDuration</code>:</p>\n<pre><code>use jiff::{civil::date, SignedDuration};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let dt1 = date(2024, 2, 1).at(17, 30, 0, 0);\n    let sdur = SignedDuration::from_mins(90);\n    assert_eq!(dt1.checked_add(sdur)?, date(2024, 2, 1).at(19, 0, 0, 0));\n\n    Ok(())\n}</code></pre>\n<p>Notice that in the above example, we actually switched from using a\n<code>civil::Date</code> to a <code>civil::DateTime</code>. This was done to show how physical time\nunits can be added. But note that the same can be accomplished with a <code>Span</code>,\nbecause it combines all units:</p>\n<pre><code>use jiff::{civil::date, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let dt1 = date(2024, 2, 1).at(17, 30, 0, 0);\n    let span = 1.hour().minutes(30);\n    assert_eq!(dt1.checked_add(span)?, date(2024, 2, 1).at(19, 0, 0, 0));\n\n    // Calendar and physical time units can\n    // be combined!\n    let span = 1.month().hours(1).minutes(30);\n    assert_eq!(dt1.checked_add(span)?, date(2024, 3, 1).at(19, 0, 0, 0));\n\n    Ok(())\n}</code></pre>\n<p>In brief, use a <code>Span</code> when you can. But when it’s too bulky or too slow, use\na <code>SignedDuration</code>. One of the key benefits of a <code>Span</code> is that since it\nrepresents each unit value distinctly, one can preserve the original meaning\nof a duration. For example, it’s common to represent the runtime of films in\nminutes, even when the duration exceeds one hour. Indeed, a span of 2 hours\nis a distinct span from a span of 120 minutes:</p>\n<pre><code>use jiff::ToSpan;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span1 = 2.hours();\n    let span2 = 120.minutes();\n    // This means the spans are distinct values\n    // in memory.\n    assert_ne!(span1.fieldwise(), span2.fieldwise());\n\n    Ok(())\n}</code></pre>\n<p>The <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.fieldwise\" rel=\"nofollow ugc noopener\"><code>Span::fieldwise</code></a> routine converts a <code>Span</code> into a value whose units can\nbe compared in a field-by-field fashion. To compare spans based on the actual\nphysical duration they represent, use <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.compare\" rel=\"nofollow ugc noopener\"><code>Span::compare</code></a>:</p>\n<pre><code>let span1 = 2.hours();\nlet span2 = 120.minutes();\nassert!(span1.compare(span2)?.is_eq());</code></pre>\n<p>This was a very brief introduction to durations in Jiff. They are <em>a lot</em> more\npowerful than what is shown here. You might even try playing with the examples\nabove to explore its nooks and crannies. We’ll cover their API in more detail\nin a later section.</p>\n<h3 id=\"when-should-i-use-jiff\">When should I use Jiff?</h3>\n<p>Jiff isn’t always the right thing to use. Sometimes you can get by with\nsomething simpler.</p>\n<p>First and foremost, if you’re <em>measuring</em> the time something takes in a\nprogram, you should almost certainly be using monotonic time. This is\navailable via <a href=\"https://doc.rust-lang.org/nightly/std/time/struct.Instant.html\" rel=\"nofollow ugc noopener\"><code>std::time::Instant</code></a>:</p>\n<pre><code>use std::time::{Duration, Instant};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let start = Instant::now();\n\n    // do some serious work\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = Instant::now().duration_since(start);\n    println!(&quot;{elapsed:?}&quot;);\n\n    Ok(())\n}</code></pre>\n<p>If you do need to compute elapsed time using your system clock, then Jiff\nis very convenient for that:</p>\n<pre><code>use std::time::Duration;\n\nuse jiff::Timestamp;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    // assume `start` came from somewhere\n    // over a network\n    let start = Timestamp::now();\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = Timestamp::now().duration_since(start);\n    println!(&quot;{elapsed}&quot;);\n\n    Ok(())\n}</code></pre>\n<p>But you don’t actually need Jiff for this. A <a href=\"https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html\" rel=\"nofollow ugc noopener\"><code>std::time::SystemTime</code></a> will\nwork perfectly fine:</p>\n<pre><code>use std::time::{Duration, SystemTime};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    // assume `start` came from somewhere\n    // over a network\n    let start = SystemTime::now();\n    std::thread::sleep(Duration::from_secs(1));\n\n    let elapsed = SystemTime::now().duration_since(start)?;\n    println!(&quot;{elapsed:?}&quot;);\n\n    Ok(())\n}</code></pre>\n<p>Where Jiff starts to become useful is when you need something beyond just an\ninteger number of seconds since the Unix epoch. For example, some very hairy\nmath is required in order to convert a <code>SystemTime</code> into an RFC 3339 timestamp\nlike <code>2026-11-14T21:34:00Z</code>.</p>\n<p>As long as you can live in UTC completely, don’t care about local time and can\nwork with Unix timestamps only, then the Rust standard library won’t steer you\nwrong.</p>\n<h2 id=\"parsing-and-formatting\">Parsing and Formatting</h2>\n<p>Conversion to and from strings is a major part of Jiff. Jiff’s focus is\nprimarily on interoperability via the following:</p>\n<ul><li><p><a href=\"https://www.rfc-editor.org/info/rfc3339/\" rel=\"nofollow ugc noopener\">RFC 3339</a> specifies a format for fixed offset instants in time, in terms of</p><p>a human readable civil datetime. For example, <code>2026-11-12T15:36:00-05:00</code>. This\nis the serialization format used by <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html\" rel=\"nofollow ugc noopener\"><code>Timestamp</code></a>.</p></li><li><p><a href=\"https://www.rfc-editor.org/info/rfc9557/\" rel=\"nofollow ugc noopener\">RFC 9557</a> extends and updates RFC 3339 to add time zone information.</p><p>For example, <code>2026-11-12T15:36:00-05:00[America/New_York]</code>. This is the\nserialization format used by <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a>.</p></li><li><p><a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow ugc noopener\">ISO 8601</a> covers mostly everything else, including durations and</p><p>civil datetimes. For example, <code>P5Y3MT20H</code> is an ISO 8601 duration and\n<code>2026-11-12T15:30:00</code> is an ISO 8601 civil datetime whose corresponding instant\nin time is unknown.</p></li></ul>\n<p>What Jiff actually implements is the\n<a href=\"https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar\" rel=\"nofollow ugc noopener\">Temporal RFC 9557 / ISO 8601</a> grammar for flexible parsing of datetimes from\nstrings. For most use cases, it suffices to think in terms of RFC 3339,\nRFC 9557 or ISO 8601. But Jiff does support parsing strings that aren’t valid\nin any of those three specifications. For example, <code>2026-11-12[America/New_York]</code>\nparses as if it was <code>2026-11-12T00:00:00[America/New_York]</code>.</p>\n<p>In this section, we’ll take a tour of how Jiff does datetime formatting and\nprinting.</p>\n<h3 id=\"fromstr-and-display\"><code>FromStr</code> and <code>Display</code></h3>\n<p>Every datetime and duration type in Jiff implements the standard library\n<a href=\"https://doc.rust-lang.org/nightly/std/str/trait.FromStr.html\" rel=\"nofollow ugc noopener\"><code>FromStr</code></a> and <a href=\"https://doc.rust-lang.org/nightly/std/fmt/trait.Display.html\" rel=\"nofollow ugc noopener\"><code>Display</code></a> traits. This means that it’s natural to parse\ndatetimes:</p>\n<pre><code>let ts: Timestamp = &quot;2026-10-31T05:15:00Z&quot;.parse()?;</code></pre>\n<p>and print them:</p>\n<pre><code>println!(&quot;{ts}&quot;);</code></pre>\n<p>Parsing is flexible, so even if there are components missing, parsing still\nsucceeds. For example, without minutes or seconds, those components default to\nzero:</p>\n<pre><code>let dt: civil::DateTime = &quot;2026-10-31T05&quot;.parse()?;\nassert_eq!(dt.to_string(), &quot;2026-10-31T05:00:00&quot;);</code></pre>\n<p>Another example of flexible parsing is that if a string <em>contains</em> another date\ntype, then one can parse that. For example, one can parse a date out of an\nISO 8601 datetime:</p>\n<pre><code>let d: civil::Date = &quot;2026-10-31T05:30&quot;.parse()?;\nassert_eq!(d.to_string(), &quot;2026-10-31&quot;);</code></pre>\n<p>A <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a> always uses <a href=\"https://www.rfc-editor.org/info/rfc9557/\" rel=\"nofollow ugc noopener\">RFC 9557</a> syntax, which includes the IANA time\nzone identifier:</p>\n<pre><code>let zdt: ZonedDateTime = &quot;2026-10-31T05:30[Australia/Sydney]&quot;.parse()?;\n// While the string we parsed didn&#39;t have any offset,\n// one was automatically added by consulting the time\n// zone definition for the civil datetime provided.\nassert_eq!(zdt.to_string(), &quot;2026-10-31T05:30:00+11:00[Australia/Sydney]&quot;);</code></pre>\n<p>If you want to print a zoned datetime using only <a href=\"https://www.rfc-editor.org/info/rfc3339/\" rel=\"nofollow ugc noopener\">RFC 3339</a> syntax, then you\ncan do so by formatting the timestamp directly with the zoned datetime’s\noffset:</p>\n<pre><code>let zdt: ZonedDateTime = &quot;2026-10-31T05:30[Australia/Sydney]&quot;.parse()?;\nassert_eq!(\n    zdt.timestamp().display_with_offset(zdt.offset()).to_string(),\n    &quot;2026-10-31T05:30:00+11:00&quot;,\n);</code></pre>\n<p>The <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html\" rel=\"nofollow ugc noopener\"><code>Span</code></a> and <a href=\"https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html\" rel=\"nofollow ugc noopener\"><code>SignedDuration</code></a> types also support the <code>FromStr</code> and\n<code>Display</code> traits via the ISO 8601 duration format. For example:</p>\n<pre><code>use jiff::{SignedDuration, Span};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let duration = &quot;PT5H30M&quot;;\n\n    let span: Span = duration.parse()?;\n    assert_eq!(span.to_string(), &quot;PT5H30M&quot;);\n\n    let sdur: SignedDuration = duration.parse()?;\n    assert_eq!(sdur.to_string(), &quot;PT5H30M&quot;);\n\n    Ok(())\n}</code></pre>\n<p>Since a <code>Span</code> is a hybrid duration that also supports calendar units, it can\nparse durations with calendar units and physical time units. A <code>SignedDuration</code>\ncan only parse durations with physical time units:</p>\n<pre><code>use jiff::{SignedDuration, Span};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let duration = &quot;P11Y2M28DT5H30M&quot;;\n\n    let span: Span = duration.parse()?;\n    assert_eq!(span.to_string(), &quot;P11Y2M28DT5H30M&quot;);\n\n    let err = duration.parse::&lt;SignedDuration&gt;().unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        &quot;parsing ISO 8601 duration in this context requires \\\n         that the duration contain a time component \\\n         and no components of days or greater&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<p>The ISO 8601 duration format does, however, have some shortcomings that we’ll\ndiscuss in the next section.</p>\n<h3 id=\"the-friendly-duration-format\">The “friendly” Duration Format</h3>\n<p>Because ISO 8601 duration strings enjoy broad support, it is the default in\nJiff for both <code>Span</code> and <code>SignedDuration</code>. However, it has two important\nshortcomings:</p>\n<ol><li><p>It is difficult to read. For example, in <code>P11Y2M28DT5H30M</code>, the lack of</p><p> whitespace makes the unit values and the unit labels all run together.</p></li><li><p>An ISO 8601 duration cannot unambiguously represent all possible <code>Span</code></p><p> values.</p></li></ol>\n<p>The second shortcoming is best seen with an example. Consider a <code>Span</code> that is\n2000 milliseconds. If you convert this to an ISO 8601 duration string and then\nparse it back, you end up with 2 seconds instead:</p>\n<pre><code>use jiff::{Span, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let original = 2000.milliseconds();\n    assert_eq!(original.to_string(), &quot;PT2S&quot;);\n\n    let got: Span = &quot;PT2S&quot;.parse()?;\n\n    // The spans have different unit values!\n    assert_eq!(original.get_seconds(), 0);\n    assert_eq!(original.get_milliseconds(), 2000);\n    assert_eq!(got.get_seconds(), 2);\n    assert_eq!(got.get_milliseconds(), 0);\n\n    Ok(())\n}</code></pre>\n<p>This might not be desirable for cases where you want a span’s string format\nto faithfully represent all possible distinct values of a span.</p>\n<p>For these two reasons, Jiff comes with its own bespoke “friendly” duration\nformat. The friendly format is non-lossy <em>and</em> is meant to be easier to read\nfor English speakers than the ISO 8601 duration format. Here are some examples\nthat are all valid friendly durations:</p>\n<pre><code>40d\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</code></pre>\n<p>Parsing a friendly duration is as easy as parsing an ISO 8601 duration: the\n<code>FromStr</code> implementations on both <code>Span</code> and <code>SignedDuration</code> support ISO 8601\ndurations and friendly durations simultaneously:</p>\n<pre><code>let span: Span = &quot;6y 10mo 3d 23h&quot;.parse()?;\n// Recall that `Span::fieldwise` permits\n// equality comparisons on `Span` in a\n// unit-by-unit fashion.\nassert_eq!(span.fieldwise(), 6.years().months(10).days(3).hours(23));</code></pre>\n<p>Printing a friendly duration does require a bit more effort, since it isn’t\nthe default. Instead of <code>Span::to_string()</code>, one can use the “alternative”\nsyntax via Rust’s formatting machinery:</p>\n<pre><code>let span = 2000.milliseconds();\n// This also demonstrates that our unit\n// values are preserved.\nassert_eq!(format!(&quot;{span:#}&quot;), &quot;2000ms&quot;);</code></pre>\n<p>One can also use a lower level friendly printer to customize its output.\nFor example, here’s how to write a span in the friendly format to an existing\n<code>String</code> using more spacing, longer unit labels and commas separating each\nunit:</p>\n<pre><code>use jiff::{fmt::friendly, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    static PRINTER: friendly::SpanPrinter = friendly::SpanPrinter::new()\n        .comma_after_designator(true)\n        .spacing(friendly::Spacing::BetweenUnitsAndDesignators)\n        .designator(friendly::Designator::Verbose);\n\n    let span = 6.years().months(10).days(3).hours(23);\n    let mut buf = String::new();\n    PRINTER.print_span(&amp;span, &amp;mut buf)?;\n    assert_eq!(buf, &quot;6 years, 10 months, 3 days, 23 hours&quot;);\n\n    Ok(())\n}</code></pre>\n<p>See the <a href=\"https://docs.rs/jiff/1.*/jiff/fmt/friendly/index.html\" rel=\"nofollow ugc noopener\"><code>jiff::fmt::friendly</code></a> module for a lot more detail, including a\ngrammar that precisely specifies the format supported.</p>\n<h3 id=\"strptime-and-strftime\"><code>strptime</code> and <code>strftime</code></h3>\n<p>The <a href=\"https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html\" rel=\"nofollow ugc noopener\">POSIX <code>strptime</code></a> and <a href=\"https://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html\" rel=\"nofollow ugc noopener\">POSIX <code>strftime</code></a> routines are far from the ideal\nway to format and parse datetimes, but they are ubiquitous and most programmers\nare familiar with them. Because of their ubiquity, and because of the utility\nof being able to format and parse bespoke datetime formats, Jiff provides\nimplementations of these routines that are mostly POSIX compatible.</p>\n<p>Every datetime type in Jiff comes with <code>strptime</code> and <code>strftime</code> routines.\nFor example, to parse a civil date in the US <code>month/day/year</code> format:</p>\n<pre><code>let date = civil::Date::strptime(&quot;%m/%d/%Y&quot;, &quot;11/13/2026&quot;)?;\nassert_eq!(date.to_string(), &quot;2026-11-13&quot;);</code></pre>\n<p>Or to format a zoned datetime in a convenient to read representation for\nEnglish speakers:</p>\n<pre><code>let zdt = civil::date(2026, 11, 13).at(17, 30, 0, 0).in_tz(&quot;Australia/Sydney&quot;)?;\nassert_eq!(\n    zdt.strftime(&quot;%a, %b %d, %Y %H:%M %Z&quot;).to_string(),\n    &quot;Fri, Nov 13, 2026 17:30 AEDT&quot;,\n);</code></pre>\n<p>Callers can also use lower level APIs from <a href=\"https://docs.rs/jiff/1.*/jiff/fmt/strtime/index.html\" rel=\"nofollow ugc noopener\"><code>jiff::fmt::strtime</code></a> to get access\nto each parsed component individually:</p>\n<pre><code>use jiff::{civil, fmt::strtime::BrokenDownTime};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let tm = BrokenDownTime::parse(\n        &quot;%a, %b %d, %Y %H:%M&quot;,\n        &quot;Fri, Nov 13, 2026 17:30&quot;,\n    )?;\n    assert_eq!(tm.weekday(), Some(civil::Weekday::Friday));\n    assert_eq!(tm.month(), Some(11));\n    assert_eq!(tm.day(), Some(13));\n    assert_eq!(tm.year(), Some(2026));\n    assert_eq!(tm.hour(), Some(17));\n    assert_eq!(tm.minute(), Some(30));\n    assert_eq!(tm.second(), None);\n\n    Ok(())\n}</code></pre>\n<h3 id=\"the-jiff-fmt-module\">The <code>jiff::fmt</code> module</h3>\n<p>While the above tour should cover most use cases, there are sometimes reasons\nfor exerting more control over parsing or formatting. Or for supporting\nalternate formats like RFC 2822. The <a href=\"https://docs.rs/jiff/1.*/jiff/fmt/index.html\" rel=\"nofollow ugc noopener\"><code>jiff::fmt</code></a> module is meant to cover\nthese use cases at the cost of more complex APIs. For example, consider parsing\nan <a href=\"https://www.rfc-editor.org/info/rfc2822/\" rel=\"nofollow ugc noopener\">RFC 2822</a> datetime string from a <code>&amp;[u8]</code> (which lets callers avoid a UTF-8\nvalidation check):</p>\n<pre><code>use jiff::fmt::rfc2822;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    static PARSER: rfc2822::DateTimeParser = rfc2822::DateTimeParser::new();\n\n    let data = b&quot;Sat, 13 Jul 2024 15:09:59 -0400&quot;;\n    let ts = PARSER.parse_timestamp(data)?;\n    assert_eq!(ts.to_string(), &quot;2024-07-13T19:09:59Z&quot;);\n    Ok(())\n}</code></pre>\n<p>Another example shows how to change the default disambiguation strategy when\nthe provided civil datetime is ambiguous. For example, Sydney, Australia moved\nthe clocks backwards at <code>2026-04-05T03:00:00</code> local time. That is, they went\nfrom UTC offset <code>+11</code> to UTC offset <code>+10</code>. So what happens if we try to parse\na time on the clock that is repeated as a result?</p>\n<pre><code>use jiff::ZonedDateTime;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt: ZonedDateTime = &quot;2026-04-05T02:30[Australia/Sydney]&quot;.parse()?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+11:00[Australia/Sydney]&quot;);\n    Ok(())\n}</code></pre>\n<p>Here, the first occurrence of <code>02:30</code> is selected, just before Sydney leaves\ndaylight saving time. Now, the data itself can actually select the desired\noffset:</p>\n<pre><code>use jiff::ZonedDateTime;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt: ZonedDateTime =\n        &quot;2026-04-05T02:30+11:00[Australia/Sydney]&quot;.parse()?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+11:00[Australia/Sydney]&quot;);\n\n    let zdt: ZonedDateTime =\n        &quot;2026-04-05T02:30+10:00[Australia/Sydney]&quot;.parse()?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+10:00[Australia/Sydney]&quot;);\n\n    Ok(())\n}</code></pre>\n<p>But this happens because <em>there is no ambiguity</em> in the data. Since the offset\nis supplied, the exact instant in time is known. Going back to\n<code>2026-04-05T02:30[Australia/Sydney]</code>, which <em>is</em> ambiguous because it could\nrefer to two different instants in time, how do we modify the strategy for\nresolving that ambiguity? We can’t using the standard library <code>FromStr</code> trait,\nso we instead have to construct our own parser manually, just like we did for\n<a href=\"https://www.rfc-editor.org/info/rfc2822/\" rel=\"nofollow ugc noopener\">RFC 2822</a> parsing above. This example shows how to do that and all of the\ndifferent disambiguation options. Remember, UTC offset +11:00 corresponds to\nthe first occurrence of <code>2026-04-05T02:30</code> on the clocks of folks in Sydney\nwhile UTC offset +10:00 corresponds to the second occurrence.</p>\n<pre><code>use jiff::{fmt::temporal::DateTimeParser, tz::Disambiguation};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let string = &quot;2026-04-05T02:30[Australia/Sydney]&quot;;\n\n    // &quot;compatible&quot; is the default strategy, which selects\n    // the earlier time in a fold (usually moving from daylight\n    // saving time to standard time) and the later time in a\n    // gap (usually moving from standard time to daylight\n    // saving time).\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Compatible);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+11:00[Australia/Sydney]&quot;);\n\n    // &quot;earlier&quot; always selects the first occurrence\n    // in a fold, or the time before a gap.\n    // So this is the same as compatible in this case,\n    // since our civil time is in a fold.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Earlier);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+11:00[Australia/Sydney]&quot;);\n\n    // &quot;later&quot; always selects the second occurrence\n    // in a fold, or the time after a gap.\n    // So this is different from &quot;compatible&quot; for a\n    // fold. Notice that the UTC +10:00 offset is\n    // chosen.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Later);\n    let zdt = parser.parse_zoned_datetime(string)?;\n    assert_eq!(zdt.to_string(), &quot;2026-04-05T02:30:00+10:00[Australia/Sydney]&quot;);\n\n    // &quot;reject&quot; means that if the instant is ambiguous,\n    // then an error is returned.\n    let parser = DateTimeParser::new().disambiguation(Disambiguation::Reject);\n    let err = parser.parse_zoned_datetime(string).unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        &quot;error converting datetime to instant \\\n         in time zone Australia/Sydney: \\\n         datetime is ambiguous since it falls \\\n         into a fold between offsets +11 and +10&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<p>The <a href=\"https://docs.rs/jiff/1.*/jiff/fmt/index.html\" rel=\"nofollow ugc noopener\"><code>jiff::fmt</code></a> module contains lots of other goodies that we won’t cover\nhere, including, but not limited to:</p>\n<ul><li>The ability to format directly into an existing allocation.</li><li>Parsing a datetime into its individual components.</li><li>Helpers for <a href=\"https://serde.rs/\" rel=\"nofollow ugc noopener\"><code>serde</code></a> integration.</li></ul>\n<h3 id=\"locale-sensitive-formatting-via-icu4x-integration\">Locale Sensitive Formatting via ICU4X Integration</h3>\n<p>No section on datetime formatting would be complete without addressing locales.\nIn this context, a locale is a set of user preferences used for formatting\ndatetimes. This is useful when you want to present a datetime to an end user\nthat doesn’t expect standard formats from <a href=\"https://www.rfc-editor.org/info/rfc3339/\" rel=\"nofollow ugc noopener\">RFC 3339</a>, <a href=\"https://www.rfc-editor.org/info/rfc9557/\" rel=\"nofollow ugc noopener\">RFC 9557</a> or <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow ugc noopener\">ISO 8601</a>.</p>\n<p>Jiff itself does not provide any facilities for dealing with locales. Instead,\nusers can opt into this support via the <a href=\"https://docs.rs/icu\" rel=\"nofollow ugc noopener\">ICU4X</a> project. To make conversions\nbetween Jiff and ICU4X, the <a href=\"https://docs.rs/jiff-icu\" rel=\"nofollow ugc noopener\"><code>jiff-icu</code></a> integration crate can be used.</p>\n<p>Here’s an example showing how to format a zoned datetime in the <code>fr-LA</code> locale:\n(You’ll need to run <code>cargo add icu jiff-icu</code> to your project for this to work.)</p>\n<pre><code>use icu::{\n    calendar::Iso,\n    datetime::{fieldsets, DateTimeFormatter},\n    locale::locale,\n    time::{zone::models::AtTime, TimeZoneInfo},\n};\nuse jiff::ZonedDateTime;\nuse jiff_icu::ConvertFrom as _;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    // Firstly, do a conversion from Jiff&#39;s zoned datetime to ICU&#39;s.\n    let jiff_zdt: ZonedDateTime =\n        &quot;2024-09-10T23:37:20-04[America/New_York]&quot;.parse()?;\n    let icu_zdt =\n        icu::time::ZonedDateTime::&lt;Iso, TimeZoneInfo&lt;AtTime&gt;&gt;::convert_from(\n            &amp;jiff_zdt,\n        );\n\n    // Second, create a datetime formatter for the fr-LA locale:\n    let formatter = DateTimeFormatter::try_new(\n        locale!(&quot;fr-LA&quot;).into(),\n        fieldsets::YMDET::medium().with_zone(fieldsets::zone::SpecificLong),\n    )?;\n\n    // Thirdly, format the zoned datetime.\n    assert_eq!(\n        formatter.format(&amp;icu_zdt).to_string(),\n        &quot;mar. 10 sept. 2024, 23:37:20 heure d’été de l’Est nord-américain&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<p>The ICU4X API has a lot of options for customizing datetime formatting.\nExploring it further is outside the scope of this blog.</p>\n<h2 id=\"date-manipulation\">Date Manipulation</h2>\n<p>Jiff provides many methods on its datetime types to make using them as\ncomfortable and error-free as possible.</p>\n<h3 id=\"date-basics\">Date Basics</h3>\n<p>Every datetime type provides a <code>new</code> constructor that lets callers build it\nfrom its constituent parts. In most cases, this constructor is fallible. For\nexample:</p>\n<pre><code>use jiff::civil::Date;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d = Date::new(2024, 2, 29)?;\n    // All datetime types have convenient\n    // accessors for each of their components.\n    assert_eq!(d.year(), 2024);\n    assert_eq!(d.month(), 2);\n    assert_eq!(d.day(), 29);\n\n    let err = Date::new(2025, 2, 29).unwrap_err();\n    assert_eq!(\n        err.to_string(),\n        &quot;parameter &#39;day&#39; for `2025-02` is invalid, must be in range `1..=28`&quot;,\n    );\n\n    Ok(())\n}</code></pre>\n<p>Because creating dates is so common, there is a shorthand for doing so when\nyou know the inputs are valid:</p>\n<pre><code>let d = const { civil::date(2024, 2, 29) };\nassert_eq!(d.year(), 2024);\nassert_eq!(d.month(), 2);\nassert_eq!(d.day(), 29);</code></pre>\n<p>That is, <code>civil::date</code> is a const function that will panic if its inputs are\ninvalid. It should only be used with inputs that are known to be valid.\nIt would, for example, be inappropriate to use this with user provided values.\nBecause of the <code>const</code> block above, if you try to provide invalid values,\nyou’ll get a compiler error.</p>\n<p>For datetime types that represent an instant in time (i.e., <code>ZonedDateTime</code> and\n<code>Timestamp</code>), there is also a <code>now()</code> constructor for getting the current time:</p>\n<pre><code>use jiff::{Timestamp, ZonedDateTime};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let now = Timestamp::now();\n    println!(&quot;{now}&quot;);\n    // Example output: 2026-11-15T14:17:21.80099287Z\n\n    // This will automatically fetch your system&#39;s configured time zone.\n    let now = ZonedDateTime::now();\n    println!(&quot;{now}&quot;);\n    // Example output: 2026-11-15T09:17:21.80102125-05:00[America/New_York]\n\n    Ok(())\n}</code></pre>\n<p>In addition to constructors, new date values can be constructed from old\ndate values using the <code>Date::with</code> API:</p>\n<pre><code>let d1 = const { civil::date(2024, 2, 29) };\n// This API doesn&#39;t break just because 31\n// is supplied before a month that has 31\n// days. Any order is fine! This is because\n// errors are deferred until `build()` is\n// called.\nlet d2 = d1.with().day(31).month(3).build()?;\nassert_eq!(d2.to_string(), &quot;2024-03-31&quot;);</code></pre>\n<p>Once you have a date, there are oodles of APIs available:</p>\n<pre><code>let d = civil::date(2025, 7, 10);\nassert_eq!(d.weekday(), civil::Weekday::Thursday);\nassert_eq!(d.first_of_year(), civil::date(2025, 1, 1));\nassert_eq!(d.last_of_year(), civil::date(2025, 12, 31));\nassert_eq!(d.first_of_month(), civil::date(2025, 7, 1));\nassert_eq!(d.last_of_month(), civil::date(2025, 7, 31));\nassert_eq!(d.yesterday()?, civil::date(2025, 7, 9));\nassert_eq!(d.tomorrow()?, civil::date(2025, 7, 11));</code></pre>\n<p>Moreover, because of the <a href=\"#the-datetime-onion\">datetime onion</a>, all of these\nAPIs are also available on <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html\" rel=\"nofollow ugc noopener\"><code>civil::DateTime</code></a> and <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a>:</p>\n<pre><code>let create_zdt =\n    |date: civil::Date| -&gt; Result&lt;ZonedDateTime, jiff::Error&gt; {\n        date.at(0, 0, 0, 0).in_tz(&quot;America/New_York&quot;)\n    };\n\nlet zdt = create_zdt(civil::date(2025, 7, 10))?;\nassert_eq!(zdt.weekday(), civil::Weekday::Thursday);\nassert_eq!(zdt.first_of_year()?, create_zdt(civil::date(2025, 1, 1))?);\nassert_eq!(zdt.last_of_year()?, create_zdt(civil::date(2025, 12, 31))?);\nassert_eq!(zdt.first_of_month()?, create_zdt(civil::date(2025, 7, 1))?);\nassert_eq!(zdt.last_of_month()?, create_zdt(civil::date(2025, 7, 31))?);\nassert_eq!(zdt.yesterday()?, create_zdt(civil::date(2025, 7, 9))?);\nassert_eq!(zdt.tomorrow()?, create_zdt(civil::date(2025, 7, 11))?);</code></pre>\n<p>These routines on <code>ZonedDateTime</code> also take time zone transitions into account.\nFor example, <code>ZonedDateTime</code> knows that <code>tomorrow()</code> doesn’t always add 24\nhours:</p>\n<pre><code>// On 2024-11-03 at 2AM in New York, time was rolled\n// back 1 hour in the transition from daylight saving\n// time to standard time. That means 2024-11-03 was\n// actually 25 hours long in New York.\nlet zdt =\n    civil::date(2024, 11, 2).at(17, 25, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(tomorrow.datetime(), civil::date(2024, 11, 3).at(17, 25, 0, 0));\n\n// The physical time difference between them is 25 hours!\nlet span = tomorrow - zdt;\nassert_eq!(format!(&quot;{span:#}&quot;), &quot;25h&quot;);</code></pre>\n<blockquote><p><strong>NOTE</strong>: We’ll talk about date arithmetic in the next section.</p></blockquote>\n<p>When <code>ZonedDateTime::tomorrow()</code> (among other APIs that produce a\n<code>ZonedDateTime</code>) would land in a gap or a fold, the “compatible” disambiguation\nstrategy is chosen automatically:</p>\n<pre><code>// For a zoned datetime that lands\n// in a fold, the earlier instant is\n// chosen by default.\nlet zdt =\n    civil::date(2024, 11, 2).at(1, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(\n    tomorrow.to_string(),\n    &quot;2024-11-03T01:30:00-04:00[America/New_York]&quot;\n);\n\n// And for a gap, the later instant\n// is chosen by default.\nlet zdt =\n    civil::date(2024, 3, 9).at(2, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nlet tomorrow = zdt.tomorrow()?;\nassert_eq!(\n    tomorrow.to_string(),\n    &quot;2024-03-10T03:30:00-04:00[America/New_York]&quot;\n);</code></pre>\n<p>To override this behavior, you can drop down to civil datetimes, perform the\noperation, and then use <code>TimeZone::to_ambiguous_zoned_datetime</code> to control the\nexact disambiguation strategy:</p>\n<pre><code>// For a zoned datetime that lands\n// in a fold, the earlier instant is\n// chosen by default. But let&#39;s say\n// we want the later instant.\nlet zdt =\n    civil::date(2024, 11, 2).at(1, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nlet tomorrow = zdt\n    .time_zone()\n    .to_ambiguous_zoned_datetime(zdt.datetime().tomorrow()?)\n    .later()?;\nassert_eq!(\n    tomorrow.to_string(),\n    // Notice that the offset is now -05,\n    // which corresponds to the later\n    // instant.\n    &quot;2024-11-03T01:30:00-05:00[America/New_York]&quot;\n);</code></pre>\n<p>There are a few other methods of note on date types that are worth mentioning.\nFirst is the ability to query for things like, “The Thursday after next” or\n“The last Sunday of the month.” The former can be answered by the <code>nth_weekday</code>\nAPI:</p>\n<pre><code>let zdt1 = civil::date(2024, 7, 10).in_tz(&quot;America/New_York&quot;)?;\nassert_eq!(zdt1.weekday(), civil::Weekday::Wednesday);\n// Not this Thursday, but the next!\nlet zdt2 = zdt1.nth_weekday(2, civil::Weekday::Thursday)?;\nassert_eq!(zdt2.weekday(), civil::Weekday::Thursday);\nassert_eq!(zdt2.date(), civil::date(2024, 7, 18));</code></pre>\n<p>While the latter can be answered by the <code>nth_weekday_of_month</code> API:</p>\n<pre><code>let zdt1 = civil::date(2024, 7, 10).in_tz(&quot;America/New_York&quot;)?;\nassert_eq!(zdt1.weekday(), civil::Weekday::Wednesday);\n// The last Sunday of this month.\nlet zdt2 = zdt1.nth_weekday_of_month(-1, civil::Weekday::Sunday)?;\nassert_eq!(zdt2.weekday(), civil::Weekday::Sunday);\nassert_eq!(zdt2.date(), civil::date(2024, 7, 28));</code></pre>\n<p>Finally, users can access a convenient time series iterator via <code>series</code>:</p>\n<pre><code>use jiff::{civil, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let start = civil::date(2024, 7, 10).in_tz(&quot;America/New_York&quot;)?;\n    let mut dates = vec![];\n    // Every week for 8 weeks.\n    for zdt in start.series(1.week()).take(8) {\n        dates.push(zdt);\n    }\n    assert_eq!(\n        dates,\n        vec![\n            civil::date(2024, 7, 10).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 7, 17).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 7, 24).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 7, 31).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 8, 7).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 8, 14).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 8, 21).in_tz(&quot;America/New_York&quot;)?,\n            civil::date(2024, 8, 28).in_tz(&quot;America/New_York&quot;)?,\n        ]\n    );\n\n    Ok(())\n}</code></pre>\n<p>All of these methods are also available on <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html\" rel=\"nofollow ugc noopener\"><code>civil::Date</code></a> and\n<a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html\" rel=\"nofollow ugc noopener\"><code>civil::DateTime</code></a>, which should make it very natural to move between them.</p>\n<h3 id=\"date-arithmetic\">Date Arithmetic</h3>\n<p>All datetime types in Jiff support adding and subtracting durations, and\nfinding the span of time between two datetime values. Let’s start with a\n<a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html\" rel=\"nofollow ugc noopener\"><code>civil::Date</code></a>:</p>\n<pre><code>use jiff::{civil, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d1 = civil::date(2024, 7, 30);\n    let d2 = d1 + 2.days();\n    assert_eq!(d2, civil::date(2024, 8, 1));\n\n    Ok(())\n}</code></pre>\n<p>Here we make use of the <code>std::ops::Add</code> trait implementation for <code>civil::Date</code>.\nThe downside of using this, though, is that if the date value goes out of\nrange, then it panics. That may or may not be acceptable. But if you’re dealing\nwith user inputs, then you should use <code>Date::checked_add</code> instead:</p>\n<pre><code>use jiff::{civil, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d1 = civil::date(2024, 7, 30);\n    let d2 = d1.checked_add(2.days())?;\n    assert_eq!(d2, civil::date(2024, 8, 1));\n\n    Ok(())\n}</code></pre>\n<p>Let’s take a look at a few other examples involving months and years:</p>\n<pre><code>let d = civil::date(2024, 5, 31);\nassert_eq!(d.checked_add(1.month())?, civil::date(2024, 6, 30));\nassert_eq!(d.checked_add(2.months())?, civil::date(2024, 7, 31));\n\nlet d = civil::date(2025, 1, 31);\nassert_eq!(d.checked_add(1.month())?, civil::date(2025, 2, 28));\n\nlet d = civil::date(2024, 2, 29);\nlet span = 1.year().months(2).days(5);\nassert_eq!(d.checked_add(span)?, civil::date(2025, 5, 4));</code></pre>\n<p>As with other methods on <code>Date</code>, they are also available on <code>ZonedDateTime</code>:</p>\n<pre><code>let d = civil::date(2024, 5, 31).at(13, 45, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nassert_eq!(\n    d.checked_add(1.month())?,\n    civil::date(2024, 6, 30).at(13, 45, 0, 0).in_tz(&quot;America/New_York&quot;)?\n);</code></pre>\n<p>If we take a look at the type signature for <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html#method.checked_add\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime::checked_add</code></a>, we\ncan see that it’s actually polymorphic:</p>\n<pre><code>pub fn checked_add&lt;A: Into&lt;ZonedDateTimeArithmetic&gt;&gt;(\n    &amp;self,\n    duration: A,\n) -&gt; Result&lt;ZonedDateTime, Error&gt;</code></pre>\n<p>Specifically, it accepts anything that can be converted into a\n<a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTimeArithmetic.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTimeArithmetic</code></a>. In this case, there are <code>From</code> trait\nimplementations for the following types:</p>\n<ul><li><a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html\" rel=\"nofollow ugc noopener\"><code>Span</code></a></li><li><a href=\"https://docs.rs/jiff/1.*/jiff/struct.SignedDuration.html\" rel=\"nofollow ugc noopener\"><code>SignedDuration</code></a></li><li><a href=\"https://doc.rust-lang.org/nightly/std/time/struct.Duration.html\" rel=\"nofollow ugc noopener\"><code>std::time::Duration</code></a></li></ul>\n<p>This means that <code>ZonedDateTime::checked_add</code> can accept any one of these\nduration values:</p>\n<pre><code>use jiff::{civil, SignedDuration};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d =\n        civil::date(2024, 5, 31).at(13, 45, 0, 0).in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(\n        d.checked_add(SignedDuration::from_mins(45))?,\n        civil::date(2024, 5, 31).at(14, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?\n    );\n\n    Ok(())\n}</code></pre>\n<p>This type of polymorphism is common in Jiff. Here, it is merely used to\nprovide a convenient way to use multiple duration types. But as we’ll see,\nit’s also used to provide an extension point for configuration options that\ncontrol how the operation works.</p>\n<p>In addition to adding or subtracting durations from datetime values, one can\nalso compute the duration between two datetime values. For example, to get the\nnumber of days between two dates:</p>\n<pre><code>use jiff::{civil, ToSpan};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let d1 = civil::date(2024, 5, 31);\n    let d2 = civil::date(2024, 9, 30);\n    assert_eq!(d2 - d1, 122.days().fieldwise());\n\n    Ok(())\n}</code></pre>\n<p>Similarly, we can use <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html#method.until\" rel=\"nofollow ugc noopener\"><code>Date::until</code></a> to compute the span between dates:</p>\n<pre><code>let d1 = civil::date(2024, 5, 31);\nlet d2 = civil::date(2024, 9, 30);\nassert_eq!(d1.until(d2)?, 122.days().fieldwise());</code></pre>\n<p>Like with <code>Date::checked_add</code>, this routine is also available at\n<a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html#method.until\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime::until</code></a>:</p>\n<pre><code>let zdt1 = civil::date(2024, 5, 31).in_tz(&quot;America/New_York&quot;)?;\nlet zdt2 = civil::date(2024, 9, 30).in_tz(&quot;America/New_York&quot;)?;\nassert_eq!(zdt1.until(&amp;zdt2)?, 2928.hours().fieldwise());</code></pre>\n<p>Notice though that hours, instead of days, are returned. This is because two\n<code>ZonedDateTime</code> values might be in different time zones. Since a <code>ZonedDateTime</code>\nis fundamentally an instant in time, and because days might be of varying length\ndepending on the time zone, defaulting to hours as the largest possible unit\nmeans subtracting two zoned datetimes will always succeed. However, we can\nrequest larger units in the duration returned by passing additional options.\nNotably, <code>ZonedDateTime::until</code> is polymorphic:</p>\n<pre><code>pub fn until&lt;&#39;a, A: Into&lt;ZonedDateTimeDifference&lt;&#39;a&gt;&gt;&gt;(\n    &amp;self,\n    other: A,\n) -&gt; Result&lt;Span, Error&gt;</code></pre>\n<p>That is, callers aren’t just limited to passing a <code>ZonedDateTime</code> here, but\n<em>anything</em> that can be converted to a <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTimeDifference.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTimeDifference</code></a>. Here is\none such example, where we can override the largest units returned in the\nduration:</p>\n<pre><code>use jiff::{civil, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt1 = civil::date(2024, 5, 31).in_tz(&quot;America/New_York&quot;)?;\n    let zdt2 = civil::date(2024, 9, 30).in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(\n        zdt1.until((Unit::Month, &amp;zdt2))?,\n        3.months().days(30).fieldwise()\n    );\n\n    Ok(())\n}</code></pre>\n<p>A <code>ZonedDateTimeDifference</code> provides much more powerful configuration options\nfor rounding the span returned. Take this example, which produces a span with\nmany unit values:</p>\n<pre><code>use jiff::{civil::date, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt1 =\n        date(2024, 5, 15).at(14, 30, 54, 0).in_tz(&quot;America/New_York&quot;)?;\n    let zdt2 = date(2024, 5, 31)\n        .at(19, 13, 27, 123_456_789)\n        .in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(\n        zdt1.until((Unit::Day, &amp;zdt2))?,\n        16.days()\n            .hours(4)\n            .minutes(42)\n            .seconds(33)\n            .milliseconds(123)\n            .microseconds(456)\n            .nanoseconds(789)\n            .fieldwise(),\n    );\n\n    Ok(())\n}</code></pre>\n<p>This might be <em>too</em> much precision to show to an end user. Instead, perhaps\nwe’d like to <em>round</em> the span to the nearest half-hour. We can do this by\nbuilding a <code>ZonedDateTimeDifference</code> explicitly and configuring its options:</p>\n<pre><code>use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt1 =\n        date(2024, 5, 15).at(14, 30, 54, 0).in_tz(&quot;America/New_York&quot;)?;\n    let zdt2 = date(2024, 5, 31)\n        .at(19, 13, 27, 123_456_789)\n        .in_tz(&quot;America/New_York&quot;)?;\n    let difference = ZonedDateTimeDifference::new(&amp;zdt2)\n        .largest(Unit::Day)\n        .smallest(Unit::Minute)\n        .increment(30)\n        .mode(RoundMode::HalfExpand);\n    assert_eq!(\n        zdt1.until(difference)?,\n        16.days().hours(4).minutes(30).fieldwise(),\n    );\n\n    Ok(())\n}</code></pre>\n<p>Note also that rounding a span takes time zone transitions like daylight saving\ntime into account. For example, let’s take <code>2024-11-02 17:30</code> and\n<code>2024-11-03 04:45</code> in New York. Because New York stopped daylight saving time\nat 2AM on 2024-11-03, the amount of physical time between them is 12 hours and\n15 minutes:</p>\n<pre><code>let zdt1 = date(2024, 11, 2).at(17, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nlet zdt2 = date(2024, 11, 3).at(4, 45, 0, 0).in_tz(&quot;America/New_York&quot;)?;\nassert_eq!(zdt2 - zdt1, 12.hours().minutes(15).fieldwise());</code></pre>\n<p>Normally, if we rounded to the nearest day, this would round up to 1 day. But\nsince the midpoint of this particular day is actually 12 hours and 30 minutes,\nthis duration will round down to 0 days when we request it:</p>\n<pre><code>use jiff::{civil::date, RoundMode, ToSpan, Unit, ZonedDateTimeDifference};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt1 = date(2024, 11, 2).at(17, 30, 0, 0).in_tz(&quot;America/New_York&quot;)?;\n    let zdt2 = date(2024, 11, 3).at(4, 45, 0, 0).in_tz(&quot;America/New_York&quot;)?;\n    let difference = ZonedDateTimeDifference::new(&amp;zdt2)\n        .largest(Unit::Day)\n        .smallest(Unit::Day)\n        .mode(RoundMode::HalfExpand);\n    assert_eq!(zdt1.until(difference)?, 0.days().fieldwise());\n\n    Ok(())\n}</code></pre>\n<p>Next we’ll continue our discussion of rounding, but when applied to datetimes\nthemselves.</p>\n<h3 id=\"date-rounding\">Date Rounding</h3>\n<p>Date rounding in Jiff is limited to units of days or lower. Therefore, it’s\nonly available on <a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a>, <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html\" rel=\"nofollow ugc noopener\"><code>Timestamp</code></a>, <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html\" rel=\"nofollow ugc noopener\"><code>civil::DateTime</code></a>,\n<a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Time.html\" rel=\"nofollow ugc noopener\"><code>civil::Time</code></a> but not <a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.Date.html\" rel=\"nofollow ugc noopener\"><code>civil::Date</code></a>.</p>\n<p>A common example for rounding a datetime is to reduce precision. For example,\na system clock might provide nanosecond precision, but maybe we only care about\nthe nearest half-hour:</p>\n<pre><code>use jiff::{civil::date, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let zdt = date(2024, 11, 2)\n        .at(17, 46, 20, 123_456_789)\n        .in_tz(&quot;America/New_York&quot;)?;\n    assert_eq!(\n        zdt.to_string(),\n        &quot;2024-11-02T17:46:20.123456789-04:00[America/New_York]&quot;\n    );\n\n    // Round to the nearest half hour.\n    let rounded = zdt.round((Unit::Minute, 30))?;\n    assert_eq!(\n        rounded.to_string(),\n        &quot;2024-11-02T18:00:00-04:00[America/New_York]&quot;\n    );\n\n    Ok(())\n}</code></pre>\n<p>As with rounding spans, rounding a <code>ZonedDateTime</code> is aware of time zone\ntransitions:</p>\n<pre><code>let zdt = date(2024, 11, 3)\n    .at(11, 45, 20, 123_456_789)\n    .in_tz(&quot;America/New_York&quot;)?;\n\n// Round to the nearest day.\nlet rounded = zdt.round(Unit::Day)?;\nassert_eq!(\n    rounded.to_string(),\n    &quot;2024-11-04T00:00:00-05:00[America/New_York]&quot;\n);</code></pre>\n<p>Notice that in the above example, our time of 11:45AM is <em>before</em> noon, yet the\nresult still rounds <em>up</em> to the next day. This is because the midpoint for this\nday is 11:30AM since, by 11:30AM, 12.5 hours have already elapsed because of\nthe repeated 1AM hour in the move away from daylight saving time in New York.</p>\n<h3 id=\"other-calendars\">Other Calendars</h3>\n<p>Jiff itself doesn’t support any calendars other than the proleptic Gregorian\ncalendar. One can instead use the <a href=\"https://docs.rs/icu\" rel=\"nofollow ugc noopener\">ICU4X</a> crate to work in non-Gregorian\ncalendars, and convert between datetime types using the <a href=\"https://docs.rs/jiff-icu\" rel=\"nofollow ugc noopener\"><code>jiff-icu</code></a> crate:\n(Use <code>cargo add icu jiff-icu</code> to make this example work.)</p>\n<pre><code>use icu::{\n    calendar::{types::Month, Date as IcuDate},\n    time::{DateTime as IcuDateTime, Time as IcuTime},\n};\nuse jiff::civil::DateTime;\nuse jiff_icu::ConvertTryFrom as _;\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    // Firstly, create an ICU datetime using the Hebrew calendar.\n    let datetime = IcuDateTime {\n        date: IcuDate::try_new_hebrew_v2(5785, Month::new(5), 4)?,\n        time: IcuTime::try_new(17, 30, 0, 0)?,\n    };\n\n    // Secondly, convert it to a civil datetime.\n    // This will automatically use ICU to convert\n    // the date from the Hebrew calendar to the\n    // Gregorian (or ISO) calendar.\n    let zdt = DateTime::convert_try_from(datetime)?;\n    assert_eq!(zdt.to_string(), &quot;2025-02-02T17:30:00&quot;);\n    Ok(())\n}</code></pre>\n<p>The ICU4X API supports <a href=\"https://docs.rs/icu_calendar/latest/icu_calendar/\" rel=\"nofollow ugc noopener\">many more calendars</a>.</p>\n<h3 id=\"which-datetime-type-do-i-use\">Which DateTime Type Do I Use?</h3>\n<p>There are 3 potentially confusable datetime types in Jiff:</p>\n<ul><li><a href=\"https://docs.rs/jiff/1.*/jiff/civil/struct.DateTime.html\" rel=\"nofollow ugc noopener\"><code>civil::DateTime</code></a></li><li><a href=\"https://docs.rs/jiff/1.*/jiff/struct.Timestamp.html\" rel=\"nofollow ugc noopener\"><code>Timestamp</code></a></li><li><a href=\"https://docs.rs/jiff/1.*/jiff/struct.ZonedDateTime.html\" rel=\"nofollow ugc noopener\"><code>ZonedDateTime</code></a></li></ul>\n<p>When should you use each one versus the other?</p>\n<p>To a first approximation, if you <em>can</em> use a <code>ZonedDateTime</code>, then that is\nprobably the type you want to reach for. It represents a specific instant in\ntime in a particular geographic location. That is, it has both a <code>Timestamp</code>\nand a <a href=\"https://docs.rs/jiff/1.*/jiff/tz/struct.TimeZone.html\" rel=\"nofollow ugc noopener\"><code>TimeZone</code></a>.</p>\n<p>If you only ever need to work in UTC or just deal with system time, then a\n<code>Timestamp</code> is probably the right choice. This is useful for representing a\nspecific instant in time that is not connected to any time zone.</p>\n<p>A <code>civil::DateTime</code> is useful in contexts where you don’t care about a specific\ninstant in time and when calcuations should be done independent of time zone.\nFor example, when parsing datetime information from a user interface datetime\npicker.</p>\n<p>Remember that both a <code>civil::DateTime</code> and a <code>Timestamp</code> can be converted to a\n<code>ZonedDateTime</code> by supplying a time zone.</p>\n<h2 id=\"span-manipulation\">Span Manipulation</h2>\n<p>We’ve already seen how to add spans to datetime values and how to get spans\nas a difference between datetime values. But we haven’t yet explored the APIs\navailable on a <code>Span</code> itself.</p>\n<p>First and foremost, we can build a <code>Span</code> through its constructor, which\nreturns a <code>Span</code> with all of its units set to <code>0</code>:</p>\n<pre><code>use jiff::Span;\n\nlet span = Span::new();</code></pre>\n<p>A <code>Span</code> is both <code>Copy</code> and immutable. We can create new spans through method\nchaining:</p>\n<pre><code>let span = Span::new().hours(1).minutes(30);\nassert_eq!(span.to_string(), &quot;PT1H30M&quot;);</code></pre>\n<p>Or we can use the <code>ToSpan</code> convenience trait, which adds methods on integer\ntypes for constructing spans:</p>\n<pre><code>use jiff::ToSpan;\n\nlet span = 1.hour().minutes(30);\nassert_eq!(span.to_string(), &quot;PT1H30M&quot;);</code></pre>\n<p>Note though that methods like <code>Span::hours</code> and <code>ToSpan::hours</code> will panic\nwhen the integer is outside the limits of what <code>Span</code> supports. This is fine\nwhen your spans are literals in your program, since a panic would indicate a\nbug. But if your inputs come from an end user, it’s better to use fallible\nmethods:</p>\n<pre><code>let span = Span::new().try_hours(1)?.try_minutes(30)?;\nassert_eq!(span.to_string(), &quot;PT1H30M&quot;);</code></pre>\n<p>Spans preserve each individual unit value. This means that 90 minutes and 1\nhour 30 minutes, while they represent the same duration, are actually different\nvalues in memory:</p>\n<pre><code>let span1 = 1.hour().minutes(30);\nlet span2 = 90.minutes();\nassert_eq!(span1.to_string(), &quot;PT1H30M&quot;);\nassert_eq!(span2.to_string(), &quot;PT90M&quot;);</code></pre>\n<p>This permits callers maximum flexibility when it comes to representing\ndurations. This makes it possible to represent durations in a specific unit\neven when they add up to larger units. For example, the runtime duration of\nfilms is typically conveyed in minutes, even when the runtime exceeds one hour.\nThis can be adjusted programmatically using <code>Span::round</code>:</p>\n<pre><code>use jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span1 = 1.hour().minutes(30);\n    let span2 = span1.round(SpanRound::new().largest(Unit::Minute))?;\n    assert_eq!(span2.to_string(), &quot;PT90M&quot;);\n\n    Ok(())\n}</code></pre>\n<p>You can go the other way as well:</p>\n<pre><code>use jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span1 = 90.minutes();\n    let span2 = span1.round(SpanRound::new().largest(Unit::Hour))?;\n    assert_eq!(span2.to_string(), &quot;PT1H30M&quot;);\n\n    Ok(())\n}</code></pre>\n<p>Neither of these examples do actual rounding, despite the name of the API.\nInstead, since we’re only setting the largest unit, this API is doing unit\nbalancing. Unit balancing is when all unit values rollover into larger units\nup until the largest configured unit. This works even for calendar units too,\nbut you need to provide a relative date:</p>\n<pre><code>use jiff::{civil, SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 2756.hours();\n    let dt = civil::date(2020, 1, 1).at(0, 0, 0, 0);\n    let round = SpanRound::new().largest(Unit::Year).relative(dt);\n    assert_eq!(span.round(round)?.to_friendly(), &quot;3mo 23d 20h&quot;);\n    Ok(())\n}</code></pre>\n<p>Without a relative date, it’s not possible to know how many hours are in a\nsingle month. That is, once calendar units are involved, a span cannot be\ninterpreted as a physical duration of time until some context is applied.</p>\n<p>The same even applies to days themselves, since days can sometimes be more or\nless than 24 hours. Take the above example. What happens if we use a zoned\ndatetime as our relative date instead?</p>\n<pre><code>use jiff::{civil, SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 2756.hours();\n    let zdt = civil::date(2020, 1, 1).at(0, 0, 0, 0).in_tz(&quot;Europe/Rome&quot;)?;\n    let round = SpanRound::new().largest(Unit::Year).relative(&amp;zdt);\n    assert_eq!(span.round(round)?.to_friendly(), &quot;3mo 23d 21h&quot;);\n    Ok(())\n}</code></pre>\n<p>Notice that the duration’s hour component changed from <code>20</code> to <code>21</code>. Why?\nBecause we started with 2756 hour in both cases and because <code>2020-03-29</code> in\nRome was only 23 hours long (in a move from standard time to daylight saving\ntime). That means that one of those days in <code>3mo 23d</code> was only 23 hours long.\nSo an extra hour needed to be added to make up for it.</p>\n<p>The <code>round</code> API can also do actual rounding:</p>\n<pre><code>use jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 2.hours().minutes(30);\n    let round = SpanRound::new().smallest(Unit::Hour);\n    assert_eq!(span.round(round)?.to_friendly(), &quot;3h&quot;);\n    Ok(())\n}</code></pre>\n<p>You can also change its rounding mode from the default (“half-expand”, or like\nyou were taught rounding in school) to truncation (or one of several other\nmodes):</p>\n<pre><code>use jiff::{RoundMode, SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 2.hours().minutes(30);\n    let round = SpanRound::new().smallest(Unit::Hour).mode(RoundMode::Trunc);\n    assert_eq!(span.round(round)?.to_friendly(), &quot;2h&quot;);\n    Ok(())\n}</code></pre>\n<p>One can also specify a rounding increment to round to the nearest unit value.\nFor example, to the nearest half-hour:</p>\n<pre><code>use jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 2.hours().minutes(31);\n    let round = SpanRound::new().smallest(Unit::Minute).increment(30);\n    assert_eq!(span.round(round)?.to_friendly(), &quot;2h 30m&quot;);\n    Ok(())\n}</code></pre>\n<p>Because a <code>Span</code> value cannot easily be compared correctly based purely on its\nvalue in memory, a dedicated comparison <a href=\"https://docs.rs/jiff/1.*/jiff/struct.Span.html#method.compare\" rel=\"nofollow ugc noopener\"><code>Span::compare</code></a> routine is provided:</p>\n<pre><code>let span1 = 2.hours();\nlet span2 = 120.minutes();\nassert!(span1.compare(span2)?.is_eq());</code></pre>\n<p>Also, one can convert a <code>Span</code> to a floating point value in terms of any unit.\nFor example:</p>\n<pre><code>use jiff::{ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 90.minutes();\n    assert_eq!(span.total(Unit::Hour)?, 1.5);\n    Ok(())\n}</code></pre>\n<p>Converting to calendar units requires a relative date for the same reasons\ndiscussed above:</p>\n<pre><code>use jiff::{civil, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 24.hours();\n    assert_eq!(\n        span.total((Unit::Month, civil::date(2026, 6, 1)))?,\n        0.03333333333333333\n    );\n    assert_eq!(\n        span.total((Unit::Month, civil::date(2026, 7, 1)))?,\n        0.03225806451612903\n    );\n    Ok(())\n}</code></pre>\n<h2 id=\"conclusion\">Conclusion</h2>\n<p>So far, we’ve explored a good chunk of Jiff’s API. We didn’t talk about every\nnook and cranny, but I think we’ve covered the most important pieces.</p>\n<p>We’ll wrap up by briefly discussing motivation and inspiration.</p>\n<h3 id=\"motivation\">Motivation</h3>\n<p>Whenever I needed datetime handling in Rust, I always got confused. Should I\nuse <code>chrono</code> or <code>time</code>? How do I get my local time from a timestamp? How do I\nuse my system’s time zone database? How do I do calendar arithmetic?</p>\n<p>Before I started working on Jiff, this confusion got annoying enough for me to\nconsider writing my own crate. I felt like the APIs of both <code>chrono</code> and <code>time</code>\ncould be improved upon. I personally found the domain quite interesting and so\nset out to build something better.</p>\n<p>Why not improve on an existing solution, like <code>chrono</code> or <code>time</code>, instead of\nadding yet another choice into the ecosystem? I do think there are material\ndownsides of having too many choices, but I had concluded that both <code>chrono</code>\nand <code>time</code> (in 2024) had reached a local maximum. Moreover, in 2024, I was not\nan expert in datetime handling. It took building a datetime library to become\none. So convincing crate maintainers to go in a radically different direction\nwould have been a tall order.</p>\n<p>Jiff’s <a href=\"https://docs.rs/jiff/1.*/jiff/_documentation/design/index.html\" rel=\"nofollow ugc noopener\">design</a> and <a href=\"https://docs.rs/jiff/1.*/jiff/_documentation/comparison/index.html\" rel=\"nofollow ugc noopener\">comparison</a> documentation contain much more detail\nregarding the motivation and specific examples between Jiff, <code>chrono</code> and\n<code>time</code>.</p>\n<h3 id=\"inspiration\">Inspiration</h3>\n<p>Jiff is heavily inspired by <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal\" rel=\"nofollow ugc noopener\">Temporal</a>, which is JavaScript’s standard library\nsolution for date and time management. Jiff inherits API design, functionality\nand even parsing/formatting of datetime values. Note though that Jiff is not\nand does not aim to be a 100% compatible implementation of the Temporal\nspecification. Jiff is meant to be a Rust ecosystem library first and foremost.</p>\n<p>With that said, if you’re familiar with Temporal and Rust, then it’s likely\nyou’ll find Jiff to be a relatively straightforward translation of Temporal’s\nAPI to Rust. This example shows how to use Temporal to round a calendar span\nto the nearest number of days relative to a date:</p>\n<pre><code>const duration = Temporal.Duration.from({ months: 1, days: 1, hours: 1 });\nconst roundedDuration = duration.round({\n  largestUnit: &quot;days&quot;,\n  smallestUnit: &quot;days&quot;,\n  relativeTo: Temporal.PlainDateTime.from(&quot;2022-01-01&quot;),\n});\nconsole.log(roundedDuration); // &quot;P32D&quot;</code></pre>\n<p>And here’s the equivalent operation in Jiff:</p>\n<pre><code>use jiff::{SpanRound, ToSpan, Unit};\n\nfn main() -&gt; anyhow::Result&lt;()&gt; {\n    let span = 1.month().days(1).hours(1);\n    let rounded_span = span.round(\n        SpanRound::new()\n            .largest(Unit::Day)\n            .smallest(Unit::Day)\n            .relative(&quot;2022-01-01&quot;.parse::&lt;jiff::civil::Date&gt;()?),\n    )?;\n    assert_eq!(rounded_span.to_string(), &quot;P32D&quot;);\n    Ok(())\n}</code></pre>\n<p>The main difference between these examples is that Jiff’s duration type is\nnamed <code>Span</code> instead of <code>Duration</code>. This was done to avoid confusion with\nRust’s standard library <code>std::time::Duration</code> type.</p>\n<p>Here are some other differences:</p>\n<ul><li><p>Temporal’s <code>Instant</code> type in Jiff is named <code>Timestamp</code> in order to avoid</p><p>confusion with Rust’s standard library <code>std::time::Instant</code> type.</p></li><li>Temporal’s “plain” date and time types are called “civil” in Jiff.</li><li>Jiff only supports the Gregorian calendar.</li><li><p>Jiff’s datetime range only extends to +/- 9999, whereas Temporal’s range is</p><p>larger.</p></li></ul>\n<p>It’s easy to say that without Temporal, Jiff wouldn’t exist in its current\nform today.</p>","headings":[{"level":1,"text":"Jiff 1.0: A datetime library for Rust","id":"jiff-1-0-a-datetime-library-for-rust"},{"level":2,"text":"Table of Contents","id":"table-of-contents"},{"level":2,"text":"The Jiff 1.0 Commitment","id":"the-jiff-1-0-commitment"},{"level":2,"text":"Introduction","id":"introduction"},{"level":3,"text":"Follow Along","id":"follow-along"},{"level":3,"text":"Terms","id":"terms"},{"level":3,"text":"The DateTime Onion","id":"the-datetime-onion"},{"level":3,"text":"Defining a time zone","id":"defining-a-time-zone"},{"level":3,"text":"Durations","id":"durations"},{"level":3,"text":"When should I use Jiff?","id":"when-should-i-use-jiff"},{"level":2,"text":"Parsing and Formatting","id":"parsing-and-formatting"},{"level":3,"text":"FromStr and Display","id":"fromstr-and-display"},{"level":3,"text":"The “friendly” Duration Format","id":"the-friendly-duration-format"},{"level":3,"text":"strptime and strftime","id":"strptime-and-strftime"},{"level":3,"text":"The jiff::fmt module","id":"the-jiff-fmt-module"},{"level":3,"text":"Locale Sensitive Formatting via ICU4X Integration","id":"locale-sensitive-formatting-via-icu4x-integration"},{"level":2,"text":"Date Manipulation","id":"date-manipulation"},{"level":3,"text":"Date Basics","id":"date-basics"},{"level":3,"text":"Date Arithmetic","id":"date-arithmetic"},{"level":3,"text":"Date Rounding","id":"date-rounding"},{"level":3,"text":"Other Calendars","id":"other-calendars"},{"level":3,"text":"Which DateTime Type Do I Use?","id":"which-datetime-type-do-i-use"},{"level":2,"text":"Span Manipulation","id":"span-manipulation"},{"level":2,"text":"Conclusion","id":"conclusion"},{"level":3,"text":"Motivation","id":"motivation"},{"level":3,"text":"Inspiration","id":"inspiration"}]}}