### Parse Month from string (valid examples) Source: https://docs.rs/chrono/latest/src/chrono/format/mod.rs.html Shows valid examples of parsing month names, including the full and shortest forms. ```rust assert_eq!("January".parse::(), Ok(Month::January)); assert!("any day".parse::().is_err()); ``` -------------------------------- ### Parse Weekday from string (valid examples) Source: https://docs.rs/chrono/latest/src/chrono/format/mod.rs.html Shows valid examples of parsing weekday names, including the full and shortest forms. ```rust assert_eq!("Sunday".parse::(), Ok(Weekday::Sun)); assert!("any day".parse::().is_err()); ``` -------------------------------- ### Default Implementation Source: https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html Shows how to get the default NaiveDate value and verifies it. ```APIDOC ## impl Default for NaiveDate ### Description The default value for a NaiveDate is 1st of January 1970. #### fn default() -> Self ### Returns - `Self`: The default `NaiveDate` value (1970-01-01). ### Example ```rust use chrono::NaiveDate; let default_date = NaiveDate::default(); assert_eq!(default_date, NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()); ``` ``` -------------------------------- ### last Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Get the last day in the collection, starting from Sunday. ```APIDOC ## last ### Description Retrieves the last day present in the `WeekdaySet`, ordered from Sunday down to Monday. Returns `None` if the set is empty. ### Method `fn last(self) -> Option` ### Returns - `Option` - `Some(Weekday)` containing the last day if the set is not empty, otherwise `None`. ### Example ```rust use chrono::WeekdaySet; use chrono::Weekday::*; assert_eq!(WeekdaySet::single(Mon).last(), Some(Mon)); assert_eq!(WeekdaySet::single(Sun).last(), Some(Sun)); assert_eq!(WeekdaySet::from_array([Mon, Tue]).last(), Some(Tue)); assert_eq!(WeekdaySet::EMPTY.last(), None); ``` ``` -------------------------------- ### Example Usage of NaiveDate::from_yo_opt Source: https://docs.rs/chrono/latest/src/chrono/naive/date/mod.rs.html Demonstrates the usage of `NaiveDate::from_yo_opt` with valid and invalid ordinal dates, showing successful creation for valid inputs and None for invalid ones. ```rust use chrono::NaiveDate; let from_yo_opt = NaiveDate::from_yo_opt; assert!(from_yo_opt(2015, 100).is_some()); assert!(from_yo_opt(2015, 0).is_none()); ``` -------------------------------- ### Format and Parse DateTime Example Source: https://docs.rs/chrono/latest/src/chrono/format/mod.rs.html Demonstrates formatting a DateTime object into a string and then parsing it back. Requires the 'alloc' feature. ```rust use chrono::{NaiveDateTime, TimeZone, Utc}; let date_time = Utc.with_ymd_and_hms(2020, 11, 10, 0, 1, 32).unwrap(); let formatted = format!("{}", date_time.format("%Y-%m-%d %H:%M:%S")); assert_eq!(formatted, "2020-11-10 00:01:32"); let parsed = NaiveDateTime::parse_from_str(&formatted, "%Y-%m-%d %H:%M:%S")?.and_utc(); assert_eq!(parsed, date_time); ``` -------------------------------- ### first Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Get the first day in the collection, starting from Monday. ```APIDOC ## first ### Description Retrieves the first day present in the `WeekdaySet`, ordered from Monday to Sunday. Returns `None` if the set is empty. ### Method `const fn first(self) -> Option` ### Returns - `Option` - `Some(Weekday)` containing the first day if the set is not empty, otherwise `None`. ### Example ```rust use chrono::WeekdaySet; use chrono::Weekday::*; assert_eq!(WeekdaySet::single(Mon).first(), Some(Mon)); assert_eq!(WeekdaySet::single(Tue).first(), Some(Tue)); assert_eq!(WeekdaySet::ALL.first(), Some(Mon)); assert_eq!(WeekdaySet::EMPTY.first(), None); ``` ``` -------------------------------- ### Example: Creating DateTime with Western FixedOffset Source: https://docs.rs/chrono/latest/src/chrono/offset/fixed.rs.html Demonstrates creating a `DateTime` with a fixed offset in the Western Hemisphere using `west_opt` and converting it to an RFC 3339 string. ```rust # #[cfg(feature = "alloc")] { use chrono::{FixedOffset, TimeZone}; let hour = 3600; let datetime = FixedOffset::west_opt(5 * hour).unwrap().with_ymd_and_hms(2016, 11, 08, 0, 0, 0).unwrap(); assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00-05:00") # } ``` -------------------------------- ### WeekdaySet: Get Length Source: https://docs.rs/chrono/latest/chrono/struct.WeekdaySet.html Demonstrates getting the number of days in a WeekdaySet. Examples include a single-day set, a multi-day set, and the set of all days. ```rust use chrono::Weekday::*; assert_eq!(WeekdaySet::single(Mon).len(), 1); assert_eq!(WeekdaySet::from_array([Mon, Wed, Fri]).len(), 3); assert_eq!(WeekdaySet::ALL.len(), 7); ``` -------------------------------- ### WeekdaySet::last Source: https://docs.rs/chrono/latest/chrono/struct.WeekdaySet.html Get the last day in the collection, starting from Sunday. ```APIDOC ## WeekdaySet::last ### Description Get the last day in the collection, starting from Sunday. Returns `None` if the collection is empty. ### Method `last(self) -> Option` ### Example ```rust use chrono::Weekday::* assert_eq!(WeekdaySet::single(Mon).last(), Some(Mon)); assert_eq!(WeekdaySet::single(Sun).last(), Some(Sun)); assert_eq!(WeekdaySet::from_array([Mon, Tue]).last(), Some(Tue)); assert_eq!(WeekdaySet::EMPTY.last(), None); ``` ``` -------------------------------- ### Example: ISO Week Date Conversion Edge Cases Source: https://docs.rs/chrono/latest/src/chrono/naive/date/mod.rs.html Demonstrates how `from_isoywd_opt` handles week dates that span across year boundaries, including cases where the ISO week year differs from the calendar year. ```rust use chrono::{NaiveDate, Weekday}; let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap(); let from_isoywd_opt = NaiveDate::from_isoywd_opt; assert_eq!(from_isoywd_opt(2015, 0, Weekday::Sun), None); assert_eq!(from_isoywd_opt(2015, 10, Weekday::Sun), Some(from_ymd(2015, 3, 8))); assert_eq!(from_isoywd_opt(2015, 30, Weekday::Mon), Some(from_ymd(2015, 7, 20))); assert_eq!(from_isoywd_opt(2015, 60, Weekday::Mon), None); assert_eq!(from_isoywd_opt(400000, 10, Weekday::Fri), None); assert_eq!(from_isoywd_opt(-400000, 10, Weekday::Sat), None); ``` ```rust # use chrono::{NaiveDate, Weekday}; # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap(); # let from_isoywd_opt = NaiveDate::from_isoywd_opt; // Mo Tu We Th Fr Sa Su // 2014-W52 22 23 24 25 26 27 28 has 4+ days of new year, // 2015-W01 29 30 31 1 2 3 4 <- so this is the first week assert_eq!(from_isoywd_opt(2014, 52, Weekday::Sun), Some(from_ymd(2014, 12, 28))); assert_eq!(from_isoywd_opt(2014, 53, Weekday::Mon), None); assert_eq!(from_isoywd_opt(2015, 1, Weekday::Mon), Some(from_ymd(2014, 12, 29))); // 2015-W52 21 22 23 24 25 26 27 has 4+ days of old year, // 2015-W53 28 29 30 31 1 2 3 <- so this is the last week // 2016-W01 4 5 6 7 8 9 10 assert_eq!(from_isoywd_opt(2015, 52, Weekday::Sun), Some(from_ymd(2015, 12, 27))); assert_eq!(from_isoywd_opt(2015, 53, Weekday::Sun), Some(from_ymd(2016, 1, 3))); assert_eq!(from_isoywd_opt(2015, 54, Weekday::Mon), None); assert_eq!(from_isoywd_opt(2016, 1, Weekday::Mon), Some(from_ymd(2016, 1, 4))); ``` -------------------------------- ### WeekdaySet::first Source: https://docs.rs/chrono/latest/chrono/struct.WeekdaySet.html Get the first day in the collection, starting from Monday. ```APIDOC ## WeekdaySet::first ### Description Get the first day in the collection, starting from Monday. Returns `None` if the collection is empty. ### Method `first(self) -> Option` ### Example ```rust use chrono::Weekday::* assert_eq!(WeekdaySet::single(Mon).first(), Some(Mon)); assert_eq!(WeekdaySet::single(Tue).first(), Some(Tue)); assert_eq!(WeekdaySet::ALL.first(), Some(Mon)); assert_eq!(WeekdaySet::EMPTY.first(), None); ``` ``` -------------------------------- ### NaiveDate Addition with TimeDelta Source: https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html Demonstrates adding TimeDelta to NaiveDate, showing how fractional days are handled and the resulting NaiveDate. ```APIDOC ## NaiveDate Addition with TimeDelta ### Description Performs the `+` operation between a `NaiveDate` and a `TimeDelta`. ### Method `add` ### Parameters - `self`: The `NaiveDate` instance. - `rhs`: The `TimeDelta` to add. ### Return Value - `NaiveDate`: The resulting date after adding the `TimeDelta`. ### Example ```rust use chrono::{NaiveDate, TimeDelta}; let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap(); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::zero(), from_ymd(2014, 1, 1)); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_seconds(86399).unwrap(), from_ymd(2014, 1, 1)); assert_eq!( from_ymd(2014, 1, 1) + TimeDelta::try_seconds(-86399).unwrap(), from_ymd(2014, 1, 1) ); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(1).unwrap(), from_ymd(2014, 1, 2)); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(-1).unwrap(), from_ymd(2013, 12, 31)); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(364).unwrap(), from_ymd(2014, 12, 31)); assert_eq!( from_ymd(2014, 1, 1) + TimeDelta::try_days(365 * 4 + 1).unwrap(), from_ymd(2018, 1, 1) ); assert_eq!( from_ymd(2014, 1, 1) + TimeDelta::try_days(365 * 400 + 97).unwrap(), from_ymd(2414, 1, 1) ); ``` ``` -------------------------------- ### Convert to and from UNIX Timestamps with Chrono Source: https://docs.rs/chrono/latest/chrono/index.html Shows how to construct a `DateTime` from seconds and nanoseconds since the UNIX epoch using `from_timestamp_secs` and how to retrieve the UNIX timestamp in seconds using the `timestamp` method. ```rust // We need the trait in scope to use Utc::timestamp(). use chrono::{DateTime, Utc}; // Construct a datetime from epoch: let dt: DateTime = DateTime::from_timestamp_secs(1_500_000_000).unwrap(); assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000"); // Get epoch value from a datetime: let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap(); assert_eq!(dt.timestamp(), 1_500_000_000); ``` -------------------------------- ### WeekdaySet::first Source: https://docs.rs/chrono/latest/chrono/struct.WeekdaySet.html Gets the first day in the WeekdaySet, starting from Monday. Returns `None` if the set is empty. ```APIDOC ## `first(self) -> Option` Get the first day in the collection, starting from Monday. Returns `None` if the collection is empty. ``` -------------------------------- ### Get Month Name Source: https://docs.rs/chrono/latest/chrono/enum.Month.html Example of how to retrieve the string name of a Month enum variant. This is useful for display purposes. ```rust use chrono::Month; assert_eq!(Month::January.name(), "January") ``` -------------------------------- ### NaiveDateTime addition with TimeDelta examples Source: https://docs.rs/chrono/latest/src/chrono/naive/datetime/mod.rs.html Demonstrates adding `TimeDelta` to `NaiveDateTime` with various durations, including zero, positive, negative, and day-based increments. Asserts expected results after addition. ```rust let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap(); assert_eq!(hms(3, 5, 7) + TimeDelta::zero(), hms(3, 5, 7)); assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(1).unwrap(), hms(3, 5, 8)); assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(-1).unwrap(), hms(3, 5, 6)); assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(3600 + 60).unwrap(), hms(4, 6, 7)); assert_eq!( hms(3, 5, 7) + TimeDelta::try_seconds(86_400).unwrap(), from_ymd(2016, 7, 9).and_hms_opt(3, 5, 7).unwrap() ); assert_eq!( hms(3, 5, 7) + TimeDelta::try_days(365).unwrap(), from_ymd(2017, 7, 8).and_hms_opt(3, 5, 7).unwrap() ); ``` -------------------------------- ### Get Last Day in WeekdaySet Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Retrieves the last day in the collection, starting from Sunday. Returns `None` if the set is empty. ```rust pub fn last(self) -> Option { if self.is_empty() { return None; } // Find the last non-zero bit. let bit = 1 << (7 - self.0.leading_zeros()); Self(bit).single_day() } ``` -------------------------------- ### WeekdaySet Creation and String Representation Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Demonstrates how to create WeekdaySet instances using various methods and how they are represented as strings. Useful for initializing and verifying weekday sets. ```rust use chrono::WeekdaySet; use chrono::Weekday::*; assert_eq!("[]", WeekdaySet::EMPTY.to_string()); assert_eq!("[Mon]", WeekdaySet::single(Mon).to_string()); assert_eq!("[Mon, Fri, Sun]", WeekdaySet::from_array([Mon, Fri, Sun]).to_string()); ``` -------------------------------- ### Weekday Parsing and Conversion Example Source: https://docs.rs/chrono/latest/chrono/enum.Weekday.html Demonstrates parsing a string into a Weekday, converting from a number, and using helper methods for day calculations. ```rust use chrono::Weekday; let monday = "Monday".parse::().unwrap(); assert_eq!(monday, Weekday::Mon); let sunday = Weekday::try_from(6).unwrap(); assert_eq!(sunday, Weekday::Sun); assert_eq!(sunday.num_days_from_monday(), 6); // starts counting with Monday = 0 assert_eq!(sunday.number_from_monday(), 7); // starts counting with Monday = 1 assert_eq!(sunday.num_days_from_sunday(), 0); // starts counting with Sunday = 0 assert_eq!(sunday.number_from_sunday(), 1); // starts counting with Sunday = 1 assert_eq!(sunday.succ(), monday); assert_eq!(sunday.pred(), Weekday::Sat); ``` -------------------------------- ### Get First Day in WeekdaySet Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Retrieves the first day in the collection, starting from Monday. Returns `None` if the set is empty. ```rust pub const fn first(self) -> Option { if self.is_empty() { return None; } // Find the first non-zero bit. let bit = 1 << self.0.trailing_zeros(); Self(bit).single_day() } ``` -------------------------------- ### NaiveDate Display Formatting Examples Source: https://docs.rs/chrono/latest/src/chrono/naive/date/mod.rs.html Illustrates the Display formatting of NaiveDate, showing its output for standard, zero, maximum, and out-of-range years. ```rust assert_eq!(format!("{}", NaiveDate::from_ymd_opt(2015, 9, 5).unwrap()), "2015-09-05"); assert_eq!(format!("{}", NaiveDate::from_ymd_opt(0, 1, 1).unwrap()), "0000-01-01"); assert_eq!(format!("{}", NaiveDate::from_ymd_opt(9999, 12, 31).unwrap()), "9999-12-31"); ``` ```rust assert_eq!(format!("{}", NaiveDate::from_ymd_opt(-1, 1, 1).unwrap()), "-0001-01-01"); assert_eq!(format!("{}", NaiveDate::from_ymd_opt(10000, 12, 31).unwrap()), "+10000-12-31"); ``` -------------------------------- ### Get Day of Year (0-indexed) - NaiveDate Source: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html Returns the day of the year starting from 0. The value ranges from 0 to 365. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal0(), 250); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal0(), 73); ``` -------------------------------- ### Rust: Initialize and set date/time fields with Parsed Source: https://docs.rs/chrono/latest/chrono/format/struct.Parsed.html Demonstrates initializing a Parsed struct and setting various date and time fields. It shows how to correctly set fields to form a valid datetime and how an inconsistent field (wrong weekday) leads to an error. ```rust use chrono::format::{ParseErrorKind, Parsed}; use chrono::Weekday; let mut parsed = Parsed::new(); parsed.set_weekday(Weekday::Wed)?; parsed.set_day(31)?; parsed.set_month(12)?; parsed.set_year(2014)?; parsed.set_hour(4)?; parsed.set_minute(26)?; parsed.set_second(40)?; parsed.set_offset(0)?; let dt = parsed.to_datetime()?; assert_eq!(dt.to_rfc2822(), "Wed, 31 Dec 2014 04:26:40 +0000"); let mut parsed = Parsed::new(); parsed.set_weekday(Weekday::Thu)?; parsed.set_day(31)?; parsed.set_month(12)?; parsed.set_year(2014)?; parsed.set_hour(4)?; parsed.set_minute(26)?; parsed.set_second(40)?; parsed.set_offset(0)?; let result = parsed.to_datetime(); assert!(result.is_err()); if let Err(error) = result { assert_eq!(error.kind(), ParseErrorKind::Impossible); } ``` -------------------------------- ### Get Day of Year (1-indexed) - NaiveDate Source: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html Returns the day of the year starting from 1. The value ranges from 1 to 366. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal(), 251); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal(), 74); ``` -------------------------------- ### Example: Creating DateTime with Eastern FixedOffset Source: https://docs.rs/chrono/latest/src/chrono/offset/fixed.rs.html Demonstrates creating a `DateTime` with a fixed offset in the Eastern Hemisphere using `east_opt` and converting it to an RFC 3339 string. ```rust # #[cfg(feature = "alloc")] { use chrono::{FixedOffset, TimeZone}; let hour = 3600; let datetime = FixedOffset::east_opt(5 * hour).unwrap().with_ymd_and_hms(2016, 11, 08, 0, 0, 0).unwrap(); assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00+05:00") # } ``` -------------------------------- ### Get Day of Month (0-indexed) - NaiveDate Source: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html Returns the day of the month starting from 0. The value ranges from 0 to 30. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().day0(), 7); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().day0(), 13); ``` -------------------------------- ### Get Month Number (1-indexed) Source: https://docs.rs/chrono/latest/src/chrono/month.rs.html The `number_from_month` method returns the month's number, starting with 1 for January and ending with 12 for December. ```rust pub const fn number_from_month(&self) -> u32 { match *self { Month::January => 1, Month::February => 2, Month::March => 3, Month::April => 4, Month::May => 5, Month::June => 6, Month::July => 7, Month::August => 8, Month::September => 9, Month::October => 10, } } ``` -------------------------------- ### NaiveTime Archive and Resolve Source: https://docs.rs/chrono/latest/chrono/struct.NaiveTime.html Demonstrates the archiving and resolving process for NaiveTime, defining its archived representation and resolver. ```rust use chrono::NaiveTime; use rkyv::{Archive, Archived, Resolver}; // Assuming 'naive_time' is a NaiveTime instance // let archived_naive_time: Archived = naive_time.archive_as::(); // let resolved_naive_time: NaiveTime = archived_naive_time.resolve(); ``` -------------------------------- ### Get ISO week number (0-52) Source: https://docs.rs/chrono/latest/chrono/naive/struct.IsoWeek.html Retrieves the ISO week number starting from 0. The range is 0 to 52, with the last week number varying by year. ```rust use chrono::{Datelike, NaiveDate, Weekday}; let d = NaiveDate::from_isoywd_opt(2015, 15, Weekday::Mon).unwrap(); assert_eq!(d.iso_week().week0(), 14); ``` -------------------------------- ### Parse Dates with Week from Sunday Source: https://docs.rs/chrono/latest/src/chrono/format/parsed.rs.html Demonstrates parsing dates using the week number starting from Sunday and the weekday. Includes examples of valid dates, impossible combinations, and out-of-range values. ```rust assert_eq!(parse!(year: 2000, week_from_sun: 1, weekday: Sun), ymd(2000, 1, 2)); assert_eq!(parse!(year: 2000, week_from_sun: 1, weekday: Mon), ymd(2000, 1, 3)); assert_eq!(parse!(year: 2000, week_from_sun: 1, weekday: Sat), ymd(2000, 1, 8)); assert_eq!(parse!(year: 2000, week_from_sun: 2, weekday: Sun), ymd(2000, 1, 9)); assert_eq!(parse!(year: 2000, week_from_sun: 52, weekday: Sat), ymd(2000, 12, 30)); assert_eq!(parse!(year: 2000, week_from_sun: 53, weekday: Sun), ymd(2000, 12, 31)); assert_eq!(parse!(year: 2000, week_from_sun: 53, weekday: Mon), Err(IMPOSSIBLE)); assert_eq!(parse!(year: 2000, week_from_sun: 0xffffffff, weekday: Mon), Err(OUT_OF_RANGE)); assert_eq!(parse!(year: 2006, week_from_sun: 0, weekday: Sat), Err(IMPOSSIBLE)); assert_eq!(parse!(year: 2006, week_from_sun: 1, weekday: Sun), ymd(2006, 1, 1)); ``` -------------------------------- ### Constructing Local DateTime instances Source: https://docs.rs/chrono/latest/chrono/offset/struct.Local.html Use the TimeZone methods on the Local struct to create DateTime instances. This example shows how to get the current local time and construct a DateTime from a timestamp. ```rust use chrono::{DateTime, Local, TimeZone}; let dt1: DateTime = Local::now(); let dt2: DateTime = Local.timestamp_opt(0, 0).unwrap(); assert!(dt1 >= dt2); ``` -------------------------------- ### Create a New Transition Instance Source: https://docs.rs/chrono/latest/src/chrono/offset/local/mod.rs.html A constructor for the `Transition` struct. It calculates the UTC transition time based on the local transition time and the offset before the transition. ```rust #[cfg(windows)] impl Transition { fn new( transition_local: NaiveDateTime, offset_before: FixedOffset, offset_after: FixedOffset, ) -> Transition { // It is no problem if the transition time in UTC falls a couple of hours inside the buffer // space around the `NaiveDateTime` range (although it is very theoretical to have a // transition at midnight around `NaiveDate::(MIN|MAX)`. let transition_utc = transition_local.overflowing_sub_offset(offset_before); Transition { transition_utc, offset_before, offset_after } } } ``` -------------------------------- ### Format Dates and Times with Chrono Source: https://docs.rs/chrono/latest/chrono/index.html Demonstrates various formatting options for `DateTime` objects, including `strftime`-like formats, localized formatting, and standard string representations like RFC2822 and RFC3339. Also shows how milliseconds and nanoseconds are printed. ```rust use chrono::prelude::*; let dt = Utc.with_ymd_and_hms(2014, 11, 28, 12, 0, 9).unwrap(); assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09"); assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014"); assert_eq!( dt.format_localized("%A %e %B %Y, %T", Locale::fr_BE).to_string(), "vendredi 28 novembre 2014, 12:00:09" ); assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string()); assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC"); assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000"); assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00"); assert_eq!(format!(‘{:?}‘, dt), "2014-11-28T12:00:09Z"); // Note that milli/nanoseconds are only printed if they are non-zero let dt_nano = NaiveDate::from_ymd_opt(2014, 11, 28) .unwrap() .and_hms_nano_opt(12, 0, 9, 1) .unwrap() .and_utc(); assert_eq!(format!(‘{:?}‘, dt_nano), "2014-11-28T12:00:09.000000001Z"); ``` -------------------------------- ### Combining NaiveDate with Time Components Source: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html Demonstrates creating a NaiveDateTime by combining a NaiveDate with hour, minute, and second. It highlights the `and_hms_opt` method for safe construction. ```APIDOC ## NaiveDate::and_hms_opt ### Description Creates a new `NaiveDateTime` from the current date, hour, minute, and second. Returns `None` if the provided time components are invalid. ### Method Signature `pub const fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option` ### Parameters - **hour** (u32) - The hour of the day (0-23). - **min** (u32) - The minute of the hour (0-59). - **sec** (u32) - The second of the minute (0-59). ### Errors Returns `None` on invalid hour, minute, or second. ### Example ```rust use chrono::NaiveDate; let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap(); assert!(d.and_hms_opt(12, 34, 56).is_some()); assert!(d.and_hms_opt(12, 34, 60).is_none()); // Invalid second assert!(d.and_hms_opt(12, 60, 56).is_none()); // Invalid minute assert!(d.and_hms_opt(24, 34, 56).is_none()); // Invalid hour ``` ``` -------------------------------- ### Get UTC Offset from Local Time Source: https://docs.rs/chrono/latest/src/chrono/offset/fixed.rs.html Returns the number of seconds that should be added to the local time to get UTC. This is the negative of the `local_minus_utc` offset. ```rust pub const fn utc_minus_local(&self) -> i32 { -self.local_minus_utc } ``` -------------------------------- ### Full Date and Time Formatting with strftime Source: https://docs.rs/chrono/latest/src/chrono/format/strftime.rs.html Examples of comprehensive date and time formatting specifiers like `%c` (locale's date and time) and `%+` (ISO 8601 format). ```rust assert_eq!(dt.format("%c").to_string(), "Sun Jul 8 00:34:60 2001"); assert_eq!(dt.format("%+").to_string(), "2001-07-08T00:34:60.026490708+09:30"); ``` -------------------------------- ### Get current local time Source: https://docs.rs/chrono/latest/chrono/struct.Local.html Get the current local date and time, including the offset from UTC. This is useful for logging or displaying local timestamps. ```rust // Current local time let now = Local::now(); // Current local date let today = now.date_naive(); // Current local time, converted to `DateTime` let now_fixed_offset = Local::now().fixed_offset(); // or let now_fixed_offset: DateTime = Local::now().into(); // Current time in some timezone (let's use +05:00) // Note that it is usually more efficient to use `Utc::now` for this use case. let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); let now_with_offset = Local::now().with_timezone(&offset); ``` -------------------------------- ### Create and Format NaiveTime Source: https://docs.rs/chrono/latest/src/chrono/naive/time/mod.rs.html Demonstrates creating NaiveTime objects with different precision levels and formatting them into strings. Supports hours, minutes, seconds, milliseconds, microseconds, and nanoseconds. Leap seconds are handled by allowing seconds to be 60. ```rust use chrono::NaiveTime; assert_eq!(format!("{}", NaiveTime::from_hms_opt(23, 56, 4).unwrap()), "23:56:04"); assert_eq!( format!("{}", NaiveTime::from_hms_milli_opt(23, 56, 4, 12).unwrap()), "23:56:04.012" ); assert_eq!( format!("{}", NaiveTime::from_hms_micro_opt(23, 56, 4, 1234).unwrap()), "23:56:04.001234" ); assert_eq!( format!("{}", NaiveTime::from_hms_nano_opt(23, 56, 4, 123456).unwrap()), "23:56:04.000123456" ); ``` ```rust # use chrono::NaiveTime; assert_eq!( format!("{}", NaiveTime::from_hms_milli_opt(6, 59, 59, 1_500).unwrap()), "06:59:60.500" ); ``` -------------------------------- ### Safely Get Err Value (Nightly) Source: https://docs.rs/chrono/latest/chrono/format/type.ParseResult.html Use `into_err` to get the contained `Err` value without panicking. This is an experimental API that never panics. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Create TimeZone with Different Rules Source: https://docs.rs/chrono/latest/src/chrono/offset/local/tz_info/timezone.rs.html Demonstrates creating `TimeZone` instances with varying transition rules, including fixed offsets and custom transition points. Useful for setting up specific time zone behaviors. ```rust let utc_local_time_types = vec![utc]; let fixed_extra_rule = TransitionRule::from(cet); let time_zone_1 = TimeZone::new(vec![], utc_local_time_types.clone(), vec![], None)?; let time_zone_2 = TimeZone::new(vec![], utc_local_time_types.clone(), vec![], Some(fixed_extra_rule))?; let time_zone_3 = TimeZone::new(vec![Transition::new(0, 0)], utc_local_time_types.clone(), vec![], None)?; let time_zone_4 = TimeZone::new( vec![Transition::new(i32::MIN.into(), 0), Transition::new(0, 1)], vec![utc, cet], Vec::new(), Some(fixed_extra_rule), )?; ``` -------------------------------- ### Safely Get Ok Value (Nightly) Source: https://docs.rs/chrono/latest/chrono/format/type.ParseResult.html Use `into_ok` to get the contained `Ok` value without panicking. This is an experimental API that never panics. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Get Local Time Offset from UTC Source: https://docs.rs/chrono/latest/src/chrono/offset/fixed.rs.html Returns the number of seconds that should be added to UTC to get the local time. This is the offset value used to construct the `FixedOffset`. ```rust pub const fn local_minus_utc(&self) -> i32 { self.local_minus_utc } ``` -------------------------------- ### Example: Parse DateTime and Remainder Source: https://docs.rs/chrono/latest/src/chrono/datetime/mod.rs.html Shows how to parse a `DateTime` from a string and capture any remaining text after the parsed date and time. ```rust use chrono::{DateTime, FixedOffset, TimeZone}; let (datetime, remainder) = DateTime::parse_and_remainder( "2015-02-18 23:16:09 +0200 trailing text", "%Y-%m-%d %H:%M:%S %z", ) .unwrap(); assert_eq!( datetime, FixedOffset::east_opt(2 * 3600).unwrap().with_ymd_and_hms(2015, 2, 18, 23, 16, 9).unwrap() ); assert_eq!(remainder, " trailing text"); ``` -------------------------------- ### NaiveDate Debug Formatting Examples Source: https://docs.rs/chrono/latest/src/chrono/naive/date/mod.rs.html Demonstrates the Debug formatting of NaiveDate for various year ranges, including standard, zero, maximum, and out-of-range years. ```rust assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(2015, 9, 5).unwrap()), "2015-09-05"); assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(0, 1, 1).unwrap()), "0000-01-01"); assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(9999, 12, 31).unwrap()), "9999-12-31"); ``` ```rust assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(-1, 1, 1).unwrap()), "-0001-01-01"); assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(10000, 12, 31).unwrap()), "+10000-12-31"); ``` -------------------------------- ### Get Local Offset from UTC Datetime Source: https://docs.rs/chrono/latest/src/chrono/offset/local/unix.rs.html Use this function to get the local timezone offset for a given UTC datetime. It utilizes a cached timezone lookup. ```rust pub(super) fn offset_from_utc_datetime(utc: &NaiveDateTime) -> MappedLocalTime { offset(utc, false) } ``` -------------------------------- ### Get Local Offset from Local Datetime Source: https://docs.rs/chrono/latest/src/chrono/offset/local/unix.rs.html Use this function to get the local timezone offset for a given naive local datetime. It relies on a cached timezone lookup. ```rust pub(super) fn offset_from_local_datetime(local: &NaiveDateTime) -> MappedLocalTime { offset(local, true) } ``` -------------------------------- ### TransitionRule with Negative Time Offsets Source: https://docs.rs/chrono/latest/src/chrono/offset/local/tz_info/rule.rs.html Demonstrates creating and using a TransitionRule with negative time offsets. It verifies the correct offset is found for given timestamps. ```rust let transition_rule_negative_time_2 = TransitionRule::from(AlternateTime::new( LocalTimeType::new(-10800, false, Some(b"-03"))?, LocalTimeType::new(-7200, true, Some(b"-02"))?, RuleDay::month_weekday(3, 5, 0)?, -7200, RuleDay::month_weekday(10, 5, 0)?, -3600, )?); assert_eq!( transition_rule_negative_time_2.find_local_time_type(954032399)?.offset(), -10800 ); assert_eq!( transition_rule_negative_time_2.find_local_time_type(954032400)?.offset(), -7200 ); assert_eq!( transition_rule_negative_time_2.find_local_time_type(972781199)?.offset(), -7200 ); assert_eq!( transition_rule_negative_time_2.find_local_time_type(972781200)?.offset(), -10800 ); ``` -------------------------------- ### Iterating through Weekdays Source: https://docs.rs/chrono/latest/src/chrono/weekday_set.rs.html Use this method to create an iterator that yields weekdays from the set, starting from a specified day. The iteration order depends on the starting day and the days present in the set. ```rust let mut iter = weekdays.iter(Wed); assert_eq!(iter.next(), Some(Wed)); assert_eq!(iter.next(), Some(Fri)); assert_eq!(iter.next(), Some(Mon)); assert_eq!(iter.next(), None); ``` -------------------------------- ### Example: Adding TimeDelta to NaiveDate Source: https://docs.rs/chrono/latest/src/chrono/naive/date/mod.rs.html Demonstrates adding positive and negative TimeDelta values to a NaiveDate, including handling leap years. ```rust assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(1).unwrap(), from_ymd(2014, 1, 2)); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(-1).unwrap(), from_ymd(2013, 12, 31)); assert_eq!(from_ymd(2014, 1, 1) + TimeDelta::try_days(364).unwrap(), from_ymd(2014, 12, 31)); assert_eq!( from_ymd(2014, 1, 1) + TimeDelta::try_days(365 * 4 + 1).unwrap(), from_ymd(2018, 1, 1) ); assert_eq!( from_ymd(2014, 1, 1) + TimeDelta::try_days(365 * 400 + 97).unwrap(), from_ymd(2414, 1, 1) ); ``` -------------------------------- ### Create NaiveDateTime from NaiveDate Source: https://docs.rs/chrono/latest/src/chrono/naive/datetime/mod.rs.html Demonstrates creating a NaiveDateTime by combining a NaiveDate with a NaiveTime. This is a common way to construct a NaiveDateTime. ```rust use chrono::{NaiveDate, NaiveDateTime}; let dt: NaiveDateTime = NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap(); # let _ = dt; ``` -------------------------------- ### Test NaiveWeek hashing Source: https://docs.rs/chrono/latest/src/chrono/naive/mod.rs.html Verifies the hashing implementation for NaiveWeek. Weeks with the same date and start weekday produce the same hash, while weeks with different start weekdays produce different hashes. ```rust #[test] fn test_naiveweek_hash() { let a = NaiveWeek { date: NaiveDate::from_ymd_opt(2025, 4, 3).unwrap(), start: Weekday::Mon }; let b = NaiveWeek { date: NaiveDate::from_ymd_opt(2025, 4, 4).unwrap(), start: Weekday::Mon }; let c = NaiveWeek { date: NaiveDate::from_ymd_opt(2025, 4, 3).unwrap(), start: Weekday::Sun }; let mut hasher = DefaultHasher::default(); a.hash(&mut hasher); let a_hash = hasher.finish(); hasher = DefaultHasher::default(); b.hash(&mut hasher); let b_hash = hasher.finish(); hasher = DefaultHasher::default(); c.hash(&mut hasher); let c_hash = hasher.finish(); assert_eq!(a_hash, b_hash); assert_ne!(b_hash, c_hash); assert_ne!(a_hash, c_hash); } ``` -------------------------------- ### TimeDelta Addition Wrap-around Examples Source: https://docs.rs/chrono/latest/chrono/struct.TimeDelta.html Illustrates how TimeDelta addition wraps around for large positive and negative second values, affecting the time of day. ```rust assert_eq!(from_hmsm(3, 5, 7, 0) + TimeDelta::try_seconds(22*60*60).unwrap(), from_hmsm(1, 5, 7, 0)); assert_eq!(from_hmsm(3, 5, 7, 0) + TimeDelta::try_seconds(-8*60*60).unwrap(), from_hmsm(19, 5, 7, 0)); assert_eq!(from_hmsm(3, 5, 7, 0) + TimeDelta::try_days(800).unwrap(), from_hmsm(3, 5, 7, 0)); ``` -------------------------------- ### Getting Current Local Time Source: https://docs.rs/chrono/latest/src/chrono/offset/local/mod.rs.html Demonstrates how to get the current local date and time using the `Local` timezone. It also shows how to convert this to a `DateTime` and how to specify a custom offset. ```APIDOC ## Getting Current Local Time ### Description This section shows how to obtain the current local time and date, and how to convert it to other timezone representations. ### Usage ```rust use chrono::{DateTime, FixedOffset, Local}; // Current local time let now = Local::now(); // Current local date let today = now.date_naive(); // Current local time, converted to `DateTime` let now_fixed_offset = Local::now().fixed_offset(); // or let now_fixed_offset: DateTime = Local::now().into(); // Current time in some timezone (e.g., +05:00) // Note: It is usually more efficient to use `Utc::now` for this use case. let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); let now_with_offset = Local::now().with_timezone(&offset); ``` ### Function Signature ```rust pub fn now() -> DateTime ``` ### Returns A `DateTime` representing the current local time. ``` -------------------------------- ### try_from Source: https://docs.rs/chrono/latest/chrono/format/enum.Numeric.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Get Current Local Time in Chrono Source: https://docs.rs/chrono/latest/src/chrono/offset/local/mod.rs.html Demonstrates how to get the current local date and time using `Local::now()`. It also shows conversion to `DateTime` and how to apply a specific offset. ```rust /// use chrono::{DateTime, FixedOffset, Local}; /// // Current local time /// let now = Local::now(); /// /// // Current local date /// let today = now.date_naive(); /// /// // Current local time, converted to `DateTime` /// let now_fixed_offset = Local::now().fixed_offset(); /// // or /// let now_fixed_offset: DateTime = Local::now().into(); /// /// // Current time in some timezone (let's use +05:00) /// // Note that it is usually more efficient to use `Utc::now` for this use case. /// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); /// let now_with_offset = Local::now().with_timezone(&offset); /// ``` ```