chrono
Date and time library for Rust covering timezones, formatting, parsing, and calendar arithmetic.
Official Documentation ↗v0.4. Check the official docs for the latest API surface.Installation
cargo add chrono --features serdeMethods
No methods match this filter.
Date and time library for Rust covering timezones, formatting, parsing, and calendar arithmetic.
Overview
chrono is the date-time workhorse for Rust: DateTime values parameterized by timezone, Utc, Local, FixedOffset, formatting and parsing with strftime specifiers plus RFC formats, and Duration arithmetic for spans.
Naive types model wall time without offsets for interop with databases, while aware types convert across zones safely. The serde feature integrates timestamps into JSON APIs, and date components, weeks, ordinals, are available for calendar-level logic.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
Utc::now / Local::now— Current time with explicit timezone: UTC for storage, Local for display.parse_from_rfc3339— Parses ISO 8601 / RFC 3339 timestamps including their offset into an aware value.format— Formats timestamps with strftime-style specifiers or fixed RFC helpers.Duration arithmetic— Calendar-unit arithmetic on datetimes and measuring spans between two values.
Usage Notes
- Standardize on DateTime
in storage and convert only at the presentation edge. - Parse external timestamps with parse_from_rfc3339 so offsets never get guessed.
- Prefer to_rfc3339 in APIs; it is unambiguous and sortable lexicographically.
Common Pitfalls
- Adding Duration::days across a DST transition lands on a different wall-clock second.
- Mixing NaiveDateTime and DateTime without an explicit timezone loses offsets silently.
- Formatting with %Z on a FixedOffset prints the offset, not a zone name.
FAQ
- Naive or aware datetimes?
- Naive values, NaiveDateTime, carry no offset and suit columns known to be UTC or purely local wall time. DateTime<Tz> carries the offset and converts correctly. Store aware UTC, convert at display, and parse external strings with parse_from_rfc3339.
- Why are month arithmetic and Duration separate?
- Duration is a fixed number of seconds, so months have no single length. chrono offers Duration::days and weeks as fixed spans; month-aware shifting belongs to date arithmetic, Date::with_month, or higher-level calendars.
- How do I serialize datetimes with serde?
- Enable the serde feature: DateTime<Utc> serializes as RFC 3339 by default. Use #[serde(with = "chrono::serde::ts_seconds")] for epoch numbers, and confirm both sides agree, mixed string and number formats break round-trips.
Report a problem with this API docOpens a pre-filled issue on GitHub.