Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DateTime::with_time() #1510

Merged
merged 1 commit into from
Mar 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::format::{write_rfc2822, write_rfc3339, DelayedFormat, SecondsFormat};
use crate::naive::{Days, IsoWeek, NaiveDate, NaiveDateTime, NaiveTime};
#[cfg(feature = "clock")]
use crate::offset::Local;
use crate::offset::{FixedOffset, Offset, TimeZone, Utc};
use crate::offset::{FixedOffset, LocalResult, Offset, TimeZone, Utc};
#[allow(deprecated)]
use crate::Date;
use crate::{expect, try_opt};
Expand Down Expand Up @@ -684,6 +684,31 @@ impl<Tz: TimeZone> DateTime<Tz> {
result
}

/// Set the time to a new fixed time on the existing date.
///
/// # Errors
///
/// Returns `LocalResult::None` if the datetime is at the edge of the representable range for a
/// `DateTime`, and `with_time` would push the value in UTC out of range.
///
/// # Example
///
#[cfg_attr(not(feature = "clock"), doc = "```ignore")]
#[cfg_attr(feature = "clock", doc = "```rust")]
/// use chrono::{Local, NaiveTime};
///
/// let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
/// let today_noon = Local::now().with_time(noon);
/// let today_midnight = Local::now().with_time(NaiveTime::MIN);
///
/// assert_eq!(today_noon.single().unwrap().time(), noon);
/// assert_eq!(today_midnight.single().unwrap().time(), NaiveTime::MIN);
/// ```
#[must_use]
pub fn with_time(&self, time: NaiveTime) -> LocalResult<Self> {
self.timezone().from_local_datetime(&self.overflowing_naive_local().date().and_time(time))
}

/// The minimum possible `DateTime<Utc>`.
pub const MIN_UTC: DateTime<Utc> = DateTime { datetime: NaiveDateTime::MIN, offset: Utc };
/// The maximum possible `DateTime<Utc>`.
Expand Down
Loading