From 03468b2d068f5b5fb120c867588723fbf91c0a34 Mon Sep 17 00:00:00 2001 From: Paul Dicker Date: Thu, 20 Jul 2023 13:12:40 +0200 Subject: [PATCH] Add some examples to `Utc::now` and `Local::now` --- src/offset/local/mod.rs | 28 +++++++++++++++++++++++++++- src/offset/utc.rs | 23 ++++++++++++++++++++++- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/offset/local/mod.rs b/src/offset/local/mod.rs index 9e7d30335a..a710d081de 100644 --- a/src/offset/local/mod.rs +++ b/src/offset/local/mod.rs @@ -113,7 +113,33 @@ impl Local { Local::now().date() } - /// Returns a `DateTime` which corresponds to the current date and time. + /// Returns a `DateTime` which corresponds to the current date, time and offset from + /// UTC. + /// + /// See also the similar [`Utc::now()`] which returns `DateTime`, i.e. without the local + /// offset. + /// + /// # Example + /// + /// ``` + /// # #![allow(unused_variables)] + /// # 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); + /// ``` pub fn now() -> DateTime { Utc::now().with_timezone(&Local) } diff --git a/src/offset/utc.rs b/src/offset/utc.rs index dbcb8eecbb..7d31a3365c 100644 --- a/src/offset/utc.rs +++ b/src/offset/utc.rs @@ -59,7 +59,28 @@ impl Utc { Utc::now().date() } - /// Returns a `DateTime` which corresponds to the current date and time. + /// Returns a `DateTime` which corresponds to the current date and time in UTC. + /// + /// See also the similar [`Local::now()`] which returns `DateTime`, i.e. the local date + /// and time including offset from UTC. + /// + /// [`Local::now()`]: crate::Local::now + /// + /// # Example + /// + /// ``` + /// # #![allow(unused_variables)] + /// # use chrono::{FixedOffset, Utc}; + /// // Current time in UTC + /// let now_utc = Utc::now(); + /// + /// // Current date in UTC + /// let today_utc = now_utc.date_naive(); + /// + /// // Current time in some timezone (let's use +05:00) + /// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); + /// let now_with_offset = Utc::now().with_timezone(&offset); + /// ``` #[cfg(not(all( target_arch = "wasm32", feature = "wasmbind",