### Install Cargo-fuzz Source: https://github.com/chronotope/chrono/blob/main/fuzz/README.md Installs the Cargo-fuzz tool, which is required for fuzzing. ```bash cargo install cargo-fuzz ``` -------------------------------- ### Create Naive Types Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Examples for creating NaiveDate, NaiveTime, and NaiveDateTime objects. ```rust NaiveDate::from_ymd_opt(2014, 7, 8) // Create ``` ```rust NaiveTime::from_hms_opt(9, 10, 11) ``` ```rust NaiveDateTime::new(date, time) ``` ```rust date.and_hms_opt(9, 10, 11) // Combine with time ``` ```rust date.and_utc() // To DateTime ``` ```rust date.and_local_timezone(Local) // To DateTime ``` -------------------------------- ### Calculate Start of Tomorrow Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Determine the start of tomorrow by adding one day to the naive date and then converting it to UTC. ```rust // Start of tomorrow let tomorrow_start = (dt.date_naive() + Days::new(1)).and_utc(); ``` -------------------------------- ### Format Datetimes Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Examples for formatting DateTime objects into various string representations. ```rust dt.to_string() // ISO 8601 ``` ```rust dt.to_rfc2822() // Email ``` ```rust dt.to_rfc3339() // RFC 3339 ``` ```rust dt.format("%Y-%m-%d").to_string() // Strftime ``` ```rust dt.format_localized("%A", Locale::fr_BE).to_string() // Localized ``` -------------------------------- ### Create Durations Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Examples for creating TimeDelta objects representing durations. ```rust TimeDelta::days(5) // Create ``` ```rust TimeDelta::hours(2) ``` ```rust TimeDelta::minutes(30) ``` ```rust TimeDelta::seconds(45) ``` ```rust TimeDelta::new(60, 500_000_000) // 60.5 seconds ``` ```rust TimeDelta::try_days(5) // Fallible ``` -------------------------------- ### now Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Gets the current local time. Requires the 'clock' feature. ```APIDOC ## now ### Description Returns the current local time. ### Function Signature `pub fn now() -> DateTime` ### Returns `DateTime` - Current local time ### Requires `clock` feature ### Example ```rust use chrono::Local; let now = Local::now(); println!("Current local time: {}", now); ``` ``` -------------------------------- ### Example Cargo.toml with Chrono, Serde, and Serde JSON Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md A sample Cargo.toml file demonstrating how to include Chrono with `std` and `serde` features, along with `serde` and `serde_json` dependencies, for applications requiring serialization. ```toml [package] name = "my-app" version = "0.1.0" edition = "2021" [dependencies] chrono = { version = "0.4", features = ["std", "serde"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" [dev-dependencies] proptest = "1.0" ``` -------------------------------- ### LocalResult Usage Example Source: https://github.com/chronotope/chrono/blob/main/_autodocs/07-types-reference.md Demonstrates how to handle the different outcomes of a timezone conversion using a match statement. ```rust match tz.with_ymd_and_hms(2014, 7, 8, 9, 10, 11) { LocalResult::Single(dt) => println!("Unambiguous: {}", dt), LocalResult::Ambiguous(dt1, dt2) => println!("Two possibilities: {} or {}", dt1, dt2), LocalResult::None => println!("Time does not exist"), } ``` -------------------------------- ### Get Weekday Number (Monday=1) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the weekday as a number, where Monday is 1 and Sunday is 7. Use this when you need a numerical representation of the day of the week starting from Monday. ```rust pub const fn number_from_monday(&self) -> u32 ``` -------------------------------- ### Parsing Datetimes Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Provides examples of parsing datetime strings using `FromStr`, `parse_from_str`, and specific RFC format parsers. ```rust // Using FromStr let dt: DateTime = "2014-11-28T12:00:09Z".parse().unwrap(); // Using parse_from_str let dt = DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z")?; // RFC formats let dt = DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900")?; let dt = DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00")?; ``` -------------------------------- ### Naive Time Access Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Get naive (timezone-unaware) representations of the DateTime. ```APIDOC ## Naive Time Access ### `naive_utc` Returns the UTC time as a `NaiveDateTime`. #### Returns * `NaiveDateTime` - UTC datetime without timezone ### `naive_local` Returns the local time as a `NaiveDateTime`. #### Returns * `NaiveDateTime` - Local datetime without timezone ``` -------------------------------- ### Project File Structure Source: https://github.com/chronotope/chrono/blob/main/_autodocs/README.md Illustrates the organizational structure of the Chrono documentation files, starting with the index and covering various aspects like datetime, timedelta, timezones, and common patterns. ```markdown ``` 00-index.md ← START HERE ├─ 01-datetime.md Core type reference ├─ 02-timedelta.md Duration handling ├─ 03-timezones.md Timezone implementations ├─ 04-naive-types.md Timezone-naive types ├─ 05-formatting-parsing.md Format & parse operations ├─ 06-traits-types.md Traits and supporting types ├─ 07-types-reference.md Complete type definitions ├─ 08-features-config.md Configuration & features ├─ 09-common-patterns.md Usage examples ├─ 10-quick-ref.md Quick lookup card ├─ 11-api-overview.md Architecture overview └─ README.md This file ``` ``` -------------------------------- ### Timezone Conversion Examples Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Illustrates converting a DateTime object to a fixed offset timezone and then to another timezone. Also shows how to represent a time in UTC. ```rust let utc = Utc::now(); // To fixed offset let tz = FixedOffset::east_opt(9 * 3600).unwrap(); let tokyo = utc.with_timezone(&tz); // Convert between any timezones let new_tz = FixedOffset::west_opt(5 * 3600).unwrap(); let in_new_tz = tokyo.with_timezone(&new_tz); // To same absolute moment in different timezone let as_utc = tokyo.with_timezone(&Utc); ``` -------------------------------- ### Get ISO Week Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the ISO week information from a NaiveDate. ```rust pub fn iso_week(&self) -> IsoWeek ``` -------------------------------- ### Error Handling Examples Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Shows common scenarios that result in errors or None values, such as invalid date components or parsing failures. ```rust NaiveDate::from_ymd_opt(2014, 2, 30) // None (invalid) ``` ```rust "2014-13-01".parse::() // Err(ParseError) ``` ```rust dt.checked_add_signed(d) // Option (overflow) ``` -------------------------------- ### Checking Minimum Supported Rust Version (MSRV) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md To verify compatibility, install the minimum supported Rust version (e.g., 1.62.0) and attempt to build the project with it. This ensures your environment meets Chrono's requirements. ```bash rustup install 1.62.0 cargo +1.62.0 build ``` -------------------------------- ### Example of Localized Date Formatting Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Demonstrates using `format_localized` with a specific locale (French, Belgium) to format a datetime object. Ensure the `unstable-locales` feature is enabled. ```rust use chrono::{prelude::*, Locale}; let dt = Utc.with_ymd_and_hms(2014, 11, 28, 12, 0, 9).unwrap(); assert_eq!( dt.format_localized("%A %e %B %Y", Locale::fr_BE).to_string(), "vendredi 28 novembre 2014" ); ``` -------------------------------- ### Common Chrono Imports Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Provides examples of common import patterns for the Chrono library. Includes a glob import for convenience and a detailed import for specific types and traits. ```rust // Everything you usually need use chrono::prelude::*; // Specific when needed use chrono::{ DateTime, Utc, Local, FixedOffset, NaiveDate, NaiveTime, NaiveDateTime, TimeDelta, Datelike, Timelike, Weekday, Month, Duration, // Type alias for TimeDelta }; ``` -------------------------------- ### Access Duration Values Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Shows how to get the number of days, seconds, or milliseconds from a duration. ```rust d.num_days() // i64 ``` ```rust d.num_seconds() // i64 ``` ```rust d.num_milliseconds() // i64 ``` ```rust d.is_zero() // bool ``` ```rust d.is_positive() // bool ``` ```rust d.abs() // Absolute value ``` -------------------------------- ### Calculate Tomorrow at the Same Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Add one day to a `DateTime` object to get the same time on the next day. ```rust // Tomorrow at same time let tomorrow = dt + TimeDelta::days(1); ``` -------------------------------- ### NaiveWeek Struct Source: https://github.com/chronotope/chrono/blob/main/_autodocs/07-types-reference.md Represents a week in a calendar, allowing for a custom start day. It does not span across year boundaries. ```APIDOC ## NaiveWeek Struct Represents a week in a calendar, allowing for a custom start day. It does not span across year boundaries. ### Properties - `date`: The `NaiveDate` representing a day within the week. - `start`: The `Weekday` on which the week starts. ### Methods - `first_day()`: Returns the first day of the week. - `last_day()`: Returns the last day of the week. ``` -------------------------------- ### Get Weekday Number (Sunday=0) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the weekday as a number, where Sunday is 0 and Saturday is 6. Use this when you need a numerical representation of the day of the week starting from Sunday. ```rust pub const fn number_from_sunday(&self) -> u32 ``` -------------------------------- ### Prelude Module Source: https://github.com/chronotope/chrono/blob/main/_autodocs/11-api-overview.md A module providing common types and traits for easy glob importing, simplifying common usage patterns. ```APIDOC ## Prelude Module ```rust pub mod prelude { pub use crate::{DateTime, Local, Locale}; pub use crate::{Datelike, Month, Timelike, Weekday}; pub use crate::{FixedOffset, Utc}; pub use crate::{NaiveDate, NaiveDateTime, NaiveTime}; pub use crate::{Offset, TimeZone}; pub use crate::{SecondsFormat}; pub use crate::{SubsecRound}; } ``` ### Description Most common types and traits for glob import. ``` -------------------------------- ### Import Conventions Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Demonstrates recommended import conventions for the Chrono library, including the prelude and specific type imports. ```rust // Prelude (recommended) use chrono::prelude::*; // Specific imports use chrono::{DateTime, NaiveDate, Utc, Local, TimeDelta, Datelike, Timelike}; use chrono::format::{strftime, parse}; ``` -------------------------------- ### Minimal Configuration for no_std Environments Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Use this configuration for minimal binary size in embedded systems or WASM. It provides naive types and fixed offset timezones but excludes formatting and current time functionality. ```toml [dependencies] chrono = { version = "0.4", default-features = false } ``` -------------------------------- ### Enable Alloc Feature Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enable the 'alloc' feature for string formatting and other allocation-dependent features. This requires an allocator to be available. ```toml [dependencies] chrono = { version = "0.4", features = ["alloc"] } ``` -------------------------------- ### Get Timezone Object Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Returns the timezone object used by this DateTime. ```rust pub fn timezone(&self) -> Tz ``` -------------------------------- ### Get Month Number (January=0) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the month as a number, where January is 0 and December is 11. Use this when you need a zero-indexed numerical representation of the month. ```rust pub const fn number_from_january(&self) -> u32 ``` -------------------------------- ### Import Prelude Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Import the necessary Chrono prelude for common types and traits. ```rust use chrono::prelude::*; ``` -------------------------------- ### Get Weekday Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the day of the week from a NaiveDate. ```rust pub fn weekday(&self) -> Weekday ``` -------------------------------- ### Get Year Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the year component from a NaiveDate. ```rust pub const fn year(&self) -> i32 ``` -------------------------------- ### Full-Featured Configuration with Serde and Locales Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enables all standard features plus JSON serialization support and localized date formatting. This is ideal for web applications and backends requiring comprehensive functionality. ```toml [dependencies] chrono = { version = "0.4", features = ["std", "serde", "unstable-locales"] } serde = { version = "1.0", features = ["derive"] } ``` -------------------------------- ### Enable Now Feature Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enable the 'now' feature to read the system time as a UNIX timestamp. This feature requires the 'std' feature. ```toml [dependencies] chrono = { version = "0.4", features = ["now"] } ``` -------------------------------- ### Get Day Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the day of the month (1-31) from a NaiveDate. ```rust pub const fn day(&self) -> u32 ``` -------------------------------- ### Get Month Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the month component (1-12) from a NaiveDate. ```rust pub const fn month(&self) -> u32 ``` -------------------------------- ### Formatting Datetimes Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Demonstrates standard and custom formatting of `DateTime` objects, including ISO 8601, RFC 2822, RFC 3339, and strftime-style formats. Also shows locale-specific formatting. ```rust let dt = Utc::now(); // Standard formats dt.to_string() // ISO 8601 with timezone dt.to_rfc2822() // Email format dt.to_rfc3339() // RFC 3339 / ISO 8601 // Custom format (strftime-style) dt.format("%Y-%m-%d %H:%M:%S").to_string() dt.format("%a %b %e %T %Y").to_string() // With locales (requires 'unstable-locales') dt.format_localized("%A %e %B %Y", Locale::fr_BE).to_string() ``` -------------------------------- ### Get ParseError Kind Source: https://github.com/chronotope/chrono/blob/main/_autodocs/05-formatting-parsing.md Returns the specific kind of parsing error encountered. ```rust pub const fn kind(&self) -> ParseErrorKind ``` -------------------------------- ### Get Timezone Offset Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Returns a reference to the timezone offset associated with the DateTime object. ```rust pub const fn offset(&self) -> &Tz::Offset ``` -------------------------------- ### Create Datetimes Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Demonstrates various methods for creating DateTime objects, including current time, from components, timestamps, and parsing strings. ```rust Utc::now() // Current UTC ``` ```rust Local::now() // Current local ``` ```rust Utc.with_ymd_and_hms(2014, 7, 8, 9, 10, 11) // From components ``` ```rust DateTime::from_timestamp(1500000000, 0) // From UNIX timestamp ``` ```rust "2014-11-28T12:00:09Z".parse::>() // Parse ISO 8601 ``` ```rust DateTime::parse_from_rfc2822("...") // Parse RFC 2822 ``` ```rust DateTime::parse_from_rfc3339("...") // Parse RFC 3339 ``` ```rust DateTime::parse_from_str("...", "%Y-%m-%d") // Parse custom format ``` -------------------------------- ### NaiveDate Construction from Components Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Creates a NaiveDate from year, month, and day. The `from_ymd_opt` function returns an Option and handles invalid dates by returning None, while `from_ymd` panics on invalid input. ```APIDOC ## NaiveDate::from_ymd_opt ### Description Creates a `NaiveDate` from year, month, and day. Returns `None` if the date is invalid. ### Method `from_ymd_opt` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust use chrono::NaiveDate; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); assert_eq!(date.year(), 2014); ``` ### Response #### Success Response (Option) - `NaiveDate` - The constructed date if valid. #### Response Example ```rust // Successful construction Some(NaiveDate { ... }) // Invalid date None ``` ## NaiveDate::from_ymd ### Description Creates a `NaiveDate` from year, month, and day. Panics if the date is invalid. ### Method `from_ymd` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust use chrono::NaiveDate; let date = NaiveDate::from_ymd(2014, 7, 8); assert_eq!(date.year(), 2014); ``` ### Response #### Success Response (NaiveDate) - `NaiveDate` - The constructed date. #### Response Example ```rust NaiveDate { ... } ``` ### Panics If the date components form an invalid date. ``` -------------------------------- ### Utc::now Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Gets the current time in UTC. Requires the 'now' feature to be enabled. ```APIDOC ## Utc::now ### Description Returns the current time in UTC. ### Method ```rust pub fn now() -> DateTime ``` ### Returns `DateTime` - Current UTC time ### Requires `now` feature ### Example ```rust use chrono::Utc; let now = Utc::now(); println!("Current UTC time: {}", now); ``` ``` -------------------------------- ### Duration Properties Source: https://github.com/chronotope/chrono/blob/main/_autodocs/02-timedelta.md Check if a duration is zero, positive, or negative, or get its absolute value. ```APIDOC ## is_zero ### Description Returns true if the duration is zero. ### Returns `bool` - True if zero ## is_positive ### Description Returns true if the duration is positive. ### Returns `bool` - True if > 0 ## is_negative ### Description Returns true if the duration is negative. ### Returns `bool` - True if < 0 ## abs ### Description Returns the absolute value of the duration. ### Returns `TimeDelta` - Duration with sign flipped if negative ### Panics If duration is the minimum value (cannot be negated) ### Example ```rust use chrono::TimeDelta; let positive = TimeDelta::seconds(60); let negative = TimeDelta::seconds(-60); assert_eq!(negative.abs(), positive); ``` ``` -------------------------------- ### Construct NaiveDate from Year, Month, Day (Panicking) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Creates a NaiveDate from year, month, and day components. Panics if the date is invalid. ```rust pub const fn from_ymd(year: i32, month: u32, day: u32) -> NaiveDate ``` -------------------------------- ### Get ISO Week Number Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Returns the ISO week number (1-53) from an IsoWeek struct. ```rust pub const fn week(&self) -> u32 ``` -------------------------------- ### Get NaiveDate Component from DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md The `date_naive` method returns the date component of a DateTime as a NaiveDate. ```rust use chrono::{DateTime, FixedOffset, NaiveDate}; let tz = FixedOffset::east_opt(3600).unwrap(); let dt = NaiveDate::from_ymd_opt(2020, 1, 1) .unwrap() .and_hms_opt(0, 0, 0) .unwrap() .and_local_timezone(tz) .unwrap(); assert_eq!(dt.date_naive(), NaiveDate::from_ymd_opt(2020, 1, 1).unwrap()); ``` -------------------------------- ### Get Next Month Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the next month. This method wraps around, so the successor of December is January. ```rust pub const fn succ(&self) -> Month ``` -------------------------------- ### Creating Datetimes Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Shows various methods for creating `DateTime` objects, including current time, from components, from timestamps, and from naive types. ```rust // Current time let now = Utc::now(); // requires 'now' feature let local = Local::now(); // requires 'clock' feature // From components let dt = Utc.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); // From timestamp let dt = DateTime::from_timestamp(1_500_000_000, 0).unwrap(); // From naive types let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); let time = NaiveTime::from_hms_opt(9, 10, 11).unwrap(); let dt = date.and_hms_opt(9, 10, 11).unwrap().and_utc(); ``` -------------------------------- ### Get Previous Month Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the previous month. This method wraps around, so the predecessor of January is December. ```rust pub const fn pred(&self) -> Month ``` -------------------------------- ### Get Naive Local DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Returns the local time represented as a `NaiveDateTime`, which does not include timezone information. ```rust pub fn naive_local(&self) -> NaiveDateTime ``` -------------------------------- ### Timezone Pattern Matching Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Illustrates how to handle potential ambiguities when converting to local time, such as during DST transitions. ```rust match Local.with_ymd_and_hms(2014, 3, 9, 2, 30, 0) { LocalResult::Single(dt) => {}, // Unambiguous LocalResult::Ambiguous(dt1, dt2) => {}, // Two options (DST) LocalResult::None => {}, // Doesn't exist } ``` -------------------------------- ### Get Naive UTC DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Returns the UTC time represented as a `NaiveDateTime`, which does not include timezone information. ```rust pub const fn naive_utc(&self) -> NaiveDateTime ``` -------------------------------- ### Handle Ambiguous Local Time Construction Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Demonstrates how constructing a local DateTime can result in ambiguity due to Daylight Saving Time transitions. The result can be Single, Ambiguous, or None. ```rust use chrono::{TimeZone, Local}; let result = Local.with_ymd_and_hms(2014, 7, 8, 9, 10, 11); ``` -------------------------------- ### Get Milliseconds Since Second Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Retrieves the number of milliseconds that have passed since the last whole second. ```rust pub const fn timestamp_subsec_millis(&self) -> u32 ``` -------------------------------- ### Timezone Handling Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Demonstrates how to use different timezone representations like UTC, FixedOffset, and Local. ```rust Utc // UTC (always) ``` ```rust FixedOffset::east_opt(9 * 3600) // UTC+09:00 ``` ```rust FixedOffset::west_opt(5 * 3600) // UTC-05:00 ``` ```rust Local // System timezone ``` ```rust dt.with_timezone(&Utc) // Convert to Utc ``` ```rust dt.with_timezone(&FixedOffset::...) // Convert to fixed ``` -------------------------------- ### Get Microseconds Since Second Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Retrieves the number of microseconds that have passed since the last whole second. ```rust pub const fn timestamp_subsec_micros(&self) -> u32 ``` -------------------------------- ### Enable Rkyv-32 Feature Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enable the 'rkyv-32' feature for serialization using the Rkyv framework with 32-bit size strategies. This provides zero-copy deserialization and is recommended for most applications. Only one rkyv feature can be enabled at a time. ```toml [dependencies] chrono = { version = "0.4", features = ["rkyv-32"] } rkyv = { version = "0.7", features = ["derive"] } ``` -------------------------------- ### Get Nanoseconds Since Second Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Retrieves the number of nanoseconds that have passed since the last whole second. ```rust pub const fn timestamp_subsec_nanos(&self) -> u32 ``` -------------------------------- ### Duration Operations Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Shows how to create `TimeDelta` durations, perform arithmetic operations, and query the number of days, hours, minutes, seconds, and milliseconds. ```rust // Creating durations let d = TimeDelta::days(5); let d = TimeDelta::hours(2) + TimeDelta::minutes(30); // Duration arithmetic let future = dt + TimeDelta::days(5); let duration = dt2.signed_duration_since(dt1); // Querying duration d.num_days() // i64 d.num_hours() // i64 d.num_minutes() // i64 d.num_seconds() // i64 d.num_milliseconds() // i64 ``` -------------------------------- ### Get Ordinal Day Component of NaiveDate Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Retrieves the ordinal day (day of the year, 1-366) from a NaiveDate. ```rust pub const fn ordinal(&self) -> u32 ``` -------------------------------- ### Get NaiveTime Component from DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md The `time` method returns the local time component of a DateTime as a NaiveTime. ```rust pub fn time(&self) -> NaiveTime ``` -------------------------------- ### Get Current UTC Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/11-api-overview.md Retrieves the current date and time in Coordinated Universal Time (UTC). ```rust // Get current UTC time let now = Utc::now(); ``` -------------------------------- ### Enable Serde Feature Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enable the 'serde' feature for serialization and deserialization using the Serde framework. This provides RFC 3339 format by default and timestamp-based serialization modules. ```toml [dependencies] chrono = { version = "0.4", features = ["serde"] } serde = { version = "1.0", features = ["derive"] } ``` ```rust use serde::{Serialize, Deserialize}; use chrono::DateTime; #[derive(Serialize, Deserialize)] struct Event { name: String, timestamp: DateTime, } ``` -------------------------------- ### Get Current Local Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Retrieves the current local date and time. Requires the 'clock' feature. ```rust use chrono::Local; let now = Local::now(); println!("Current local time: {}", now); ``` -------------------------------- ### Construct DateTime with FixedOffset Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Demonstrates constructing a `DateTime` object using a `FixedOffset` timezone obtained via `east_opt`. ```rust use chrono::{TimeZone, FixedOffset}; let tz = FixedOffset::east_opt(9 * 3600).unwrap(); let dt = tz.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); ``` -------------------------------- ### NaiveDate Construction from ISO Week Date Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Creates a NaiveDate from an ISO week date, specified by year, week number, and weekday. Returns None if the combination is invalid. ```APIDOC ## NaiveDate::from_isoywd_opt ### Description Creates a `NaiveDate` from ISO week date (year, week number, weekday). Returns `None` if the provided week date is invalid. ### Method `from_isoywd_opt` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust use chrono::{NaiveDate, Weekday}; // July 8, 2014 is Tuesday in ISO week 28 let date = NaiveDate::from_isoywd_opt(2014, 28, Weekday::Tue).unwrap(); assert_eq!(date, NaiveDate::from_ymd_opt(2014, 7, 8).unwrap()); ``` ### Response #### Success Response (Option) - `NaiveDate` - The constructed date if valid. #### Response Example ```rust // Successful construction Some(NaiveDate { ... }) // Invalid ISO week date None ``` ``` -------------------------------- ### Construct TimeDelta from Minutes (Panicking) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/02-timedelta.md Creates a TimeDelta from a number of minutes. This function will panic if the resulting duration is out of bounds. ```rust pub const fn minutes(mins: i64) -> TimeDelta ``` -------------------------------- ### Create Datetime from Naive Date and Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Combines `NaiveDate` and `NaiveTime` to create a `DateTime` object, which can then be localized to a specific timezone like UTC. ```rust use chrono::{NaiveDate, NaiveTime, Utc, TimeZone}; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); let time = NaiveTime::from_hms_opt(9, 10, 11).unwrap(); // To UTC let dt_utc = date.and_hms_opt(9, 10, 11).unwrap().and_utc(); // To local timezone let dt_local = date.and_hms_opt(9, 10, 11).unwrap().and_local_timezone(Utc).unwrap(); ``` -------------------------------- ### Construct NaiveDate from Year, Month, Day (Optional) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Creates a NaiveDate from year, month, and day components. Returns None if the date is invalid or out of range. ```rust pub const fn from_ymd_opt(year: i32, month: u32, day: u32) -> Option ``` ```rust use chrono::NaiveDate; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); assert_eq!(date.year(), 2014); ``` -------------------------------- ### Get Next Weekday Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the next day of the week. This method wraps around, so the successor of Sunday is Monday. ```rust pub const fn succ(&self) -> Weekday ``` -------------------------------- ### Get Previous Weekday Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Returns the previous day of the week. This method wraps around, so the predecessor of Monday is Sunday. ```rust pub const fn pred(&self) -> Weekday ``` -------------------------------- ### Enable Clock Feature Source: https://github.com/chronotope/chrono/blob/main/_autodocs/08-features-config.md Enable the 'clock' feature to read the system clock and local timezone. This feature requires the 'now' feature as a prerequisite and depends on 'iana-time-zone' on Unix or 'winapi' on Windows. ```toml [dependencies] chrono = { version = "0.4", features = ["clock"] } ``` -------------------------------- ### Get UNIX Timestamp in Microseconds from DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md The `timestamp_micros` method returns the UNIX timestamp in microseconds since the epoch. ```rust pub const fn timestamp_micros(&self) -> i64 ``` -------------------------------- ### Construct NaiveDate from ISO Week Date (Optional) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Creates a NaiveDate from an ISO week date (year, week number, and weekday). Returns None if the date is invalid. ```rust pub const fn from_isoywd_opt(year: i32, week: u32, weekday: Weekday) -> Option ``` ```rust use chrono::{NaiveDate, Weekday}; // July 8, 2014 is Tuesday in ISO week 28 let date = NaiveDate::from_isoywd_opt(2014, 28, Weekday::Tue).unwrap(); assert_eq!(date, NaiveDate::from_ymd_opt(2014, 7, 8).unwrap()); ``` -------------------------------- ### Get UNIX Timestamp in Milliseconds from DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md The `timestamp_millis` method returns the UNIX timestamp in milliseconds since the epoch. ```rust pub const fn timestamp_millis(&self) -> i64 ``` -------------------------------- ### Handling Ambiguous Local Times Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Demonstrates how to manage ambiguous local times that can occur during Daylight Saving Time transitions, using `LocalResult` to capture all possibilities. ```rust use chrono::LocalResult; match Local.with_ymd_and_hms(2014, 3, 9, 2, 30, 0) { LocalResult::Single(dt) => println!("Unique: {}", dt), LocalResult::Ambiguous(dt1, dt2) => println!("Two choices"), LocalResult::None => println!("Doesn't exist"), } ``` -------------------------------- ### Prelude Module Re-exports Source: https://github.com/chronotope/chrono/blob/main/_autodocs/11-api-overview.md Re-exports common types and traits from the Chronotope library for convenient glob importing. ```rust pub mod prelude { pub use crate::{DateTime, Local, Locale}; pub use crate::{Datelike, Month, Timelike, Weekday}; pub use crate::{FixedOffset, Utc}; pub use crate::{NaiveDate, NaiveDateTime, NaiveTime}; pub use crate::{Offset, TimeZone}; pub use crate::{SecondsFormat}; pub use crate::{SubsecRound}; } ``` -------------------------------- ### Get UNIX Timestamp in Seconds from DateTime Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md The `timestamp` method returns the UNIX timestamp in seconds since the epoch. ```rust use chrono::{DateTime, Utc}; let dt: DateTime = Utc.with_ymd_and_hms(2015, 5, 15, 0, 0, 0).unwrap(); assert_eq!(dt.timestamp(), 1431648000); ``` -------------------------------- ### Get Age in Days Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md Calculate the age in days by finding the signed duration between the current UTC time and a birthdate. ```rust // Get age in days let age_days = Utc::now().signed_duration_since(birthdate).num_days(); ``` -------------------------------- ### Formatting Without Allocation Support Source: https://github.com/chronotope/chrono/blob/main/_autodocs/10-quick-ref.md The `to_string()` method for formatting requires the `alloc` feature. Formatting is not possible without allocation support. ```rust // to_string() requires 'alloc' feature // Can't format without allocation support ``` -------------------------------- ### Datelike Accessor: ordinal0 Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Retrieves the day of the year from a date, starting from 0. The day is returned as a u32 in the range 0-365. ```rust fn ordinal0(&self) -> u32 ``` -------------------------------- ### Create WeekdaySet Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Constructs a WeekdaySet from a boolean array of length 7, where each element corresponds to a day of the week. ```rust pub const fn new(v: [bool; 7]) -> WeekdaySet ``` -------------------------------- ### Datelike Accessor: day0 Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Retrieves the day of the month from a date, starting from 0. The day is returned as a u32 in the range 0-30. ```rust fn day0(&self) -> u32 ``` -------------------------------- ### Work with ISO Weeks in Rust Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Calculate ISO week numbers from a `NaiveDate` and construct dates from ISO week components. Ensure correct week and year values are used for accurate conversions. ```rust use chrono::{NaiveDate, Weekday}; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); // Get ISO week let week = date.iso_week(); assert_eq!(week.year(), 2014); assert_eq!(week.week(), 28); // Create from ISO week date let date2 = NaiveDate::from_isoywd_opt(2014, 28, Weekday::Tue).unwrap(); assert_eq!(date, date2); ``` -------------------------------- ### Datelike Accessor: month0 Source: https://github.com/chronotope/chrono/blob/main/_autodocs/06-traits-types.md Retrieves the month component from a date, starting from 0. The month is returned as a u32 in the range 0-11. ```rust fn month0(&self) -> u32 ``` -------------------------------- ### Construct DateTime from Naive UTC and Offset Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Use `from_naive_utc_and_offset` to create a DateTime from a NaiveDateTime (in UTC) and a specific timezone offset. ```rust use chrono::{DateTime, FixedOffset, NaiveDate, Utc}; let naive_utc = NaiveDate::from_ymd_opt(2020, 1, 1) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(); let offset = FixedOffset::east_opt(9 * 3600).unwrap(); let dt = DateTime::::from_naive_utc_and_offset(naive_utc, offset); ``` -------------------------------- ### ParseError Type (Error Types) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/11-api-overview.md Represents errors that occur during parsing, providing a `kind()` method to get specific error details. ```APIDOC ## ParseError Type (Error Types) ### Description Returned by parsing operations. ### Has - `kind()` method to get error details ``` -------------------------------- ### Construct DateTime with Utc Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Demonstrates constructing a `DateTime` object in the `Utc` timezone using the `with_ymd_and_hms` method. ```rust use chrono::{TimeZone, Utc}; let dt = Utc.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); ``` -------------------------------- ### Get Current Local Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Retrieves the current time in the system's local timezone. Requires the 'clock' feature to be enabled. ```rust use chrono::Local; // Get current local time (requires 'clock' feature) #[cfg(feature = "clock")] { let now = Local::now(); println!("Local now: {}", now); } ``` -------------------------------- ### Handling Invalid Dates and Parsing Errors Source: https://github.com/chronotope/chrono/blob/main/_autodocs/00-index.md Shows how to safely handle invalid date constructions that return `None`. Demonstrates parsing date strings which return a `Result` for error handling. ```rust // Invalid dates return None (safe) match NaiveDate::from_ymd_opt(2014, 2, 30) { Some(d) => println!("Valid"), None => println!("Invalid"), } // Parsing returns Result match "2014-13-01".parse::() { Ok(d) => println!("Parsed"), Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### NaiveDateTime::new Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Constructs a NaiveDateTime object by combining a NaiveDate and a NaiveTime. ```APIDOC ## NaiveDateTime::new ### Description Creates a `NaiveDateTime` from separate date and time. ### Method Signature `pub const fn new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime` ### Parameters #### Path Parameters - **date** (NaiveDate) - Required - The date - **time** (NaiveTime) - Required - The time ### Returns `NaiveDateTime` - The datetime ### Example ```rust use chrono::{NaiveDate, NaiveTime, NaiveDateTime}; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); let time = NaiveTime::from_hms_opt(9, 10, 11).unwrap(); let dt = NaiveDateTime::new(date, time); ``` ``` -------------------------------- ### Get Current UTC Time Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Retrieves the current time in Coordinated Universal Time (UTC). Requires the 'now' feature to be enabled. ```rust use chrono::Utc; // Get current UTC time (requires 'now' feature) #[cfg(feature = "now")] { let now = Utc::now(); println!("UTC now: {}", now); // ISO 8601 format } ``` -------------------------------- ### Run Chrono Fuzzer Source: https://github.com/chronotope/chrono/blob/main/fuzz/README.md Executes the Chrono fuzzer. Navigate to the top directory of chrono before running this command. ```bash cargo-fuzz run fuzz_reader ``` -------------------------------- ### DateTime::from_naive_utc_and_offset Source: https://github.com/chronotope/chrono/blob/main/_autodocs/01-datetime.md Constructs a DateTime from a NaiveDateTime (in UTC) and a timezone offset. This method allows for precise creation when you have both the UTC time and the desired offset. ```APIDOC ## DateTime::from_naive_utc_and_offset ### Description Creates a `DateTime` from a `NaiveDateTime` (in UTC) and an offset. ### Method `DateTime::from_naive_utc_and_offset` ### Parameters #### Path Parameters - `datetime` (NaiveDateTime) - Required - UTC date and time - `offset` (Tz::Offset) - Required - Timezone offset ### Returns `DateTime` - The constructed datetime ### Example ```rust use chrono::{DateTime, FixedOffset, NaiveDate, Utc}; let naive_utc = NaiveDate::from_ymd_opt(2020, 1, 1) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(); let offset = FixedOffset::east_opt(9 * 3600).unwrap(); let dt = DateTime::::from_naive_utc_and_offset(naive_utc, offset); ``` ``` -------------------------------- ### IsoWeek Struct Source: https://github.com/chronotope/chrono/blob/main/_autodocs/07-types-reference.md Represents a date in the ISO 8601 week date format. This format has specific rules for week numbering and the start of the week. ```APIDOC ## IsoWeek Struct Represents a date in the ISO 8601 week date format. This format has specific rules for week numbering and the start of the week. ### Properties - `year`: The ISO 8601 week year. - `week`: The week number within the year (1-53). ### Notes - Weeks start on Monday. - Week 1 is defined as the week containing the first Thursday of the year. ``` -------------------------------- ### Construct TimeDelta from Days (Panicking) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/02-timedelta.md Creates a TimeDelta from a number of days. This function will panic if the resulting duration is out of bounds. ```rust pub const fn days(days: i64) -> TimeDelta ``` -------------------------------- ### NaiveWeek Struct Definition Source: https://github.com/chronotope/chrono/blob/main/_autodocs/07-types-reference.md Represents a week within a calendar, allowing for a custom start day. This struct cannot span across year boundaries. ```rust pub struct NaiveWeek { date: NaiveDate, start: Weekday, } ``` -------------------------------- ### Get Time Components Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Retrieves time-specific components such as hour, minute, second, and nanosecond from a `DateTime` object. The `Timelike` trait must be imported. ```rust use chrono::{Timelike, Utc}; let dt = Utc.with_ymd_and_hms(2014, 11, 28, 12, 30, 45).unwrap(); assert_eq!(dt.hour(), 12); assert_eq!(dt.minute(), 30); assert_eq!(dt.second(), 45); assert_eq!(dt.nanosecond(), 0); ``` -------------------------------- ### and_hms_opt Source: https://github.com/chronotope/chrono/blob/main/_autodocs/04-naive-types.md Combines a NaiveDate with hour, minute, and second components to create a NaiveDateTime. Returns None if the time components are invalid. ```APIDOC ## and_hms_opt ### Description Combines date with time components to create a `NaiveDateTime`. Returns `Option`. ### Method Signature `pub const fn and_hms_opt(self, hour: u32, min: u32, sec: u32) -> Option` ### Parameters #### Path Parameters - **hour** (u32) - Required - Hour (0-23) - **min** (u32) - Required - Minute (0-59) - **sec** (u32) - Required - Second (0-59) ### Returns `Option` - The datetime, or `None` if invalid ### Example ```rust use chrono::NaiveDate; let date = NaiveDate::from_ymd_opt(2014, 7, 8).unwrap(); let datetime = date.and_hms_opt(9, 10, 11).unwrap(); ``` ``` -------------------------------- ### Get Default TimeDelta Value Source: https://github.com/chronotope/chrono/blob/main/_autodocs/02-timedelta.md Retrieves the default value for TimeDelta, which is zero seconds. This is useful for initializing durations or when a zero duration is needed. ```rust use chrono::TimeDelta; let default: TimeDelta = Default::default(); assert!(default.is_zero()); ``` -------------------------------- ### Create UTC Datetime from Components Source: https://github.com/chronotope/chrono/blob/main/_autodocs/09-common-patterns.md Constructs a UTC datetime object from year, month, day, hour, minute, and second components. The `unwrap()` call will panic if the date or time components are invalid. ```rust use chrono::{TimeZone, Utc, FixedOffset}; // UTC datetime let dt = Utc.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); assert_eq!(dt.year(), 2014); assert_eq!(dt.month(), 7); // With fixed offset let tz = FixedOffset::east_opt(9 * 3600).unwrap(); let dt = tz.with_ymd_and_hms(2014, 7, 8, 9, 10, 11).unwrap(); ``` -------------------------------- ### Construct TimeDelta from Minutes (Fallible) Source: https://github.com/chronotope/chrono/blob/main/_autodocs/02-timedelta.md Creates a TimeDelta from minutes, returning None if the duration is out of the representable range. ```rust pub const fn try_minutes(mins: i64) -> Option ``` -------------------------------- ### Offset Trait Definition Source: https://github.com/chronotope/chrono/blob/main/_autodocs/03-timezones.md Represents a fixed offset from UTC. Implementations must provide methods to convert to a `FixedOffset` and to get the offset duration. ```rust pub trait Offset: Sized + Clone + fmt::Debug { fn fix(&self) -> FixedOffset; fn local_minus_utc(&self) -> TimeDelta; } ```