Skip to content

Commit

Permalink
Add some examples to Utc::now and Local::now
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Aug 3, 2023
1 parent bce5485 commit e39078c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
28 changes: 27 additions & 1 deletion src/offset/local/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,33 @@ impl Local {
Local::now().date()
}

/// Returns a `DateTime` which corresponds to the current date and time.
/// Returns a `DateTime<Local>` which corresponds to the current date, time and offset from
/// UTC.
///
/// See also the similar [`Utc::now()`] which returns `DateTime<Utc>`, 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<FixedOffset>`
/// let now_fixed_offset = Local::now().fixed_offset();
/// // or
/// let now_fixed_offset: DateTime<FixedOffset> = 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<Local> {
Utc::now().with_timezone(&Local)
}
Expand Down
23 changes: 22 additions & 1 deletion src/offset/utc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,28 @@ impl Utc {
Utc::now().date()
}

/// Returns a `DateTime` which corresponds to the current date and time.
/// Returns a `DateTime<Utc>` which corresponds to the current date and time in UTC.
///
/// See also the similar [`Local::now()`] which returns `DateTime<Local>`, 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",
Expand Down

0 comments on commit e39078c

Please sign in to comment.