time Rust Library
repository·main·Indexed 23 days ago
https://github.com/time-rs/timeA 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.
What's inside time
Minimum Rust version policy
mainThe
timecrate 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.
Use `PlainDateTime` and `SignedDuration` aliases
mainThe 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
PlainDateTimeinstead ofPrimitiveDateTime. - Use
SignedDurationinstead ofDuration.
- Use
Use `time::Instant` for measuring elapsed time
mainAn
Instantis 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());Use FormatDescriptionV3 for formatting and parsing
mainIn
time,FormatDescriptionV3is 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:
- The
format_description!macro: Use this macro withversion=3to create a description from a format string. - Parsing methods: The
parse_borrowedandparse_ownedmethods return aFormatDescriptionV3instance.
If you have a
FormatDescriptionV3with a lifetime (e.g., it contains borrowed literals), you can convert it to an owned version using.to_owned()(requires theallocfeature).- The
Understand the ComponentProvider trait
mainThe
ComponentProvidertrait 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 ispub(crate)and not directly intended for end-user implementation, understanding it helps clarify how different types likeDate,Time,OffsetDateTime, andTimestampbehave when being formatted.Key capabilities of a
ComponentProviderinclude:- 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
Statetype to cache computed values (like aDateextracted from aTimestamp) to avoid redundant calculations during a single formatting operation.Understand Format Description Components
mainFormat descriptions in
timeare 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 aformatmodifier 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
v3format descriptions, all literals must be valid UTF-8.Configure `time` crate feature flags
mainThe
timecrate uses Cargo features to enable or disable functionality. Most features are disabled by default. Use these flags in yourCargo.tomlto 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 viastd).macros: Enables macros for compile-time verification and intuitive syntax.formatting: Enables formatting of most structs (implicitly enablesstd).parsing: Enables parsing of most structs.local-offset: Enables methods to obtain the system's UTC offset (implicitly enablesstd).large-dates: Increases supported year range from ±9999 to ±999,999. Note: this may impact performance and introduce parsing ambiguities.serde: Enablesserdesupport for all types.serde-human-readable: Allowsserdeto use human-readable formats (implicitly enablesserde,formatting, andparsing). 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: Supportsrand0.8.rand09: Supportsrand0.9.rand010: Supportsrand0.10.rand: Enables support for all three versions (not recommended unless necessary).
Migrate from `time::Instant` to `std::time::Instant`
mainThe
time::Instantstruct is deprecated as of version 0.3.35. To ensure compatibility and follow current best practices, you should stop usingtime::Instantand instead importstd::time::Instantalong with thetime::ext::InstantExttrait for extended functionality.Deprecation Note:
- Since:
0.3.35 - Recommendation:
import std::time::Instant and time::ext::InstantExt instead
- Since:
Create `SignedDuration`s from floating point values
mainThe
NumericalDurationtrait is implemented forf64, 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();Convert between `Month` and numeric types
mainYou can convert a
Monthto its correspondingu8value (1-12) or attempt to create aMonthfrom au8value.- To
u8: Useu8::from(month)ormonth as u8. - From
u8: UseMonth::try_from(value)orvalue.try_into(). This will return an error if the value is not in the range 1-12. - From
str: Uses.parse::<Month>(). The string must match the full month name (e.g., "January").
- To
Perform arithmetic and replacements on UtcDateTime
mainArithmetic
checked_add(duration)/checked_sub(duration): ReturnsOption<Self>,Noneon overflow.saturating_add(duration)/saturating_sub(duration): ReturnsSelf, saturating atMINorMAXon overflow.
Component Replacement
These methods return a new
UtcDateTimeand do not mutate the original:replace_time(time): Replaces the time component.replace_date(date): Replaces the date component.replace_year(year): ReturnsResult<Self, error::ComponentRange>.replace_month(month): ReturnsResult<Self, error::ComponentRange>.replace_day(day): ReturnsResult<Self, error::ComponentRange>.replace_ordinal(ordinal): ReturnsResult<Self, error::ComponentRange>.replace_hour(hour): ReturnsResult<Self, error::ComponentRange>.replace_minute(minute): ReturnsResult<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.