time Rust Library

repository·main·Indexed 23 days ago

https://github.com/time-rs/time

A comprehensive date and time library for Rust (v0.3.55) providing safe and efficient time manipulation, parsing, and formatting. It is fully interoperable with the standard library and mostly compatible with #![no_std]. The library includes the time-macros crate for compile-time constants and format descriptions, as well as extension traits like InstantExt, NumericalDuration, and NumericalStdDuration for enhanced arithmetic and duration construction.

Tokens
11.2K
Snippets
19
Records
47
Agent score
79%

What's inside time

  1. Overview of the time crate

    main
    The time crate is a date and time library for Rust. It provides robust tools for handling time-related operations, including parsing, formatting, and manipulating dates and times. For detailed API documentation and guides, refer to the official docs.rs or the time book.
  2. Minimum Rust version policy

    main

    The time crate follows a rolling minimum supported Rust version (MSRV) policy. It is guaranteed to compile with the latest stable release of Rust and the two prior minor releases.

    Note that the MSRV may be bumped up to one of those three versions to provide user benefits, or bumped down to four minor releases prior to the most recent stable release to improve maintainability.

  3. Use `PlainDateTime` and `SignedDuration` aliases

    main

    The crate provides type aliases for backward compatibility, but these are expected to be removed in a future breaking release. When writing new code, you should use the primary types instead.

    • Use PlainDateTime instead of PrimitiveDateTime.
    • Use SignedDuration instead of Duration.
  4. Use `time::Instant` for measuring elapsed time

    main

    An Instant is a measurement of a monotonically non-decreasing clock. It is an opaque type used primarily for measuring benchmarks or timing how long an operation takes.

    Key Characteristics:

    • Monotonicity: Instants are guaranteed to be no less than any previously measured instant, but they are not guaranteed to be steady (ticks may vary in length).
    • Opaque: You cannot extract
    // Note: This API is deprecated. Use std::time::Instant instead.
    # #![expect(deprecated)]
    # use time::Instant;
    # use std::thread;
    # use std::time::Duration as StdDuration;
    # use time::ext::NumericalStdDuration;
    let instant = Instant::now();
    thread::sleep(1.std_milliseconds());
    assert!(instant.elapsed() >= 1.milliseconds());
  5. Use FormatDescriptionV3 for formatting and parsing

    main

    In time, FormatDescriptionV3 is the primary type used to describe how to format and parse date/time types. It is an opaque type designed for forwards compatibility and performance optimizations.

    Because it is opaque, you cannot construct it directly using a struct literal. Instead, you should use one of the following methods:

    1. The format_description! macro: Use this macro with version=3 to create a description from a format string.
    2. Parsing methods: The parse_borrowed and parse_owned methods return a FormatDescriptionV3 instance.

    If you have a FormatDescriptionV3 with a lifetime (e.g., it contains borrowed literals), you can convert it to an owned version using .to_owned() (requires the alloc feature).

  6. Understand the ComponentProvider trait

    main

    The ComponentProvider trait is an internal abstraction used by the formatting engine to extract specific date, time, offset, or timestamp components from various time types. While the trait itself is pub(crate) and not directly intended for end-user implementation, understanding it helps clarify how different types like Date, Time, OffsetDateTime, and Timestamp behave when being formatted.

    Key capabilities of a ComponentProvider include:

    • Date components: Day, month, ordinal, weekday, ISO week, etc.
    • Time components: Hour, minute, period (AM/PM), second, nanosecond.
    • Offset components: Sign, UTC status, and hour/minute/second components of the offset.
    • Timestamp components: Unix timestamps in seconds, milliseconds, microseconds, and nanoseconds.

    Types implement this trait to expose their underlying data to the formatter, often using a State type to cache computed values (like a Date extracted from a Timestamp) to avoid redundant calculations during a single formatting operation.

  7. Understand Format Description Components

    main

    Format descriptions in time are composed of several types of items that define how date and time data should be parsed or formatted:

    • Literal: A fixed sequence of bytes or a UTF-8 string.
    • Component: A named part of a date/time (e.g., day, hour, month) that can have specific modifiers (e.g., padding, repr).
    • Optional: A component wrapped in optional(...) brackets. It can optionally include a format modifier to control how the optionality is handled.
    • First: A component using first(...) brackets that allows choosing the first matching format description from a list of provided options.

    Note that for v3 format descriptions, all literals must be valid UTF-8.

  8. Configure `time` crate feature flags

    main

    The time crate uses Cargo features to enable or disable functionality. Most features are disabled by default. Use these flags in your Cargo.toml to add support for parsing, formatting, serialization, or specific random number generator versions.

    Core Features

    • std: Enables standard library support (enabled by default).
    • alloc: Enables dynamic memory allocation (enabled by default via std).
    • macros: Enables macros for compile-time verification and intuitive syntax.
    • formatting: Enables formatting of most structs (implicitly enables std).
    • parsing: Enables parsing of most structs.
    • local-offset: Enables methods to obtain the system's UTC offset (implicitly enables std).
    • large-dates: Increases supported year range from ±9999 to ±999,999. Note: this may impact performance and introduce parsing ambiguities.
    • serde: Enables serde support for all types.
    • serde-human-readable: Allows serde to use human-readable formats (implicitly enables serde, formatting, and parsing). Note: Libraries should avoid enabling this; it is intended for end-user applications.
    • wasm-bindgen: Enables support for converting JavaScript dates and obtaining UTC offsets from JS.

    Random Number Generation (rand)

    To avoid pulling in all versions of rand, it is recommended to enable the specific version you need directly:

    • rand08: Supports rand 0.8.
    • rand09: Supports rand 0.9.
    • rand010: Supports rand 0.10.
    • rand: Enables support for all three versions (not recommended unless necessary).
  9. Migrate from `time::Instant` to `std::time::Instant`

    main

    The time::Instant struct is deprecated as of version 0.3.35. To ensure compatibility and follow current best practices, you should stop using time::Instant and instead import std::time::Instant along with the time::ext::InstantExt trait for extended functionality.

    Deprecation Note:

    • Since: 0.3.35
    • Recommendation: import std::time::Instant and time::ext::InstantExt instead
  10. Create `SignedDuration`s from floating point values

    main

    The NumericalDuration trait is implemented for f64, allowing you to create durations from fractional numbers.

    Warning: When calling these methods on floating point values, any remainder of the floating point value will be truncated. Because floating point numbers are inherently imprecise, use them with caution for high-precision timing requirements.

    use time::ext::NumericalDuration;
    
    // Example of using f64 (truncation occurs internally)
    let duration = 1.5_f64.seconds(); 
  11. Convert between `Month` and numeric types

    main

    You can convert a Month to its corresponding u8 value (1-12) or attempt to create a Month from a u8 value.

    • To u8: Use u8::from(month) or month as u8.
    • From u8: Use Month::try_from(value) or value.try_into(). This will return an error if the value is not in the range 1-12.
    • From str: Use s.parse::<Month>(). The string must match the full month name (e.g., "January").
  12. Perform arithmetic and replacements on UtcDateTime

    main

    Arithmetic

    • checked_add(duration) / checked_sub(duration): Returns Option<Self>, None on overflow.
    • saturating_add(duration) / saturating_sub(duration): Returns Self, saturating at MIN or MAX on overflow.

    Component Replacement

    These methods return a new UtcDateTime and do not mutate the original:

    • replace_time(time): Replaces the time component.
    • replace_date(date): Replaces the date component.
    • replace_year(year): Returns Result<Self, error::ComponentRange>.
    • replace_month(month): Returns Result<Self, error::ComponentRange>.
    • replace_day(day): Returns Result<Self, error::ComponentRange>.
    • replace_ordinal(ordinal): Returns Result<Self, error::ComponentRange>.
    • replace_hour(hour): Returns Result<Self, error::ComponentRange>.
    • replace_minute(minute): Returns Result<Self, error::ComponentRange>.

    Truncation

    • truncate_to_day(): Sets time to midnight.
    • truncate_to_hour(): Sets minute, second, and subsecond to zero.
    • truncate_to_minute(): Sets second and subsecond to zero.