Jiff

repository·master·Indexed 25 days ago

https://github.com/burntsushi/jiff

A high-level datetime library for Rust designed for high performance and misuse resistance. Inspired by the TC39 Temporal proposal, it provides DST-aware arithmetic, seamless IANA Time Zone Database integration, and lossless Serde serialization. The ecosystem includes specialized crates for Diesel (jiff-diesel), SQLx (jiff-sqlx), ICU conversions (jiff-icu), and embedded time zone data (jiff-tzdb, jiff-static, jiff-tzdb-platform).

Tokens
20.4K
Snippets
46
Records
117
Agent score
84%

What's inside jiff

  1. Platform support matrix for Jiff

    master

    Unix

    • Current Time: Supported via Rust stdlib.
    • IANA Database: Automatically detects /usr/share/zoneinfo. Use TZDIR if located elsewhere. Use tzdb-bundle-always if the database is missing (e.g., minimal Docker).
    • System Time Zone: Discovered via /etc/localtime symbolic link metadata. If /etc/localtime is not a symlink, Jiff reads it as a TZif file, which may prevent lossless serialization of the IANA identifier.

    Android

    • Current Time: Supported via Rust stdlib.
    • IANA Database: Uses a 'Concatenated Time Zone Database' format. Jiff supports this on all platforms.
    • System Time Zone: Discovered via the persist.sys.timezone property.

    Windows

    • Current Time: Supported via Rust stdlib.
    • IANA Database: Automatically bundled via tzdb-bundle-platform (enabled by default). Can be overridden using TZDIR.
    • System Time Zone: Discovered via GetDynamicTimeZoneInformation and mapped to IANA identifiers using CLDR XML data.

    WASM

    • wasm32-unknown-emscripten: Current time supported via stdlib. IANA database bundled via tzdb-bundle-platform. System time zone is unsupported.
    • wasm32-wasi*: Current time supported via stdlib. IANA database bundled via tzdb-bundle-platform. System time zone can be set via TZ environment variable.
    • wasm{32,64}-unknown-unknown:
      • Default: Current time panics; IANA database is bundled; System time zone is unsupported.
      • With js feature: Current time uses Date.now; System time zone uses Intl.DateTimeFormat.
  2. Use jiff-icu for ICU datetime conversions

    master
    The jiff-icu crate provides functionality to convert between jiff datetime types and the datetime types found in the icu crate. This allows you to extend jiff with features not natively supported, such as non-Gregorian calendars and datetime localization.
  3. Compare Jiff with other Rust datetime libraries

    master

    Jiff is designed as a general-purpose datetime library that addresses perceived limitations in existing Rust crates like chrono, time, hifitime, and icu.

    Key differentiators include:

    • Time Zone Handling: Unlike chrono (which requires external crates like chrono-tz or tzfile) or time (which has limited IANA support), Jiff provides full IANA Time Zone Database support out of the box. It abstracts the discovery method, allowing transparent use of either system databases or embedded data.
    • Serialization: Jiff follows [RFC 9557] to support embedding IANA time zone identifiers in serialized representations (e.g., 2024-07-21T17:11-04[America/New_York]), ensuring lossless serialization/deserialization of time zone-aware datetimes. chrono typically loses the time zone and only preserves the offset.
    • API Ergonomics: Jiff provides consistent methods across different datetime types. For example, methods available on civil::Date are also available on civil::DateTime and Zoned. This simplifies transitions between civil and time zone-aware datetimes (e.g., using Zoned::tomorrow instead of manual conversion steps).
    • Error Handling: Jiff prefers returning Result<T, E> with contextualized, human-readable error messages over Option<T> to avoid the need for manual error conversion.
    • Specialized Types: Jiff includes a dedicated Timestamp type for Unix epoch seconds, providing a standard way to handle timestamps that is more integrated than DateTime<Utc> in other libraries.
  4. Understand the difference between Timestamp and Instant

    master
    In Jiff, a Timestamp represents a point in time from the system clock (similar to std::time::SystemTime). It is not a monotonic clock. This is distinct from a monotonic Instant (like std::time::Instant), which is used for measuring elapsed time and is guaranteed to never move backwards.
  5. Understand the purpose of jiff-core

    master

    jiff-core is a low-level dependency of the jiff crate. It provides core datetime primitives including:

    • Civil datetime algorithms
    • Conversions to and from Unix timestamps
    • Low-level time zone operations

    Note: This crate is primarily an implementation detail of jiff to improve compile times and share code with jiff-static. It does not include a time zone aware datetime type, formatting, parsing, Serde integration, or calendar durations. It is not intended to provide a stable API, and its semver evolution is independent of jiff.

  6. Use jiff-tzdb-platform for embedded IANA Time Zone Database

    master

    The jiff-tzdb-platform crate is an optional dependency for jiff that embeds the entire IANA Time Zone Database (specifically the TZif binary format) directly into your compiled binary.

    This is primarily used on platforms that lack a system-provided copy of the IANA Time Zone Database, such as Windows. It acts as a target-dependent proxy to ensure the necessary time zone data is available without relying on the host operating system's files.

  7. Zone-Aware Calendar Arithmetic

    master

    Jiff supports adding non-uniform units (like days) to time zone aware datetimes. It handles DST transitions (23-hour or 25-hour days) correctly so that adding a day preserves the expected civil time. It also allows consistent conversion between calendar units (days) and clock units (hours) using Span.

    use jiff::{civil::date, ToSpan, Unit};
    
    fn main() -> anyhow::Result<()> {
        let zdt1 = date(2024, 3, 9).at(21, 0, 0, 0).in_tz("America/New_York")?;
        let zdt2 = zdt1.checked_add(1.day())?;
    
        // Even though 2 o'clock didn't occur on 2024-03-10, adding 1 day
        // returns the same civil time the next day.
        assert_eq!(zdt2.to_string(), "2024-03-10T21:00:00-04:00[America/New_York]");
        // The span of time is 23 hours:
        assert_eq!(&zdt2 - &zdt1, 23.hours().fieldwise());
        // But if you ask for the span in units of days, you get exactly 1:
        assert_eq!(zdt1.until((Unit::Day, &zdt2))?, 1.day().fieldwise());
    
        Ok(())
    }
  8. Automatic Time Zone Database Integration

    master

    Jiff automatically integrates with your system's Time Zone Database.

    • On Unix: It typically uses /usr/share/zoneinfo.
    • On Windows: It defaults to using jiff-tzdb, which embeds the entire database into your binary.

    This allows you to convert civil time into absolute time in a specific time zone using the .in_tz() method.

    use jiff::civil::date;
    
    fn main() -> anyhow::Result<()> {
        let zdt = date(2024, 6, 30).at(9, 46, 0, 0).in_tz("America/New_York")?;
        assert_eq!(zdt.to_string(), "2024-06-30T09:46:00-04:00[America/New_York]");
        Ok(())
    }
  9. Enable environment interaction in Jiff

    master
    To allow Jiff to interact with the environment (e.g., reading environment variables or files), you must enable the std feature in your Cargo configuration. Without the std feature, Jiff cannot access system resources like the IANA Time Zone Database or environment variables.
  10. Bundle the IANA Time Zone Database into your binary

    master

    To ensure Jiff has access to the IANA Time Zone Database without relying on the host system (useful for stripped-down Docker containers, Windows, or WASM), you can bundle the database into your compiled artifact using crate features:

    1. tzdb-bundle-always: This causes Jiff to depend on jiff-tzdb, embedding a complete copy of the IANA database into your binary. This is a recommended fallback if the system database is missing.
    2. tzdb-bundle-platform: A target-activated feature that automatically bundles the database on specific platforms like Windows and WASM. It is enabled by default for these targets.