@@ -25,7 +25,7 @@ use crate::format::{write_rfc2822, write_rfc3339, DelayedFormat, SecondsFormat};
25
25
use crate :: naive:: { Days , IsoWeek , NaiveDate , NaiveDateTime , NaiveTime } ;
26
26
#[ cfg( feature = "clock" ) ]
27
27
use crate :: offset:: Local ;
28
- use crate :: offset:: { FixedOffset , Offset , TimeZone , Utc } ;
28
+ use crate :: offset:: { FixedOffset , LocalResult , Offset , TimeZone , Utc } ;
29
29
#[ allow( deprecated) ]
30
30
use crate :: Date ;
31
31
use crate :: { expect, try_opt} ;
@@ -684,6 +684,30 @@ impl<Tz: TimeZone> DateTime<Tz> {
684
684
result
685
685
}
686
686
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
+
687
711
/// The minimum possible `DateTime<Utc>`.
688
712
pub const MIN_UTC : DateTime < Utc > = DateTime { datetime : NaiveDateTime :: MIN , offset : Utc } ;
689
713
/// The maximum possible `DateTime<Utc>`.
0 commit comments