@@ -25,7 +25,7 @@ use crate::format::{write_rfc2822, write_rfc3339, DelayedFormat, SecondsFormat};
2525use crate :: naive:: { Days , IsoWeek , NaiveDate , NaiveDateTime , NaiveTime } ;
2626#[ cfg( feature = "clock" ) ]
2727use crate :: offset:: Local ;
28- use crate :: offset:: { FixedOffset , Offset , TimeZone , Utc } ;
28+ use crate :: offset:: { FixedOffset , LocalResult , Offset , TimeZone , Utc } ;
2929#[ allow( deprecated) ]
3030use crate :: Date ;
3131use crate :: { expect, try_opt} ;
@@ -684,6 +684,30 @@ impl<Tz: TimeZone> DateTime<Tz> {
684684 result
685685 }
686686
687+ /// Set the time to a new fixed time on the existing date.
688+ ///
689+ /// # Errors
690+ ///
691+ /// Returns `LocalResult::None` if the datetime is at the edge of the representable range for a
692+ /// `DateTime`, and `with_time` would push the value in UTC out of range.
693+ ///
694+ /// # Example
695+ ///
696+ #[ cfg_attr( not( feature = "clock" ) , doc = "```ignore" ) ]
697+ #[ cfg_attr( feature = "clock" , doc = "```rust" ) ]
698+ /// # use chrono::{Local, NaiveTime};
699+ /// let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
700+ /// let today_noon = Local::now().with_time(noon);
701+ /// let today_midnight = Local::now().with_time(NaiveTime::MIN);
702+ ///
703+ /// assert_eq!(today_noon.single().unwrap().time(), noon);
704+ /// assert_eq!(today_midnight.single().unwrap().time(), NaiveTime::MIN);
705+ /// ```
706+ #[ must_use]
707+ pub fn with_time ( & self , time : NaiveTime ) -> LocalResult < Self > {
708+ self . timezone ( ) . from_local_datetime ( & self . overflowing_naive_local ( ) . date ( ) . and_time ( time) )
709+ }
710+
687711 /// The minimum possible `DateTime<Utc>`.
688712 pub const MIN_UTC : DateTime < Utc > = DateTime { datetime : NaiveDateTime :: MIN , offset : Utc } ;
689713 /// The maximum possible `DateTime<Utc>`.
0 commit comments