Skip to content

Commit

Permalink
Add a set_time method to DateTime
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Apr 18, 2023
1 parent 93e2a91 commit fae0ea4
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use crate::oldtime::Duration as OldDuration;
#[allow(deprecated)]
use crate::Date;
use crate::Months;
use crate::{Datelike, Timelike, Weekday};
use crate::{Datelike, LocalResult, Timelike, Weekday};

#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize, Serialize};
Expand Down Expand Up @@ -325,6 +325,23 @@ impl<Tz: TimeZone> DateTime<Tz> {
tz.from_utc_datetime(&self.datetime)
}

/// Set the time to a new fixed time on the existing date, taking into account timezone
/// effects such as DST transitions.
///
/// # Example
///
/// ```
/// let midnight = DateTime::from_hms_opt(0, 0, 0).unwrap();
/// let today_midnight = Local::now().set_time(midnight);
///
/// assert_eq!(today_midnight.unwrap().time(), midnight);
/// ```
#[must_use]
pub fn set_time(&self, time: NaiveTime) -> LocalResult<Self> {
let timezone: Tz = TimeZone::from_offset(&self.offset);
timezone.from_local_datetime(&self.date_naive().and_time(time))
}

/// Adds given `Duration` to the current date and time.
///
/// Returns `None` when it will result in overflow.
Expand Down

0 comments on commit fae0ea4

Please sign in to comment.