• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
3 
4 //! ISO 8601 date and time without timezone.
5 
6 #[cfg(feature = "alloc")]
7 use core::borrow::Borrow;
8 use core::fmt::Write;
9 use core::ops::{Add, AddAssign, Sub, SubAssign};
10 use core::time::Duration;
11 use core::{fmt, str};
12 
13 #[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
14 use rkyv::{Archive, Deserialize, Serialize};
15 
16 #[cfg(feature = "alloc")]
17 use crate::format::DelayedFormat;
18 use crate::format::{parse, parse_and_remainder, ParseError, ParseResult, Parsed, StrftimeItems};
19 use crate::format::{Fixed, Item, Numeric, Pad};
20 use crate::naive::{Days, IsoWeek, NaiveDate, NaiveTime};
21 use crate::offset::Utc;
22 use crate::time_delta::NANOS_PER_SEC;
23 use crate::{
24     expect, try_opt, DateTime, Datelike, FixedOffset, MappedLocalTime, Months, TimeDelta, TimeZone,
25     Timelike, Weekday,
26 };
27 
28 /// Tools to help serializing/deserializing `NaiveDateTime`s
29 #[cfg(feature = "serde")]
30 pub(crate) mod serde;
31 
32 #[cfg(test)]
33 mod tests;
34 
35 /// The minimum possible `NaiveDateTime`.
36 #[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MIN instead")]
37 pub const MIN_DATETIME: NaiveDateTime = NaiveDateTime::MIN;
38 /// The maximum possible `NaiveDateTime`.
39 #[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MAX instead")]
40 pub const MAX_DATETIME: NaiveDateTime = NaiveDateTime::MAX;
41 
42 /// ISO 8601 combined date and time without timezone.
43 ///
44 /// # Example
45 ///
46 /// `NaiveDateTime` is commonly created from [`NaiveDate`].
47 ///
48 /// ```
49 /// use chrono::{NaiveDate, NaiveDateTime};
50 ///
51 /// let dt: NaiveDateTime =
52 ///     NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap();
53 /// # let _ = dt;
54 /// ```
55 ///
56 /// You can use typical [date-like](Datelike) and [time-like](Timelike) methods,
57 /// provided that relevant traits are in the scope.
58 ///
59 /// ```
60 /// # use chrono::{NaiveDate, NaiveDateTime};
61 /// # let dt: NaiveDateTime = NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap();
62 /// use chrono::{Datelike, Timelike, Weekday};
63 ///
64 /// assert_eq!(dt.weekday(), Weekday::Fri);
65 /// assert_eq!(dt.num_seconds_from_midnight(), 33011);
66 /// ```
67 #[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
68 #[cfg_attr(
69     any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
70     derive(Archive, Deserialize, Serialize),
71     archive(compare(PartialEq, PartialOrd)),
72     archive_attr(derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash))
73 )]
74 #[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
75 #[cfg_attr(all(feature = "arbitrary", feature = "std"), derive(arbitrary::Arbitrary))]
76 pub struct NaiveDateTime {
77     date: NaiveDate,
78     time: NaiveTime,
79 }
80 
81 impl NaiveDateTime {
82     /// Makes a new `NaiveDateTime` from date and time components.
83     /// Equivalent to [`date.and_time(time)`](./struct.NaiveDate.html#method.and_time)
84     /// and many other helper constructors on `NaiveDate`.
85     ///
86     /// # Example
87     ///
88     /// ```
89     /// use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
90     ///
91     /// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
92     /// let t = NaiveTime::from_hms_milli_opt(12, 34, 56, 789).unwrap();
93     ///
94     /// let dt = NaiveDateTime::new(d, t);
95     /// assert_eq!(dt.date(), d);
96     /// assert_eq!(dt.time(), t);
97     /// ```
98     #[inline]
new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime99     pub const fn new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime {
100         NaiveDateTime { date, time }
101     }
102 
103     /// Makes a new `NaiveDateTime` corresponding to a UTC date and time,
104     /// from the number of non-leap seconds
105     /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp")
106     /// and the number of nanoseconds since the last whole non-leap second.
107     ///
108     /// For a non-naive version of this function see [`TimeZone::timestamp`].
109     ///
110     /// The nanosecond part can exceed 1,000,000,000 in order to represent a
111     /// [leap second](NaiveTime#leap-second-handling), but only when `secs % 60 == 59`.
112     /// (The true "UNIX timestamp" cannot represent a leap second unambiguously.)
113     ///
114     /// # Panics
115     ///
116     /// Panics if the number of seconds would be out of range for a `NaiveDateTime` (more than
117     /// ca. 262,000 years away from common era), and panics on an invalid nanosecond (2 seconds or
118     /// more).
119     #[deprecated(since = "0.4.23", note = "use `DateTime::from_timestamp` instead")]
120     #[inline]
121     #[must_use]
from_timestamp(secs: i64, nsecs: u32) -> NaiveDateTime122     pub const fn from_timestamp(secs: i64, nsecs: u32) -> NaiveDateTime {
123         let datetime =
124             expect(DateTime::from_timestamp(secs, nsecs), "invalid or out-of-range datetime");
125         datetime.naive_utc()
126     }
127 
128     /// Creates a new [NaiveDateTime] from milliseconds since the UNIX epoch.
129     ///
130     /// The UNIX epoch starts on midnight, January 1, 1970, UTC.
131     ///
132     /// # Errors
133     ///
134     /// Returns `None` if the number of milliseconds would be out of range for a `NaiveDateTime`
135     /// (more than ca. 262,000 years away from common era)
136     #[deprecated(since = "0.4.35", note = "use `DateTime::from_timestamp_millis` instead")]
137     #[inline]
138     #[must_use]
from_timestamp_millis(millis: i64) -> Option<NaiveDateTime>139     pub const fn from_timestamp_millis(millis: i64) -> Option<NaiveDateTime> {
140         Some(try_opt!(DateTime::from_timestamp_millis(millis)).naive_utc())
141     }
142 
143     /// Creates a new [NaiveDateTime] from microseconds since the UNIX epoch.
144     ///
145     /// The UNIX epoch starts on midnight, January 1, 1970, UTC.
146     ///
147     /// # Errors
148     ///
149     /// Returns `None` if the number of microseconds would be out of range for a `NaiveDateTime`
150     /// (more than ca. 262,000 years away from common era)
151     #[deprecated(since = "0.4.35", note = "use `DateTime::from_timestamp_micros` instead")]
152     #[inline]
153     #[must_use]
from_timestamp_micros(micros: i64) -> Option<NaiveDateTime>154     pub const fn from_timestamp_micros(micros: i64) -> Option<NaiveDateTime> {
155         let secs = micros.div_euclid(1_000_000);
156         let nsecs = micros.rem_euclid(1_000_000) as u32 * 1000;
157         Some(try_opt!(DateTime::<Utc>::from_timestamp(secs, nsecs)).naive_utc())
158     }
159 
160     /// Creates a new [NaiveDateTime] from nanoseconds since the UNIX epoch.
161     ///
162     /// The UNIX epoch starts on midnight, January 1, 1970, UTC.
163     ///
164     /// # Errors
165     ///
166     /// Returns `None` if the number of nanoseconds would be out of range for a `NaiveDateTime`
167     /// (more than ca. 262,000 years away from common era)
168     #[deprecated(since = "0.4.35", note = "use `DateTime::from_timestamp_nanos` instead")]
169     #[inline]
170     #[must_use]
from_timestamp_nanos(nanos: i64) -> Option<NaiveDateTime>171     pub const fn from_timestamp_nanos(nanos: i64) -> Option<NaiveDateTime> {
172         let secs = nanos.div_euclid(NANOS_PER_SEC as i64);
173         let nsecs = nanos.rem_euclid(NANOS_PER_SEC as i64) as u32;
174         Some(try_opt!(DateTime::from_timestamp(secs, nsecs)).naive_utc())
175     }
176 
177     /// Makes a new `NaiveDateTime` corresponding to a UTC date and time,
178     /// from the number of non-leap seconds
179     /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp")
180     /// and the number of nanoseconds since the last whole non-leap second.
181     ///
182     /// The nanosecond part can exceed 1,000,000,000 in order to represent a
183     /// [leap second](NaiveTime#leap-second-handling), but only when `secs % 60 == 59`.
184     /// (The true "UNIX timestamp" cannot represent a leap second unambiguously.)
185     ///
186     /// # Errors
187     ///
188     /// Returns `None` if the number of seconds would be out of range for a `NaiveDateTime` (more
189     /// than ca. 262,000 years away from common era), and panics on an invalid nanosecond
190     /// (2 seconds or more).
191     #[deprecated(since = "0.4.35", note = "use `DateTime::from_timestamp` instead")]
192     #[inline]
193     #[must_use]
from_timestamp_opt(secs: i64, nsecs: u32) -> Option<NaiveDateTime>194     pub const fn from_timestamp_opt(secs: i64, nsecs: u32) -> Option<NaiveDateTime> {
195         Some(try_opt!(DateTime::from_timestamp(secs, nsecs)).naive_utc())
196     }
197 
198     /// Parses a string with the specified format string and returns a new `NaiveDateTime`.
199     /// See the [`format::strftime` module](crate::format::strftime)
200     /// on the supported escape sequences.
201     ///
202     /// # Example
203     ///
204     /// ```
205     /// use chrono::{NaiveDate, NaiveDateTime};
206     ///
207     /// let parse_from_str = NaiveDateTime::parse_from_str;
208     ///
209     /// assert_eq!(
210     ///     parse_from_str("2015-09-05 23:56:04", "%Y-%m-%d %H:%M:%S"),
211     ///     Ok(NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().and_hms_opt(23, 56, 4).unwrap())
212     /// );
213     /// assert_eq!(
214     ///     parse_from_str("5sep2015pm012345.6789", "%d%b%Y%p%I%M%S%.f"),
215     ///     Ok(NaiveDate::from_ymd_opt(2015, 9, 5)
216     ///         .unwrap()
217     ///         .and_hms_micro_opt(13, 23, 45, 678_900)
218     ///         .unwrap())
219     /// );
220     /// ```
221     ///
222     /// Offset is ignored for the purpose of parsing.
223     ///
224     /// ```
225     /// # use chrono::{NaiveDateTime, NaiveDate};
226     /// # let parse_from_str = NaiveDateTime::parse_from_str;
227     /// assert_eq!(
228     ///     parse_from_str("2014-5-17T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
229     ///     Ok(NaiveDate::from_ymd_opt(2014, 5, 17).unwrap().and_hms_opt(12, 34, 56).unwrap())
230     /// );
231     /// ```
232     ///
233     /// [Leap seconds](./struct.NaiveTime.html#leap-second-handling) are correctly handled by
234     /// treating any time of the form `hh:mm:60` as a leap second.
235     /// (This equally applies to the formatting, so the round trip is possible.)
236     ///
237     /// ```
238     /// # use chrono::{NaiveDateTime, NaiveDate};
239     /// # let parse_from_str = NaiveDateTime::parse_from_str;
240     /// assert_eq!(
241     ///     parse_from_str("2015-07-01 08:59:60.123", "%Y-%m-%d %H:%M:%S%.f"),
242     ///     Ok(NaiveDate::from_ymd_opt(2015, 7, 1)
243     ///         .unwrap()
244     ///         .and_hms_milli_opt(8, 59, 59, 1_123)
245     ///         .unwrap())
246     /// );
247     /// ```
248     ///
249     /// Missing seconds are assumed to be zero,
250     /// but out-of-bound times or insufficient fields are errors otherwise.
251     ///
252     /// ```
253     /// # use chrono::{NaiveDateTime, NaiveDate};
254     /// # let parse_from_str = NaiveDateTime::parse_from_str;
255     /// assert_eq!(
256     ///     parse_from_str("94/9/4 7:15", "%y/%m/%d %H:%M"),
257     ///     Ok(NaiveDate::from_ymd_opt(1994, 9, 4).unwrap().and_hms_opt(7, 15, 0).unwrap())
258     /// );
259     ///
260     /// assert!(parse_from_str("04m33s", "%Mm%Ss").is_err());
261     /// assert!(parse_from_str("94/9/4 12", "%y/%m/%d %H").is_err());
262     /// assert!(parse_from_str("94/9/4 17:60", "%y/%m/%d %H:%M").is_err());
263     /// assert!(parse_from_str("94/9/4 24:00:00", "%y/%m/%d %H:%M:%S").is_err());
264     /// ```
265     ///
266     /// All parsed fields should be consistent to each other, otherwise it's an error.
267     ///
268     /// ```
269     /// # use chrono::NaiveDateTime;
270     /// # let parse_from_str = NaiveDateTime::parse_from_str;
271     /// let fmt = "%Y-%m-%d %H:%M:%S = UNIX timestamp %s";
272     /// assert!(parse_from_str("2001-09-09 01:46:39 = UNIX timestamp 999999999", fmt).is_ok());
273     /// assert!(parse_from_str("1970-01-01 00:00:00 = UNIX timestamp 1", fmt).is_err());
274     /// ```
275     ///
276     /// Years before 1 BCE or after 9999 CE, require an initial sign
277     ///
278     ///```
279     /// # use chrono::NaiveDateTime;
280     /// # let parse_from_str = NaiveDateTime::parse_from_str;
281     /// let fmt = "%Y-%m-%d %H:%M:%S";
282     /// assert!(parse_from_str("10000-09-09 01:46:39", fmt).is_err());
283     /// assert!(parse_from_str("+10000-09-09 01:46:39", fmt).is_ok());
284     /// ```
parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime>285     pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime> {
286         let mut parsed = Parsed::new();
287         parse(&mut parsed, s, StrftimeItems::new(fmt))?;
288         parsed.to_naive_datetime_with_offset(0) // no offset adjustment
289     }
290 
291     /// Parses a string with the specified format string and returns a new `NaiveDateTime`, and a
292     /// slice with the remaining portion of the string.
293     /// See the [`format::strftime` module](crate::format::strftime)
294     /// on the supported escape sequences.
295     ///
296     /// Similar to [`parse_from_str`](#method.parse_from_str).
297     ///
298     /// # Example
299     ///
300     /// ```rust
301     /// # use chrono::{NaiveDate, NaiveDateTime};
302     /// let (datetime, remainder) = NaiveDateTime::parse_and_remainder(
303     ///     "2015-02-18 23:16:09 trailing text",
304     ///     "%Y-%m-%d %H:%M:%S",
305     /// )
306     /// .unwrap();
307     /// assert_eq!(
308     ///     datetime,
309     ///     NaiveDate::from_ymd_opt(2015, 2, 18).unwrap().and_hms_opt(23, 16, 9).unwrap()
310     /// );
311     /// assert_eq!(remainder, " trailing text");
312     /// ```
parse_and_remainder<'a>(s: &'a str, fmt: &str) -> ParseResult<(NaiveDateTime, &'a str)>313     pub fn parse_and_remainder<'a>(s: &'a str, fmt: &str) -> ParseResult<(NaiveDateTime, &'a str)> {
314         let mut parsed = Parsed::new();
315         let remainder = parse_and_remainder(&mut parsed, s, StrftimeItems::new(fmt))?;
316         parsed.to_naive_datetime_with_offset(0).map(|d| (d, remainder)) // no offset adjustment
317     }
318 
319     /// Retrieves a date component.
320     ///
321     /// # Example
322     ///
323     /// ```
324     /// use chrono::NaiveDate;
325     ///
326     /// let dt = NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap();
327     /// assert_eq!(dt.date(), NaiveDate::from_ymd_opt(2016, 7, 8).unwrap());
328     /// ```
329     #[inline]
date(&self) -> NaiveDate330     pub const fn date(&self) -> NaiveDate {
331         self.date
332     }
333 
334     /// Retrieves a time component.
335     ///
336     /// # Example
337     ///
338     /// ```
339     /// use chrono::{NaiveDate, NaiveTime};
340     ///
341     /// let dt = NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(9, 10, 11).unwrap();
342     /// assert_eq!(dt.time(), NaiveTime::from_hms_opt(9, 10, 11).unwrap());
343     /// ```
344     #[inline]
time(&self) -> NaiveTime345     pub const fn time(&self) -> NaiveTime {
346         self.time
347     }
348 
349     /// Returns the number of non-leap seconds since the midnight on January 1, 1970.
350     ///
351     /// Note that this does *not* account for the timezone!
352     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
353     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp()` instead")]
354     #[inline]
355     #[must_use]
timestamp(&self) -> i64356     pub const fn timestamp(&self) -> i64 {
357         self.and_utc().timestamp()
358     }
359 
360     /// Returns the number of non-leap *milliseconds* since midnight on January 1, 1970.
361     ///
362     /// Note that this does *not* account for the timezone!
363     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
364     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp_millis()` instead")]
365     #[inline]
366     #[must_use]
timestamp_millis(&self) -> i64367     pub const fn timestamp_millis(&self) -> i64 {
368         self.and_utc().timestamp_millis()
369     }
370 
371     /// Returns the number of non-leap *microseconds* since midnight on January 1, 1970.
372     ///
373     /// Note that this does *not* account for the timezone!
374     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
375     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp_micros()` instead")]
376     #[inline]
377     #[must_use]
timestamp_micros(&self) -> i64378     pub const fn timestamp_micros(&self) -> i64 {
379         self.and_utc().timestamp_micros()
380     }
381 
382     /// Returns the number of non-leap *nanoseconds* since midnight on January 1, 1970.
383     ///
384     /// Note that this does *not* account for the timezone!
385     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
386     ///
387     /// # Panics
388     ///
389     /// An `i64` with nanosecond precision can span a range of ~584 years. This function panics on
390     /// an out of range `NaiveDateTime`.
391     ///
392     /// The dates that can be represented as nanoseconds are between 1677-09-21T00:12:43.145224192
393     /// and 2262-04-11T23:47:16.854775807.
394     #[deprecated(since = "0.4.31", note = "use `.and_utc().timestamp_nanos_opt()` instead")]
395     #[inline]
396     #[must_use]
397     #[allow(deprecated)]
timestamp_nanos(&self) -> i64398     pub const fn timestamp_nanos(&self) -> i64 {
399         self.and_utc().timestamp_nanos()
400     }
401 
402     /// Returns the number of non-leap *nanoseconds* since midnight on January 1, 1970.
403     ///
404     /// Note that this does *not* account for the timezone!
405     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
406     ///
407     /// # Errors
408     ///
409     /// An `i64` with nanosecond precision can span a range of ~584 years. This function returns
410     /// `None` on an out of range `NaiveDateTime`.
411     ///
412     /// The dates that can be represented as nanoseconds are between 1677-09-21T00:12:43.145224192
413     /// and 2262-04-11T23:47:16.854775807.
414     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp_nanos_opt()` instead")]
415     #[inline]
416     #[must_use]
timestamp_nanos_opt(&self) -> Option<i64>417     pub const fn timestamp_nanos_opt(&self) -> Option<i64> {
418         self.and_utc().timestamp_nanos_opt()
419     }
420 
421     /// Returns the number of milliseconds since the last whole non-leap second.
422     ///
423     /// The return value ranges from 0 to 999,
424     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999.
425     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp_subsec_millis()` instead")]
426     #[inline]
427     #[must_use]
timestamp_subsec_millis(&self) -> u32428     pub const fn timestamp_subsec_millis(&self) -> u32 {
429         self.and_utc().timestamp_subsec_millis()
430     }
431 
432     /// Returns the number of microseconds since the last whole non-leap second.
433     ///
434     /// The return value ranges from 0 to 999,999,
435     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999,999.
436     #[deprecated(since = "0.4.35", note = "use `.and_utc().timestamp_subsec_micros()` instead")]
437     #[inline]
438     #[must_use]
timestamp_subsec_micros(&self) -> u32439     pub const fn timestamp_subsec_micros(&self) -> u32 {
440         self.and_utc().timestamp_subsec_micros()
441     }
442 
443     /// Returns the number of nanoseconds since the last whole non-leap second.
444     ///
445     /// The return value ranges from 0 to 999,999,999,
446     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999,999,999.
447     #[deprecated(since = "0.4.36", note = "use `.and_utc().timestamp_subsec_nanos()` instead")]
timestamp_subsec_nanos(&self) -> u32448     pub const fn timestamp_subsec_nanos(&self) -> u32 {
449         self.and_utc().timestamp_subsec_nanos()
450     }
451 
452     /// Adds given `TimeDelta` to the current date and time.
453     ///
454     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
455     /// the addition assumes that **there is no leap second ever**,
456     /// except when the `NaiveDateTime` itself represents a leap second
457     /// in which case the assumption becomes that **there is exactly a single leap second ever**.
458     ///
459     /// # Errors
460     ///
461     /// Returns `None` if the resulting date would be out of range.
462     ///
463     /// # Example
464     ///
465     /// ```
466     /// use chrono::{NaiveDate, TimeDelta};
467     ///
468     /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
469     ///
470     /// let d = from_ymd(2016, 7, 8);
471     /// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
472     /// assert_eq!(hms(3, 5, 7).checked_add_signed(TimeDelta::zero()), Some(hms(3, 5, 7)));
473     /// assert_eq!(
474     ///     hms(3, 5, 7).checked_add_signed(TimeDelta::try_seconds(1).unwrap()),
475     ///     Some(hms(3, 5, 8))
476     /// );
477     /// assert_eq!(
478     ///     hms(3, 5, 7).checked_add_signed(TimeDelta::try_seconds(-1).unwrap()),
479     ///     Some(hms(3, 5, 6))
480     /// );
481     /// assert_eq!(
482     ///     hms(3, 5, 7).checked_add_signed(TimeDelta::try_seconds(3600 + 60).unwrap()),
483     ///     Some(hms(4, 6, 7))
484     /// );
485     /// assert_eq!(
486     ///     hms(3, 5, 7).checked_add_signed(TimeDelta::try_seconds(86_400).unwrap()),
487     ///     Some(from_ymd(2016, 7, 9).and_hms_opt(3, 5, 7).unwrap())
488     /// );
489     ///
490     /// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
491     /// assert_eq!(
492     ///     hmsm(3, 5, 7, 980).checked_add_signed(TimeDelta::try_milliseconds(450).unwrap()),
493     ///     Some(hmsm(3, 5, 8, 430))
494     /// );
495     /// ```
496     ///
497     /// Overflow returns `None`.
498     ///
499     /// ```
500     /// # use chrono::{TimeDelta, NaiveDate};
501     /// # let hms = |h, m, s| NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(h, m, s).unwrap();
502     /// assert_eq!(hms(3, 5, 7).checked_add_signed(TimeDelta::try_days(1_000_000_000).unwrap()), None);
503     /// ```
504     ///
505     /// Leap seconds are handled,
506     /// but the addition assumes that it is the only leap second happened.
507     ///
508     /// ```
509     /// # use chrono::{TimeDelta, NaiveDate};
510     /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
511     /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
512     /// let leap = hmsm(3, 5, 59, 1_300);
513     /// assert_eq!(leap.checked_add_signed(TimeDelta::zero()),
514     ///            Some(hmsm(3, 5, 59, 1_300)));
515     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_milliseconds(-500).unwrap()),
516     ///            Some(hmsm(3, 5, 59, 800)));
517     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_milliseconds(500).unwrap()),
518     ///            Some(hmsm(3, 5, 59, 1_800)));
519     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_milliseconds(800).unwrap()),
520     ///            Some(hmsm(3, 6, 0, 100)));
521     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_seconds(10).unwrap()),
522     ///            Some(hmsm(3, 6, 9, 300)));
523     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_seconds(-10).unwrap()),
524     ///            Some(hmsm(3, 5, 50, 300)));
525     /// assert_eq!(leap.checked_add_signed(TimeDelta::try_days(1).unwrap()),
526     ///            Some(from_ymd(2016, 7, 9).and_hms_milli_opt(3, 5, 59, 300).unwrap()));
527     /// ```
528     #[must_use]
checked_add_signed(self, rhs: TimeDelta) -> Option<NaiveDateTime>529     pub const fn checked_add_signed(self, rhs: TimeDelta) -> Option<NaiveDateTime> {
530         let (time, remainder) = self.time.overflowing_add_signed(rhs);
531         let remainder = try_opt!(TimeDelta::try_seconds(remainder));
532         let date = try_opt!(self.date.checked_add_signed(remainder));
533         Some(NaiveDateTime { date, time })
534     }
535 
536     /// Adds given `Months` to the current date and time.
537     ///
538     /// Uses the last day of the month if the day does not exist in the resulting month.
539     ///
540     /// # Errors
541     ///
542     /// Returns `None` if the resulting date would be out of range.
543     ///
544     /// # Example
545     ///
546     /// ```
547     /// use chrono::{Months, NaiveDate};
548     ///
549     /// assert_eq!(
550     ///     NaiveDate::from_ymd_opt(2014, 1, 1)
551     ///         .unwrap()
552     ///         .and_hms_opt(1, 0, 0)
553     ///         .unwrap()
554     ///         .checked_add_months(Months::new(1)),
555     ///     Some(NaiveDate::from_ymd_opt(2014, 2, 1).unwrap().and_hms_opt(1, 0, 0).unwrap())
556     /// );
557     ///
558     /// assert_eq!(
559     ///     NaiveDate::from_ymd_opt(2014, 1, 1)
560     ///         .unwrap()
561     ///         .and_hms_opt(1, 0, 0)
562     ///         .unwrap()
563     ///         .checked_add_months(Months::new(core::i32::MAX as u32 + 1)),
564     ///     None
565     /// );
566     /// ```
567     #[must_use]
checked_add_months(self, rhs: Months) -> Option<NaiveDateTime>568     pub const fn checked_add_months(self, rhs: Months) -> Option<NaiveDateTime> {
569         Some(Self { date: try_opt!(self.date.checked_add_months(rhs)), time: self.time })
570     }
571 
572     /// Adds given `FixedOffset` to the current datetime.
573     /// Returns `None` if the result would be outside the valid range for [`NaiveDateTime`].
574     ///
575     /// This method is similar to [`checked_add_signed`](#method.checked_add_offset), but preserves
576     /// leap seconds.
577     #[must_use]
checked_add_offset(self, rhs: FixedOffset) -> Option<NaiveDateTime>578     pub const fn checked_add_offset(self, rhs: FixedOffset) -> Option<NaiveDateTime> {
579         let (time, days) = self.time.overflowing_add_offset(rhs);
580         let date = match days {
581             -1 => try_opt!(self.date.pred_opt()),
582             1 => try_opt!(self.date.succ_opt()),
583             _ => self.date,
584         };
585         Some(NaiveDateTime { date, time })
586     }
587 
588     /// Subtracts given `FixedOffset` from the current datetime.
589     /// Returns `None` if the result would be outside the valid range for [`NaiveDateTime`].
590     ///
591     /// This method is similar to [`checked_sub_signed`](#method.checked_sub_signed), but preserves
592     /// leap seconds.
checked_sub_offset(self, rhs: FixedOffset) -> Option<NaiveDateTime>593     pub const fn checked_sub_offset(self, rhs: FixedOffset) -> Option<NaiveDateTime> {
594         let (time, days) = self.time.overflowing_sub_offset(rhs);
595         let date = match days {
596             -1 => try_opt!(self.date.pred_opt()),
597             1 => try_opt!(self.date.succ_opt()),
598             _ => self.date,
599         };
600         Some(NaiveDateTime { date, time })
601     }
602 
603     /// Adds given `FixedOffset` to the current datetime.
604     /// The resulting value may be outside the valid range of [`NaiveDateTime`].
605     ///
606     /// This can be useful for intermediate values, but the resulting out-of-range `NaiveDate`
607     /// should not be exposed to library users.
608     #[must_use]
overflowing_add_offset(self, rhs: FixedOffset) -> NaiveDateTime609     pub(crate) fn overflowing_add_offset(self, rhs: FixedOffset) -> NaiveDateTime {
610         let (time, days) = self.time.overflowing_add_offset(rhs);
611         let date = match days {
612             -1 => self.date.pred_opt().unwrap_or(NaiveDate::BEFORE_MIN),
613             1 => self.date.succ_opt().unwrap_or(NaiveDate::AFTER_MAX),
614             _ => self.date,
615         };
616         NaiveDateTime { date, time }
617     }
618 
619     /// Subtracts given `FixedOffset` from the current datetime.
620     /// The resulting value may be outside the valid range of [`NaiveDateTime`].
621     ///
622     /// This can be useful for intermediate values, but the resulting out-of-range `NaiveDate`
623     /// should not be exposed to library users.
624     #[must_use]
625     #[allow(unused)] // currently only used in `Local` but not on all platforms
overflowing_sub_offset(self, rhs: FixedOffset) -> NaiveDateTime626     pub(crate) fn overflowing_sub_offset(self, rhs: FixedOffset) -> NaiveDateTime {
627         let (time, days) = self.time.overflowing_sub_offset(rhs);
628         let date = match days {
629             -1 => self.date.pred_opt().unwrap_or(NaiveDate::BEFORE_MIN),
630             1 => self.date.succ_opt().unwrap_or(NaiveDate::AFTER_MAX),
631             _ => self.date,
632         };
633         NaiveDateTime { date, time }
634     }
635 
636     /// Subtracts given `TimeDelta` from the current date and time.
637     ///
638     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
639     /// the subtraction assumes that **there is no leap second ever**,
640     /// except when the `NaiveDateTime` itself represents a leap second
641     /// in which case the assumption becomes that **there is exactly a single leap second ever**.
642     ///
643     /// # Errors
644     ///
645     /// Returns `None` if the resulting date would be out of range.
646     ///
647     /// # Example
648     ///
649     /// ```
650     /// use chrono::{NaiveDate, TimeDelta};
651     ///
652     /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
653     ///
654     /// let d = from_ymd(2016, 7, 8);
655     /// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
656     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(TimeDelta::zero()), Some(hms(3, 5, 7)));
657     /// assert_eq!(
658     ///     hms(3, 5, 7).checked_sub_signed(TimeDelta::try_seconds(1).unwrap()),
659     ///     Some(hms(3, 5, 6))
660     /// );
661     /// assert_eq!(
662     ///     hms(3, 5, 7).checked_sub_signed(TimeDelta::try_seconds(-1).unwrap()),
663     ///     Some(hms(3, 5, 8))
664     /// );
665     /// assert_eq!(
666     ///     hms(3, 5, 7).checked_sub_signed(TimeDelta::try_seconds(3600 + 60).unwrap()),
667     ///     Some(hms(2, 4, 7))
668     /// );
669     /// assert_eq!(
670     ///     hms(3, 5, 7).checked_sub_signed(TimeDelta::try_seconds(86_400).unwrap()),
671     ///     Some(from_ymd(2016, 7, 7).and_hms_opt(3, 5, 7).unwrap())
672     /// );
673     ///
674     /// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
675     /// assert_eq!(
676     ///     hmsm(3, 5, 7, 450).checked_sub_signed(TimeDelta::try_milliseconds(670).unwrap()),
677     ///     Some(hmsm(3, 5, 6, 780))
678     /// );
679     /// ```
680     ///
681     /// Overflow returns `None`.
682     ///
683     /// ```
684     /// # use chrono::{TimeDelta, NaiveDate};
685     /// # let hms = |h, m, s| NaiveDate::from_ymd_opt(2016, 7, 8).unwrap().and_hms_opt(h, m, s).unwrap();
686     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(TimeDelta::try_days(1_000_000_000).unwrap()), None);
687     /// ```
688     ///
689     /// Leap seconds are handled,
690     /// but the subtraction assumes that it is the only leap second happened.
691     ///
692     /// ```
693     /// # use chrono::{TimeDelta, NaiveDate};
694     /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
695     /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
696     /// let leap = hmsm(3, 5, 59, 1_300);
697     /// assert_eq!(leap.checked_sub_signed(TimeDelta::zero()),
698     ///            Some(hmsm(3, 5, 59, 1_300)));
699     /// assert_eq!(leap.checked_sub_signed(TimeDelta::try_milliseconds(200).unwrap()),
700     ///            Some(hmsm(3, 5, 59, 1_100)));
701     /// assert_eq!(leap.checked_sub_signed(TimeDelta::try_milliseconds(500).unwrap()),
702     ///            Some(hmsm(3, 5, 59, 800)));
703     /// assert_eq!(leap.checked_sub_signed(TimeDelta::try_seconds(60).unwrap()),
704     ///            Some(hmsm(3, 5, 0, 300)));
705     /// assert_eq!(leap.checked_sub_signed(TimeDelta::try_days(1).unwrap()),
706     ///            Some(from_ymd(2016, 7, 7).and_hms_milli_opt(3, 6, 0, 300).unwrap()));
707     /// ```
708     #[must_use]
checked_sub_signed(self, rhs: TimeDelta) -> Option<NaiveDateTime>709     pub const fn checked_sub_signed(self, rhs: TimeDelta) -> Option<NaiveDateTime> {
710         let (time, remainder) = self.time.overflowing_sub_signed(rhs);
711         let remainder = try_opt!(TimeDelta::try_seconds(remainder));
712         let date = try_opt!(self.date.checked_sub_signed(remainder));
713         Some(NaiveDateTime { date, time })
714     }
715 
716     /// Subtracts given `Months` from the current date and time.
717     ///
718     /// Uses the last day of the month if the day does not exist in the resulting month.
719     ///
720     /// # Errors
721     ///
722     /// Returns `None` if the resulting date would be out of range.
723     ///
724     /// # Example
725     ///
726     /// ```
727     /// use chrono::{Months, NaiveDate};
728     ///
729     /// assert_eq!(
730     ///     NaiveDate::from_ymd_opt(2014, 1, 1)
731     ///         .unwrap()
732     ///         .and_hms_opt(1, 0, 0)
733     ///         .unwrap()
734     ///         .checked_sub_months(Months::new(1)),
735     ///     Some(NaiveDate::from_ymd_opt(2013, 12, 1).unwrap().and_hms_opt(1, 0, 0).unwrap())
736     /// );
737     ///
738     /// assert_eq!(
739     ///     NaiveDate::from_ymd_opt(2014, 1, 1)
740     ///         .unwrap()
741     ///         .and_hms_opt(1, 0, 0)
742     ///         .unwrap()
743     ///         .checked_sub_months(Months::new(core::i32::MAX as u32 + 1)),
744     ///     None
745     /// );
746     /// ```
747     #[must_use]
checked_sub_months(self, rhs: Months) -> Option<NaiveDateTime>748     pub const fn checked_sub_months(self, rhs: Months) -> Option<NaiveDateTime> {
749         Some(Self { date: try_opt!(self.date.checked_sub_months(rhs)), time: self.time })
750     }
751 
752     /// Add a duration in [`Days`] to the date part of the `NaiveDateTime`
753     ///
754     /// Returns `None` if the resulting date would be out of range.
755     #[must_use]
checked_add_days(self, days: Days) -> Option<Self>756     pub const fn checked_add_days(self, days: Days) -> Option<Self> {
757         Some(Self { date: try_opt!(self.date.checked_add_days(days)), ..self })
758     }
759 
760     /// Subtract a duration in [`Days`] from the date part of the `NaiveDateTime`
761     ///
762     /// Returns `None` if the resulting date would be out of range.
763     #[must_use]
checked_sub_days(self, days: Days) -> Option<Self>764     pub const fn checked_sub_days(self, days: Days) -> Option<Self> {
765         Some(Self { date: try_opt!(self.date.checked_sub_days(days)), ..self })
766     }
767 
768     /// Subtracts another `NaiveDateTime` from the current date and time.
769     /// This does not overflow or underflow at all.
770     ///
771     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
772     /// the subtraction assumes that **there is no leap second ever**,
773     /// except when any of the `NaiveDateTime`s themselves represents a leap second
774     /// in which case the assumption becomes that
775     /// **there are exactly one (or two) leap second(s) ever**.
776     ///
777     /// # Example
778     ///
779     /// ```
780     /// use chrono::{NaiveDate, TimeDelta};
781     ///
782     /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
783     ///
784     /// let d = from_ymd(2016, 7, 8);
785     /// assert_eq!(
786     ///     d.and_hms_opt(3, 5, 7).unwrap().signed_duration_since(d.and_hms_opt(2, 4, 6).unwrap()),
787     ///     TimeDelta::try_seconds(3600 + 60 + 1).unwrap()
788     /// );
789     ///
790     /// // July 8 is 190th day in the year 2016
791     /// let d0 = from_ymd(2016, 1, 1);
792     /// assert_eq!(
793     ///     d.and_hms_milli_opt(0, 7, 6, 500)
794     ///         .unwrap()
795     ///         .signed_duration_since(d0.and_hms_opt(0, 0, 0).unwrap()),
796     ///     TimeDelta::try_seconds(189 * 86_400 + 7 * 60 + 6).unwrap()
797     ///         + TimeDelta::try_milliseconds(500).unwrap()
798     /// );
799     /// ```
800     ///
801     /// Leap seconds are handled, but the subtraction assumes that
802     /// there were no other leap seconds happened.
803     ///
804     /// ```
805     /// # use chrono::{TimeDelta, NaiveDate};
806     /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
807     /// let leap = from_ymd(2015, 6, 30).and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
808     /// assert_eq!(
809     ///     leap.signed_duration_since(from_ymd(2015, 6, 30).and_hms_opt(23, 0, 0).unwrap()),
810     ///     TimeDelta::try_seconds(3600).unwrap() + TimeDelta::try_milliseconds(500).unwrap()
811     /// );
812     /// assert_eq!(
813     ///     from_ymd(2015, 7, 1).and_hms_opt(1, 0, 0).unwrap().signed_duration_since(leap),
814     ///     TimeDelta::try_seconds(3600).unwrap() - TimeDelta::try_milliseconds(500).unwrap()
815     /// );
816     /// ```
817     #[must_use]
signed_duration_since(self, rhs: NaiveDateTime) -> TimeDelta818     pub const fn signed_duration_since(self, rhs: NaiveDateTime) -> TimeDelta {
819         expect(
820             self.date
821                 .signed_duration_since(rhs.date)
822                 .checked_add(&self.time.signed_duration_since(rhs.time)),
823             "always in range",
824         )
825     }
826 
827     /// Formats the combined date and time with the specified formatting items.
828     /// Otherwise it is the same as the ordinary [`format`](#method.format) method.
829     ///
830     /// The `Iterator` of items should be `Clone`able,
831     /// since the resulting `DelayedFormat` value may be formatted multiple times.
832     ///
833     /// # Example
834     ///
835     /// ```
836     /// use chrono::format::strftime::StrftimeItems;
837     /// use chrono::NaiveDate;
838     ///
839     /// let fmt = StrftimeItems::new("%Y-%m-%d %H:%M:%S");
840     /// let dt = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().and_hms_opt(23, 56, 4).unwrap();
841     /// assert_eq!(dt.format_with_items(fmt.clone()).to_string(), "2015-09-05 23:56:04");
842     /// assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2015-09-05 23:56:04");
843     /// ```
844     ///
845     /// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
846     ///
847     /// ```
848     /// # use chrono::NaiveDate;
849     /// # use chrono::format::strftime::StrftimeItems;
850     /// # let fmt = StrftimeItems::new("%Y-%m-%d %H:%M:%S").clone();
851     /// # let dt = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().and_hms_opt(23, 56, 4).unwrap();
852     /// assert_eq!(format!("{}", dt.format_with_items(fmt)), "2015-09-05 23:56:04");
853     /// ```
854     #[cfg(feature = "alloc")]
855     #[inline]
856     #[must_use]
format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I> where I: Iterator<Item = B> + Clone, B: Borrow<Item<'a>>,857     pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
858     where
859         I: Iterator<Item = B> + Clone,
860         B: Borrow<Item<'a>>,
861     {
862         DelayedFormat::new(Some(self.date), Some(self.time), items)
863     }
864 
865     /// Formats the combined date and time with the specified format string.
866     /// See the [`format::strftime` module](crate::format::strftime)
867     /// on the supported escape sequences.
868     ///
869     /// This returns a `DelayedFormat`,
870     /// which gets converted to a string only when actual formatting happens.
871     /// You may use the `to_string` method to get a `String`,
872     /// or just feed it into `print!` and other formatting macros.
873     /// (In this way it avoids the redundant memory allocation.)
874     ///
875     /// A wrong format string does *not* issue an error immediately.
876     /// Rather, converting or formatting the `DelayedFormat` fails.
877     /// You are recommended to immediately use `DelayedFormat` for this reason.
878     ///
879     /// # Example
880     ///
881     /// ```
882     /// use chrono::NaiveDate;
883     ///
884     /// let dt = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().and_hms_opt(23, 56, 4).unwrap();
885     /// assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2015-09-05 23:56:04");
886     /// assert_eq!(dt.format("around %l %p on %b %-d").to_string(), "around 11 PM on Sep 5");
887     /// ```
888     ///
889     /// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
890     ///
891     /// ```
892     /// # use chrono::NaiveDate;
893     /// # let dt = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().and_hms_opt(23, 56, 4).unwrap();
894     /// assert_eq!(format!("{}", dt.format("%Y-%m-%d %H:%M:%S")), "2015-09-05 23:56:04");
895     /// assert_eq!(format!("{}", dt.format("around %l %p on %b %-d")), "around 11 PM on Sep 5");
896     /// ```
897     #[cfg(feature = "alloc")]
898     #[inline]
899     #[must_use]
format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>>900     pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
901         self.format_with_items(StrftimeItems::new(fmt))
902     }
903 
904     /// Converts the `NaiveDateTime` into a timezone-aware `DateTime<Tz>` with the provided
905     /// time zone.
906     ///
907     /// # Example
908     ///
909     /// ```
910     /// use chrono::{FixedOffset, NaiveDate};
911     /// let hour = 3600;
912     /// let tz = FixedOffset::east_opt(5 * hour).unwrap();
913     /// let dt = NaiveDate::from_ymd_opt(2015, 9, 5)
914     ///     .unwrap()
915     ///     .and_hms_opt(23, 56, 4)
916     ///     .unwrap()
917     ///     .and_local_timezone(tz)
918     ///     .unwrap();
919     /// assert_eq!(dt.timezone(), tz);
920     /// ```
921     #[must_use]
and_local_timezone<Tz: TimeZone>(&self, tz: Tz) -> MappedLocalTime<DateTime<Tz>>922     pub fn and_local_timezone<Tz: TimeZone>(&self, tz: Tz) -> MappedLocalTime<DateTime<Tz>> {
923         tz.from_local_datetime(self)
924     }
925 
926     /// Converts the `NaiveDateTime` into the timezone-aware `DateTime<Utc>`.
927     ///
928     /// # Example
929     ///
930     /// ```
931     /// use chrono::{NaiveDate, Utc};
932     /// let dt =
933     ///     NaiveDate::from_ymd_opt(2023, 1, 30).unwrap().and_hms_opt(19, 32, 33).unwrap().and_utc();
934     /// assert_eq!(dt.timezone(), Utc);
935     /// ```
936     #[must_use]
and_utc(&self) -> DateTime<Utc>937     pub const fn and_utc(&self) -> DateTime<Utc> {
938         DateTime::from_naive_utc_and_offset(*self, Utc)
939     }
940 
941     /// The minimum possible `NaiveDateTime`.
942     pub const MIN: Self = Self { date: NaiveDate::MIN, time: NaiveTime::MIN };
943 
944     /// The maximum possible `NaiveDateTime`.
945     pub const MAX: Self = Self { date: NaiveDate::MAX, time: NaiveTime::MAX };
946 
947     /// The Unix Epoch, 1970-01-01 00:00:00.
948     pub const UNIX_EPOCH: Self =
949         expect(NaiveDate::from_ymd_opt(1970, 1, 1), "").and_time(NaiveTime::MIN);
950 }
951 
952 impl From<NaiveDate> for NaiveDateTime {
953     /// Converts a `NaiveDate` to a `NaiveDateTime` of the same date but at midnight.
954     ///
955     /// # Example
956     ///
957     /// ```
958     /// use chrono::{NaiveDate, NaiveDateTime};
959     ///
960     /// let nd = NaiveDate::from_ymd_opt(2016, 5, 28).unwrap();
961     /// let ndt = NaiveDate::from_ymd_opt(2016, 5, 28).unwrap().and_hms_opt(0, 0, 0).unwrap();
962     /// assert_eq!(ndt, NaiveDateTime::from(nd));
from(date: NaiveDate) -> Self963     fn from(date: NaiveDate) -> Self {
964         date.and_hms_opt(0, 0, 0).unwrap()
965     }
966 }
967 
968 impl Datelike for NaiveDateTime {
969     /// Returns the year number in the [calendar date](./struct.NaiveDate.html#calendar-date).
970     ///
971     /// See also the [`NaiveDate::year`](./struct.NaiveDate.html#method.year) method.
972     ///
973     /// # Example
974     ///
975     /// ```
976     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
977     ///
978     /// let dt: NaiveDateTime =
979     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
980     /// assert_eq!(dt.year(), 2015);
981     /// ```
982     #[inline]
year(&self) -> i32983     fn year(&self) -> i32 {
984         self.date.year()
985     }
986 
987     /// Returns the month number starting from 1.
988     ///
989     /// The return value ranges from 1 to 12.
990     ///
991     /// See also the [`NaiveDate::month`](./struct.NaiveDate.html#method.month) method.
992     ///
993     /// # Example
994     ///
995     /// ```
996     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
997     ///
998     /// let dt: NaiveDateTime =
999     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1000     /// assert_eq!(dt.month(), 9);
1001     /// ```
1002     #[inline]
month(&self) -> u321003     fn month(&self) -> u32 {
1004         self.date.month()
1005     }
1006 
1007     /// Returns the month number starting from 0.
1008     ///
1009     /// The return value ranges from 0 to 11.
1010     ///
1011     /// See also the [`NaiveDate::month0`] method.
1012     ///
1013     /// # Example
1014     ///
1015     /// ```
1016     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1017     ///
1018     /// let dt: NaiveDateTime =
1019     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1020     /// assert_eq!(dt.month0(), 8);
1021     /// ```
1022     #[inline]
month0(&self) -> u321023     fn month0(&self) -> u32 {
1024         self.date.month0()
1025     }
1026 
1027     /// Returns the day of month starting from 1.
1028     ///
1029     /// The return value ranges from 1 to 31. (The last day of month differs by months.)
1030     ///
1031     /// See also the [`NaiveDate::day`](./struct.NaiveDate.html#method.day) method.
1032     ///
1033     /// # Example
1034     ///
1035     /// ```
1036     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1037     ///
1038     /// let dt: NaiveDateTime =
1039     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1040     /// assert_eq!(dt.day(), 25);
1041     /// ```
1042     #[inline]
day(&self) -> u321043     fn day(&self) -> u32 {
1044         self.date.day()
1045     }
1046 
1047     /// Returns the day of month starting from 0.
1048     ///
1049     /// The return value ranges from 0 to 30. (The last day of month differs by months.)
1050     ///
1051     /// See also the [`NaiveDate::day0`] method.
1052     ///
1053     /// # Example
1054     ///
1055     /// ```
1056     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1057     ///
1058     /// let dt: NaiveDateTime =
1059     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1060     /// assert_eq!(dt.day0(), 24);
1061     /// ```
1062     #[inline]
day0(&self) -> u321063     fn day0(&self) -> u32 {
1064         self.date.day0()
1065     }
1066 
1067     /// Returns the day of year starting from 1.
1068     ///
1069     /// The return value ranges from 1 to 366. (The last day of year differs by years.)
1070     ///
1071     /// See also the [`NaiveDate::ordinal`](./struct.NaiveDate.html#method.ordinal) method.
1072     ///
1073     /// # Example
1074     ///
1075     /// ```
1076     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1077     ///
1078     /// let dt: NaiveDateTime =
1079     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1080     /// assert_eq!(dt.ordinal(), 268);
1081     /// ```
1082     #[inline]
ordinal(&self) -> u321083     fn ordinal(&self) -> u32 {
1084         self.date.ordinal()
1085     }
1086 
1087     /// Returns the day of year starting from 0.
1088     ///
1089     /// The return value ranges from 0 to 365. (The last day of year differs by years.)
1090     ///
1091     /// See also the [`NaiveDate::ordinal0`] method.
1092     ///
1093     /// # Example
1094     ///
1095     /// ```
1096     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1097     ///
1098     /// let dt: NaiveDateTime =
1099     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1100     /// assert_eq!(dt.ordinal0(), 267);
1101     /// ```
1102     #[inline]
ordinal0(&self) -> u321103     fn ordinal0(&self) -> u32 {
1104         self.date.ordinal0()
1105     }
1106 
1107     /// Returns the day of week.
1108     ///
1109     /// See also the [`NaiveDate::weekday`](./struct.NaiveDate.html#method.weekday) method.
1110     ///
1111     /// # Example
1112     ///
1113     /// ```
1114     /// use chrono::{Datelike, NaiveDate, NaiveDateTime, Weekday};
1115     ///
1116     /// let dt: NaiveDateTime =
1117     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1118     /// assert_eq!(dt.weekday(), Weekday::Fri);
1119     /// ```
1120     #[inline]
weekday(&self) -> Weekday1121     fn weekday(&self) -> Weekday {
1122         self.date.weekday()
1123     }
1124 
1125     #[inline]
iso_week(&self) -> IsoWeek1126     fn iso_week(&self) -> IsoWeek {
1127         self.date.iso_week()
1128     }
1129 
1130     /// Makes a new `NaiveDateTime` with the year number changed, while keeping the same month and
1131     /// day.
1132     ///
1133     /// See also the [`NaiveDate::with_year`] method.
1134     ///
1135     /// # Errors
1136     ///
1137     /// Returns `None` if:
1138     /// - The resulting date does not exist (February 29 in a non-leap year).
1139     /// - The year is out of range for a `NaiveDate`.
1140     ///
1141     /// # Example
1142     ///
1143     /// ```
1144     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1145     ///
1146     /// let dt: NaiveDateTime =
1147     ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1148     /// assert_eq!(
1149     ///     dt.with_year(2016),
1150     ///     Some(NaiveDate::from_ymd_opt(2016, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap())
1151     /// );
1152     /// assert_eq!(
1153     ///     dt.with_year(-308),
1154     ///     Some(NaiveDate::from_ymd_opt(-308, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap())
1155     /// );
1156     /// ```
1157     #[inline]
with_year(&self, year: i32) -> Option<NaiveDateTime>1158     fn with_year(&self, year: i32) -> Option<NaiveDateTime> {
1159         self.date.with_year(year).map(|d| NaiveDateTime { date: d, ..*self })
1160     }
1161 
1162     /// Makes a new `NaiveDateTime` with the month number (starting from 1) changed.
1163     ///
1164     /// Don't combine multiple `Datelike::with_*` methods. The intermediate value may not exist.
1165     ///
1166     /// See also the [`NaiveDate::with_month`] method.
1167     ///
1168     /// # Errors
1169     ///
1170     /// Returns `None` if:
1171     /// - The resulting date does not exist (for example `month(4)` when day of the month is 31).
1172     /// - The value for `month` is invalid.
1173     ///
1174     /// # Example
1175     ///
1176     /// ```
1177     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1178     ///
1179     /// let dt: NaiveDateTime =
1180     ///     NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap();
1181     /// assert_eq!(
1182     ///     dt.with_month(10),
1183     ///     Some(NaiveDate::from_ymd_opt(2015, 10, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1184     /// );
1185     /// assert_eq!(dt.with_month(13), None); // No month 13
1186     /// assert_eq!(dt.with_month(2), None); // No February 30
1187     /// ```
1188     #[inline]
with_month(&self, month: u32) -> Option<NaiveDateTime>1189     fn with_month(&self, month: u32) -> Option<NaiveDateTime> {
1190         self.date.with_month(month).map(|d| NaiveDateTime { date: d, ..*self })
1191     }
1192 
1193     /// Makes a new `NaiveDateTime` with the month number (starting from 0) changed.
1194     ///
1195     /// See also the [`NaiveDate::with_month0`] method.
1196     ///
1197     /// # Errors
1198     ///
1199     /// Returns `None` if:
1200     /// - The resulting date does not exist (for example `month0(3)` when day of the month is 31).
1201     /// - The value for `month0` is invalid.
1202     ///
1203     /// # Example
1204     ///
1205     /// ```
1206     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1207     ///
1208     /// let dt: NaiveDateTime =
1209     ///     NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap();
1210     /// assert_eq!(
1211     ///     dt.with_month0(9),
1212     ///     Some(NaiveDate::from_ymd_opt(2015, 10, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1213     /// );
1214     /// assert_eq!(dt.with_month0(12), None); // No month 13
1215     /// assert_eq!(dt.with_month0(1), None); // No February 30
1216     /// ```
1217     #[inline]
with_month0(&self, month0: u32) -> Option<NaiveDateTime>1218     fn with_month0(&self, month0: u32) -> Option<NaiveDateTime> {
1219         self.date.with_month0(month0).map(|d| NaiveDateTime { date: d, ..*self })
1220     }
1221 
1222     /// Makes a new `NaiveDateTime` with the day of month (starting from 1) changed.
1223     ///
1224     /// See also the [`NaiveDate::with_day`] method.
1225     ///
1226     /// # Errors
1227     ///
1228     /// Returns `None` if:
1229     /// - The resulting date does not exist (for example `day(31)` in April).
1230     /// - The value for `day` is invalid.
1231     ///
1232     /// # Example
1233     ///
1234     /// ```
1235     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1236     ///
1237     /// let dt: NaiveDateTime =
1238     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1239     /// assert_eq!(
1240     ///     dt.with_day(30),
1241     ///     Some(NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1242     /// );
1243     /// assert_eq!(dt.with_day(31), None); // no September 31
1244     /// ```
1245     #[inline]
with_day(&self, day: u32) -> Option<NaiveDateTime>1246     fn with_day(&self, day: u32) -> Option<NaiveDateTime> {
1247         self.date.with_day(day).map(|d| NaiveDateTime { date: d, ..*self })
1248     }
1249 
1250     /// Makes a new `NaiveDateTime` with the day of month (starting from 0) changed.
1251     ///
1252     /// See also the [`NaiveDate::with_day0`] method.
1253     ///
1254     /// # Errors
1255     ///
1256     /// Returns `None` if:
1257     /// - The resulting date does not exist (for example `day(30)` in April).
1258     /// - The value for `day0` is invalid.
1259     ///
1260     /// # Example
1261     ///
1262     /// ```
1263     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1264     ///
1265     /// let dt: NaiveDateTime =
1266     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1267     /// assert_eq!(
1268     ///     dt.with_day0(29),
1269     ///     Some(NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1270     /// );
1271     /// assert_eq!(dt.with_day0(30), None); // no September 31
1272     /// ```
1273     #[inline]
with_day0(&self, day0: u32) -> Option<NaiveDateTime>1274     fn with_day0(&self, day0: u32) -> Option<NaiveDateTime> {
1275         self.date.with_day0(day0).map(|d| NaiveDateTime { date: d, ..*self })
1276     }
1277 
1278     /// Makes a new `NaiveDateTime` with the day of year (starting from 1) changed.
1279     ///
1280     /// See also the [`NaiveDate::with_ordinal`] method.
1281     ///
1282     /// # Errors
1283     ///
1284     /// Returns `None` if:
1285     /// - The resulting date does not exist (`with_ordinal(366)` in a non-leap year).
1286     /// - The value for `ordinal` is invalid.
1287     ///
1288     /// # Example
1289     ///
1290     /// ```
1291     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1292     ///
1293     /// let dt: NaiveDateTime =
1294     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1295     /// assert_eq!(
1296     ///     dt.with_ordinal(60),
1297     ///     Some(NaiveDate::from_ymd_opt(2015, 3, 1).unwrap().and_hms_opt(12, 34, 56).unwrap())
1298     /// );
1299     /// assert_eq!(dt.with_ordinal(366), None); // 2015 had only 365 days
1300     ///
1301     /// let dt: NaiveDateTime =
1302     ///     NaiveDate::from_ymd_opt(2016, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1303     /// assert_eq!(
1304     ///     dt.with_ordinal(60),
1305     ///     Some(NaiveDate::from_ymd_opt(2016, 2, 29).unwrap().and_hms_opt(12, 34, 56).unwrap())
1306     /// );
1307     /// assert_eq!(
1308     ///     dt.with_ordinal(366),
1309     ///     Some(NaiveDate::from_ymd_opt(2016, 12, 31).unwrap().and_hms_opt(12, 34, 56).unwrap())
1310     /// );
1311     /// ```
1312     #[inline]
with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime>1313     fn with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime> {
1314         self.date.with_ordinal(ordinal).map(|d| NaiveDateTime { date: d, ..*self })
1315     }
1316 
1317     /// Makes a new `NaiveDateTime` with the day of year (starting from 0) changed.
1318     ///
1319     /// See also the [`NaiveDate::with_ordinal0`] method.
1320     ///
1321     /// # Errors
1322     ///
1323     /// Returns `None` if:
1324     /// - The resulting date does not exist (`with_ordinal0(365)` in a non-leap year).
1325     /// - The value for `ordinal0` is invalid.
1326     ///
1327     /// # Example
1328     ///
1329     /// ```
1330     /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1331     ///
1332     /// let dt: NaiveDateTime =
1333     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1334     /// assert_eq!(
1335     ///     dt.with_ordinal0(59),
1336     ///     Some(NaiveDate::from_ymd_opt(2015, 3, 1).unwrap().and_hms_opt(12, 34, 56).unwrap())
1337     /// );
1338     /// assert_eq!(dt.with_ordinal0(365), None); // 2015 had only 365 days
1339     ///
1340     /// let dt: NaiveDateTime =
1341     ///     NaiveDate::from_ymd_opt(2016, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1342     /// assert_eq!(
1343     ///     dt.with_ordinal0(59),
1344     ///     Some(NaiveDate::from_ymd_opt(2016, 2, 29).unwrap().and_hms_opt(12, 34, 56).unwrap())
1345     /// );
1346     /// assert_eq!(
1347     ///     dt.with_ordinal0(365),
1348     ///     Some(NaiveDate::from_ymd_opt(2016, 12, 31).unwrap().and_hms_opt(12, 34, 56).unwrap())
1349     /// );
1350     /// ```
1351     #[inline]
with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime>1352     fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime> {
1353         self.date.with_ordinal0(ordinal0).map(|d| NaiveDateTime { date: d, ..*self })
1354     }
1355 }
1356 
1357 impl Timelike for NaiveDateTime {
1358     /// Returns the hour number from 0 to 23.
1359     ///
1360     /// See also the [`NaiveTime::hour`] method.
1361     ///
1362     /// # Example
1363     ///
1364     /// ```
1365     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1366     ///
1367     /// let dt: NaiveDateTime =
1368     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1369     /// assert_eq!(dt.hour(), 12);
1370     /// ```
1371     #[inline]
hour(&self) -> u321372     fn hour(&self) -> u32 {
1373         self.time.hour()
1374     }
1375 
1376     /// Returns the minute number from 0 to 59.
1377     ///
1378     /// See also the [`NaiveTime::minute`] method.
1379     ///
1380     /// # Example
1381     ///
1382     /// ```
1383     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1384     ///
1385     /// let dt: NaiveDateTime =
1386     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1387     /// assert_eq!(dt.minute(), 34);
1388     /// ```
1389     #[inline]
minute(&self) -> u321390     fn minute(&self) -> u32 {
1391         self.time.minute()
1392     }
1393 
1394     /// Returns the second number from 0 to 59.
1395     ///
1396     /// See also the [`NaiveTime::second`] method.
1397     ///
1398     /// # Example
1399     ///
1400     /// ```
1401     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1402     ///
1403     /// let dt: NaiveDateTime =
1404     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1405     /// assert_eq!(dt.second(), 56);
1406     /// ```
1407     #[inline]
second(&self) -> u321408     fn second(&self) -> u32 {
1409         self.time.second()
1410     }
1411 
1412     /// Returns the number of nanoseconds since the whole non-leap second.
1413     /// The range from 1,000,000,000 to 1,999,999,999 represents
1414     /// the [leap second](./struct.NaiveTime.html#leap-second-handling).
1415     ///
1416     /// See also the [`NaiveTime#method.nanosecond`] method.
1417     ///
1418     /// # Example
1419     ///
1420     /// ```
1421     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1422     ///
1423     /// let dt: NaiveDateTime =
1424     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1425     /// assert_eq!(dt.nanosecond(), 789_000_000);
1426     /// ```
1427     #[inline]
nanosecond(&self) -> u321428     fn nanosecond(&self) -> u32 {
1429         self.time.nanosecond()
1430     }
1431 
1432     /// Makes a new `NaiveDateTime` with the hour number changed.
1433     ///
1434     /// See also the [`NaiveTime::with_hour`] method.
1435     ///
1436     /// # Errors
1437     ///
1438     /// Returns `None` if the value for `hour` is invalid.
1439     ///
1440     /// # Example
1441     ///
1442     /// ```
1443     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1444     ///
1445     /// let dt: NaiveDateTime =
1446     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1447     /// assert_eq!(
1448     ///     dt.with_hour(7),
1449     ///     Some(
1450     ///         NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(7, 34, 56, 789).unwrap()
1451     ///     )
1452     /// );
1453     /// assert_eq!(dt.with_hour(24), None);
1454     /// ```
1455     #[inline]
with_hour(&self, hour: u32) -> Option<NaiveDateTime>1456     fn with_hour(&self, hour: u32) -> Option<NaiveDateTime> {
1457         self.time.with_hour(hour).map(|t| NaiveDateTime { time: t, ..*self })
1458     }
1459 
1460     /// Makes a new `NaiveDateTime` with the minute number changed.
1461     ///
1462     /// See also the [`NaiveTime::with_minute`] method.
1463     ///
1464     /// # Errors
1465     ///
1466     /// Returns `None` if the value for `minute` is invalid.
1467     ///
1468     /// # Example
1469     ///
1470     /// ```
1471     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1472     ///
1473     /// let dt: NaiveDateTime =
1474     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1475     /// assert_eq!(
1476     ///     dt.with_minute(45),
1477     ///     Some(
1478     ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1479     ///             .unwrap()
1480     ///             .and_hms_milli_opt(12, 45, 56, 789)
1481     ///             .unwrap()
1482     ///     )
1483     /// );
1484     /// assert_eq!(dt.with_minute(60), None);
1485     /// ```
1486     #[inline]
with_minute(&self, min: u32) -> Option<NaiveDateTime>1487     fn with_minute(&self, min: u32) -> Option<NaiveDateTime> {
1488         self.time.with_minute(min).map(|t| NaiveDateTime { time: t, ..*self })
1489     }
1490 
1491     /// Makes a new `NaiveDateTime` with the second number changed.
1492     ///
1493     /// As with the [`second`](#method.second) method,
1494     /// the input range is restricted to 0 through 59.
1495     ///
1496     /// See also the [`NaiveTime::with_second`] method.
1497     ///
1498     /// # Errors
1499     ///
1500     /// Returns `None` if the value for `second` is invalid.
1501     ///
1502     /// # Example
1503     ///
1504     /// ```
1505     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1506     ///
1507     /// let dt: NaiveDateTime =
1508     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1509     /// assert_eq!(
1510     ///     dt.with_second(17),
1511     ///     Some(
1512     ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1513     ///             .unwrap()
1514     ///             .and_hms_milli_opt(12, 34, 17, 789)
1515     ///             .unwrap()
1516     ///     )
1517     /// );
1518     /// assert_eq!(dt.with_second(60), None);
1519     /// ```
1520     #[inline]
with_second(&self, sec: u32) -> Option<NaiveDateTime>1521     fn with_second(&self, sec: u32) -> Option<NaiveDateTime> {
1522         self.time.with_second(sec).map(|t| NaiveDateTime { time: t, ..*self })
1523     }
1524 
1525     /// Makes a new `NaiveDateTime` with nanoseconds since the whole non-leap second changed.
1526     ///
1527     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1528     /// As with the [`NaiveDateTime::nanosecond`] method,
1529     /// the input range can exceed 1,000,000,000 for leap seconds.
1530     ///
1531     /// See also the [`NaiveTime::with_nanosecond`] method.
1532     ///
1533     /// # Errors
1534     ///
1535     /// Returns `None` if `nanosecond >= 2,000,000,000`.
1536     ///
1537     /// # Example
1538     ///
1539     /// ```
1540     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1541     ///
1542     /// let dt: NaiveDateTime =
1543     ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 59, 789).unwrap();
1544     /// assert_eq!(
1545     ///     dt.with_nanosecond(333_333_333),
1546     ///     Some(
1547     ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1548     ///             .unwrap()
1549     ///             .and_hms_nano_opt(12, 34, 59, 333_333_333)
1550     ///             .unwrap()
1551     ///     )
1552     /// );
1553     /// assert_eq!(
1554     ///     dt.with_nanosecond(1_333_333_333), // leap second
1555     ///     Some(
1556     ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1557     ///             .unwrap()
1558     ///             .and_hms_nano_opt(12, 34, 59, 1_333_333_333)
1559     ///             .unwrap()
1560     ///     )
1561     /// );
1562     /// assert_eq!(dt.with_nanosecond(2_000_000_000), None);
1563     /// ```
1564     #[inline]
with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime>1565     fn with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime> {
1566         self.time.with_nanosecond(nano).map(|t| NaiveDateTime { time: t, ..*self })
1567     }
1568 }
1569 
1570 /// Add `TimeDelta` to `NaiveDateTime`.
1571 ///
1572 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1573 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1574 /// the assumption becomes that **there is exactly a single leap second ever**.
1575 ///
1576 /// # Panics
1577 ///
1578 /// Panics if the resulting date would be out of range.
1579 /// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1580 ///
1581 /// # Example
1582 ///
1583 /// ```
1584 /// use chrono::{NaiveDate, TimeDelta};
1585 ///
1586 /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1587 ///
1588 /// let d = from_ymd(2016, 7, 8);
1589 /// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
1590 /// assert_eq!(hms(3, 5, 7) + TimeDelta::zero(), hms(3, 5, 7));
1591 /// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(1).unwrap(), hms(3, 5, 8));
1592 /// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(-1).unwrap(), hms(3, 5, 6));
1593 /// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(3600 + 60).unwrap(), hms(4, 6, 7));
1594 /// assert_eq!(
1595 ///     hms(3, 5, 7) + TimeDelta::try_seconds(86_400).unwrap(),
1596 ///     from_ymd(2016, 7, 9).and_hms_opt(3, 5, 7).unwrap()
1597 /// );
1598 /// assert_eq!(
1599 ///     hms(3, 5, 7) + TimeDelta::try_days(365).unwrap(),
1600 ///     from_ymd(2017, 7, 8).and_hms_opt(3, 5, 7).unwrap()
1601 /// );
1602 ///
1603 /// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
1604 /// assert_eq!(hmsm(3, 5, 7, 980) + TimeDelta::try_milliseconds(450).unwrap(), hmsm(3, 5, 8, 430));
1605 /// ```
1606 ///
1607 /// Leap seconds are handled,
1608 /// but the addition assumes that it is the only leap second happened.
1609 ///
1610 /// ```
1611 /// # use chrono::{TimeDelta, NaiveDate};
1612 /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1613 /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
1614 /// let leap = hmsm(3, 5, 59, 1_300);
1615 /// assert_eq!(leap + TimeDelta::zero(), hmsm(3, 5, 59, 1_300));
1616 /// assert_eq!(leap + TimeDelta::try_milliseconds(-500).unwrap(), hmsm(3, 5, 59, 800));
1617 /// assert_eq!(leap + TimeDelta::try_milliseconds(500).unwrap(), hmsm(3, 5, 59, 1_800));
1618 /// assert_eq!(leap + TimeDelta::try_milliseconds(800).unwrap(), hmsm(3, 6, 0, 100));
1619 /// assert_eq!(leap + TimeDelta::try_seconds(10).unwrap(), hmsm(3, 6, 9, 300));
1620 /// assert_eq!(leap + TimeDelta::try_seconds(-10).unwrap(), hmsm(3, 5, 50, 300));
1621 /// assert_eq!(leap + TimeDelta::try_days(1).unwrap(),
1622 ///            from_ymd(2016, 7, 9).and_hms_milli_opt(3, 5, 59, 300).unwrap());
1623 /// ```
1624 ///
1625 /// [leap second handling]: crate::NaiveTime#leap-second-handling
1626 impl Add<TimeDelta> for NaiveDateTime {
1627     type Output = NaiveDateTime;
1628 
1629     #[inline]
add(self, rhs: TimeDelta) -> NaiveDateTime1630     fn add(self, rhs: TimeDelta) -> NaiveDateTime {
1631         self.checked_add_signed(rhs).expect("`NaiveDateTime + TimeDelta` overflowed")
1632     }
1633 }
1634 
1635 /// Add `std::time::Duration` to `NaiveDateTime`.
1636 ///
1637 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1638 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1639 /// the assumption becomes that **there is exactly a single leap second ever**.
1640 ///
1641 /// # Panics
1642 ///
1643 /// Panics if the resulting date would be out of range.
1644 /// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1645 impl Add<Duration> for NaiveDateTime {
1646     type Output = NaiveDateTime;
1647 
1648     #[inline]
add(self, rhs: Duration) -> NaiveDateTime1649     fn add(self, rhs: Duration) -> NaiveDateTime {
1650         let rhs = TimeDelta::from_std(rhs)
1651             .expect("overflow converting from core::time::Duration to TimeDelta");
1652         self.checked_add_signed(rhs).expect("`NaiveDateTime + TimeDelta` overflowed")
1653     }
1654 }
1655 
1656 /// Add-assign `TimeDelta` to `NaiveDateTime`.
1657 ///
1658 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1659 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1660 /// the assumption becomes that **there is exactly a single leap second ever**.
1661 ///
1662 /// # Panics
1663 ///
1664 /// Panics if the resulting date would be out of range.
1665 /// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1666 impl AddAssign<TimeDelta> for NaiveDateTime {
1667     #[inline]
add_assign(&mut self, rhs: TimeDelta)1668     fn add_assign(&mut self, rhs: TimeDelta) {
1669         *self = self.add(rhs);
1670     }
1671 }
1672 
1673 /// Add-assign `std::time::Duration` to `NaiveDateTime`.
1674 ///
1675 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1676 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1677 /// the assumption becomes that **there is exactly a single leap second ever**.
1678 ///
1679 /// # Panics
1680 ///
1681 /// Panics if the resulting date would be out of range.
1682 /// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1683 impl AddAssign<Duration> for NaiveDateTime {
1684     #[inline]
add_assign(&mut self, rhs: Duration)1685     fn add_assign(&mut self, rhs: Duration) {
1686         *self = self.add(rhs);
1687     }
1688 }
1689 
1690 /// Add `FixedOffset` to `NaiveDateTime`.
1691 ///
1692 /// # Panics
1693 ///
1694 /// Panics if the resulting date would be out of range.
1695 /// Consider using `checked_add_offset` to get an `Option` instead.
1696 impl Add<FixedOffset> for NaiveDateTime {
1697     type Output = NaiveDateTime;
1698 
1699     #[inline]
add(self, rhs: FixedOffset) -> NaiveDateTime1700     fn add(self, rhs: FixedOffset) -> NaiveDateTime {
1701         self.checked_add_offset(rhs).expect("`NaiveDateTime + FixedOffset` out of range")
1702     }
1703 }
1704 
1705 /// Add `Months` to `NaiveDateTime`.
1706 ///
1707 /// The result will be clamped to valid days in the resulting month, see `checked_add_months` for
1708 /// details.
1709 ///
1710 /// # Panics
1711 ///
1712 /// Panics if the resulting date would be out of range.
1713 /// Consider using `checked_add_months` to get an `Option` instead.
1714 ///
1715 /// # Example
1716 ///
1717 /// ```
1718 /// use chrono::{Months, NaiveDate};
1719 ///
1720 /// assert_eq!(
1721 ///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(1, 0, 0).unwrap() + Months::new(1),
1722 ///     NaiveDate::from_ymd_opt(2014, 2, 1).unwrap().and_hms_opt(1, 0, 0).unwrap()
1723 /// );
1724 /// assert_eq!(
1725 ///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 2, 0).unwrap()
1726 ///         + Months::new(11),
1727 ///     NaiveDate::from_ymd_opt(2014, 12, 1).unwrap().and_hms_opt(0, 2, 0).unwrap()
1728 /// );
1729 /// assert_eq!(
1730 ///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 0, 3).unwrap()
1731 ///         + Months::new(12),
1732 ///     NaiveDate::from_ymd_opt(2015, 1, 1).unwrap().and_hms_opt(0, 0, 3).unwrap()
1733 /// );
1734 /// assert_eq!(
1735 ///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 0, 4).unwrap()
1736 ///         + Months::new(13),
1737 ///     NaiveDate::from_ymd_opt(2015, 2, 1).unwrap().and_hms_opt(0, 0, 4).unwrap()
1738 /// );
1739 /// assert_eq!(
1740 ///     NaiveDate::from_ymd_opt(2014, 1, 31).unwrap().and_hms_opt(0, 5, 0).unwrap()
1741 ///         + Months::new(1),
1742 ///     NaiveDate::from_ymd_opt(2014, 2, 28).unwrap().and_hms_opt(0, 5, 0).unwrap()
1743 /// );
1744 /// assert_eq!(
1745 ///     NaiveDate::from_ymd_opt(2020, 1, 31).unwrap().and_hms_opt(6, 0, 0).unwrap()
1746 ///         + Months::new(1),
1747 ///     NaiveDate::from_ymd_opt(2020, 2, 29).unwrap().and_hms_opt(6, 0, 0).unwrap()
1748 /// );
1749 /// ```
1750 impl Add<Months> for NaiveDateTime {
1751     type Output = NaiveDateTime;
1752 
add(self, rhs: Months) -> Self::Output1753     fn add(self, rhs: Months) -> Self::Output {
1754         self.checked_add_months(rhs).expect("`NaiveDateTime + Months` out of range")
1755     }
1756 }
1757 
1758 /// Subtract `TimeDelta` from `NaiveDateTime`.
1759 ///
1760 /// This is the same as the addition with a negated `TimeDelta`.
1761 ///
1762 /// As a part of Chrono's [leap second handling] the subtraction assumes that **there is no leap
1763 /// second ever**, except when the `NaiveDateTime` itself represents a leap second in which case
1764 /// the assumption becomes that **there is exactly a single leap second ever**.
1765 ///
1766 /// # Panics
1767 ///
1768 /// Panics if the resulting date would be out of range.
1769 /// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1770 ///
1771 /// # Example
1772 ///
1773 /// ```
1774 /// use chrono::{NaiveDate, TimeDelta};
1775 ///
1776 /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1777 ///
1778 /// let d = from_ymd(2016, 7, 8);
1779 /// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
1780 /// assert_eq!(hms(3, 5, 7) - TimeDelta::zero(), hms(3, 5, 7));
1781 /// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(1).unwrap(), hms(3, 5, 6));
1782 /// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(-1).unwrap(), hms(3, 5, 8));
1783 /// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(3600 + 60).unwrap(), hms(2, 4, 7));
1784 /// assert_eq!(
1785 ///     hms(3, 5, 7) - TimeDelta::try_seconds(86_400).unwrap(),
1786 ///     from_ymd(2016, 7, 7).and_hms_opt(3, 5, 7).unwrap()
1787 /// );
1788 /// assert_eq!(
1789 ///     hms(3, 5, 7) - TimeDelta::try_days(365).unwrap(),
1790 ///     from_ymd(2015, 7, 9).and_hms_opt(3, 5, 7).unwrap()
1791 /// );
1792 ///
1793 /// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
1794 /// assert_eq!(hmsm(3, 5, 7, 450) - TimeDelta::try_milliseconds(670).unwrap(), hmsm(3, 5, 6, 780));
1795 /// ```
1796 ///
1797 /// Leap seconds are handled,
1798 /// but the subtraction assumes that it is the only leap second happened.
1799 ///
1800 /// ```
1801 /// # use chrono::{TimeDelta, NaiveDate};
1802 /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1803 /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
1804 /// let leap = hmsm(3, 5, 59, 1_300);
1805 /// assert_eq!(leap - TimeDelta::zero(), hmsm(3, 5, 59, 1_300));
1806 /// assert_eq!(leap - TimeDelta::try_milliseconds(200).unwrap(), hmsm(3, 5, 59, 1_100));
1807 /// assert_eq!(leap - TimeDelta::try_milliseconds(500).unwrap(), hmsm(3, 5, 59, 800));
1808 /// assert_eq!(leap - TimeDelta::try_seconds(60).unwrap(), hmsm(3, 5, 0, 300));
1809 /// assert_eq!(leap - TimeDelta::try_days(1).unwrap(),
1810 ///            from_ymd(2016, 7, 7).and_hms_milli_opt(3, 6, 0, 300).unwrap());
1811 /// ```
1812 ///
1813 /// [leap second handling]: crate::NaiveTime#leap-second-handling
1814 impl Sub<TimeDelta> for NaiveDateTime {
1815     type Output = NaiveDateTime;
1816 
1817     #[inline]
sub(self, rhs: TimeDelta) -> NaiveDateTime1818     fn sub(self, rhs: TimeDelta) -> NaiveDateTime {
1819         self.checked_sub_signed(rhs).expect("`NaiveDateTime - TimeDelta` overflowed")
1820     }
1821 }
1822 
1823 /// Subtract `std::time::Duration` from `NaiveDateTime`.
1824 ///
1825 /// As a part of Chrono's [leap second handling] the subtraction assumes that **there is no leap
1826 /// second ever**, except when the `NaiveDateTime` itself represents a leap second in which case
1827 /// the assumption becomes that **there is exactly a single leap second ever**.
1828 ///
1829 /// # Panics
1830 ///
1831 /// Panics if the resulting date would be out of range.
1832 /// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1833 impl Sub<Duration> for NaiveDateTime {
1834     type Output = NaiveDateTime;
1835 
1836     #[inline]
sub(self, rhs: Duration) -> NaiveDateTime1837     fn sub(self, rhs: Duration) -> NaiveDateTime {
1838         let rhs = TimeDelta::from_std(rhs)
1839             .expect("overflow converting from core::time::Duration to TimeDelta");
1840         self.checked_sub_signed(rhs).expect("`NaiveDateTime - TimeDelta` overflowed")
1841     }
1842 }
1843 
1844 /// Subtract-assign `TimeDelta` from `NaiveDateTime`.
1845 ///
1846 /// This is the same as the addition with a negated `TimeDelta`.
1847 ///
1848 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1849 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1850 /// the assumption becomes that **there is exactly a single leap second ever**.
1851 ///
1852 /// # Panics
1853 ///
1854 /// Panics if the resulting date would be out of range.
1855 /// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1856 impl SubAssign<TimeDelta> for NaiveDateTime {
1857     #[inline]
sub_assign(&mut self, rhs: TimeDelta)1858     fn sub_assign(&mut self, rhs: TimeDelta) {
1859         *self = self.sub(rhs);
1860     }
1861 }
1862 
1863 /// Subtract-assign `std::time::Duration` from `NaiveDateTime`.
1864 ///
1865 /// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1866 /// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1867 /// the assumption becomes that **there is exactly a single leap second ever**.
1868 ///
1869 /// # Panics
1870 ///
1871 /// Panics if the resulting date would be out of range.
1872 /// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1873 impl SubAssign<Duration> for NaiveDateTime {
1874     #[inline]
sub_assign(&mut self, rhs: Duration)1875     fn sub_assign(&mut self, rhs: Duration) {
1876         *self = self.sub(rhs);
1877     }
1878 }
1879 
1880 /// Subtract `FixedOffset` from `NaiveDateTime`.
1881 ///
1882 /// # Panics
1883 ///
1884 /// Panics if the resulting date would be out of range.
1885 /// Consider using `checked_sub_offset` to get an `Option` instead.
1886 impl Sub<FixedOffset> for NaiveDateTime {
1887     type Output = NaiveDateTime;
1888 
1889     #[inline]
sub(self, rhs: FixedOffset) -> NaiveDateTime1890     fn sub(self, rhs: FixedOffset) -> NaiveDateTime {
1891         self.checked_sub_offset(rhs).expect("`NaiveDateTime - FixedOffset` out of range")
1892     }
1893 }
1894 
1895 /// Subtract `Months` from `NaiveDateTime`.
1896 ///
1897 /// The result will be clamped to valid days in the resulting month, see
1898 /// [`NaiveDateTime::checked_sub_months`] for details.
1899 ///
1900 /// # Panics
1901 ///
1902 /// Panics if the resulting date would be out of range.
1903 /// Consider using [`NaiveDateTime::checked_sub_months`] to get an `Option` instead.
1904 ///
1905 /// # Example
1906 ///
1907 /// ```
1908 /// use chrono::{Months, NaiveDate};
1909 ///
1910 /// assert_eq!(
1911 ///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(01, 00, 00).unwrap()
1912 ///         - Months::new(11),
1913 ///     NaiveDate::from_ymd_opt(2013, 02, 01).unwrap().and_hms_opt(01, 00, 00).unwrap()
1914 /// );
1915 /// assert_eq!(
1916 ///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(00, 02, 00).unwrap()
1917 ///         - Months::new(12),
1918 ///     NaiveDate::from_ymd_opt(2013, 01, 01).unwrap().and_hms_opt(00, 02, 00).unwrap()
1919 /// );
1920 /// assert_eq!(
1921 ///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(00, 00, 03).unwrap()
1922 ///         - Months::new(13),
1923 ///     NaiveDate::from_ymd_opt(2012, 12, 01).unwrap().and_hms_opt(00, 00, 03).unwrap()
1924 /// );
1925 /// ```
1926 impl Sub<Months> for NaiveDateTime {
1927     type Output = NaiveDateTime;
1928 
sub(self, rhs: Months) -> Self::Output1929     fn sub(self, rhs: Months) -> Self::Output {
1930         self.checked_sub_months(rhs).expect("`NaiveDateTime - Months` out of range")
1931     }
1932 }
1933 
1934 /// Subtracts another `NaiveDateTime` from the current date and time.
1935 /// This does not overflow or underflow at all.
1936 ///
1937 /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
1938 /// the subtraction assumes that **there is no leap second ever**,
1939 /// except when any of the `NaiveDateTime`s themselves represents a leap second
1940 /// in which case the assumption becomes that
1941 /// **there are exactly one (or two) leap second(s) ever**.
1942 ///
1943 /// The implementation is a wrapper around [`NaiveDateTime::signed_duration_since`].
1944 ///
1945 /// # Example
1946 ///
1947 /// ```
1948 /// use chrono::{NaiveDate, TimeDelta};
1949 ///
1950 /// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1951 ///
1952 /// let d = from_ymd(2016, 7, 8);
1953 /// assert_eq!(
1954 ///     d.and_hms_opt(3, 5, 7).unwrap() - d.and_hms_opt(2, 4, 6).unwrap(),
1955 ///     TimeDelta::try_seconds(3600 + 60 + 1).unwrap()
1956 /// );
1957 ///
1958 /// // July 8 is 190th day in the year 2016
1959 /// let d0 = from_ymd(2016, 1, 1);
1960 /// assert_eq!(
1961 ///     d.and_hms_milli_opt(0, 7, 6, 500).unwrap() - d0.and_hms_opt(0, 0, 0).unwrap(),
1962 ///     TimeDelta::try_seconds(189 * 86_400 + 7 * 60 + 6).unwrap()
1963 ///         + TimeDelta::try_milliseconds(500).unwrap()
1964 /// );
1965 /// ```
1966 ///
1967 /// Leap seconds are handled, but the subtraction assumes that no other leap
1968 /// seconds happened.
1969 ///
1970 /// ```
1971 /// # use chrono::{TimeDelta, NaiveDate};
1972 /// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1973 /// let leap = from_ymd(2015, 6, 30).and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
1974 /// assert_eq!(
1975 ///     leap - from_ymd(2015, 6, 30).and_hms_opt(23, 0, 0).unwrap(),
1976 ///     TimeDelta::try_seconds(3600).unwrap() + TimeDelta::try_milliseconds(500).unwrap()
1977 /// );
1978 /// assert_eq!(
1979 ///     from_ymd(2015, 7, 1).and_hms_opt(1, 0, 0).unwrap() - leap,
1980 ///     TimeDelta::try_seconds(3600).unwrap() - TimeDelta::try_milliseconds(500).unwrap()
1981 /// );
1982 /// ```
1983 impl Sub<NaiveDateTime> for NaiveDateTime {
1984     type Output = TimeDelta;
1985 
1986     #[inline]
sub(self, rhs: NaiveDateTime) -> TimeDelta1987     fn sub(self, rhs: NaiveDateTime) -> TimeDelta {
1988         self.signed_duration_since(rhs)
1989     }
1990 }
1991 
1992 /// Add `Days` to `NaiveDateTime`.
1993 ///
1994 /// # Panics
1995 ///
1996 /// Panics if the resulting date would be out of range.
1997 /// Consider using `checked_add_days` to get an `Option` instead.
1998 impl Add<Days> for NaiveDateTime {
1999     type Output = NaiveDateTime;
2000 
add(self, days: Days) -> Self::Output2001     fn add(self, days: Days) -> Self::Output {
2002         self.checked_add_days(days).expect("`NaiveDateTime + Days` out of range")
2003     }
2004 }
2005 
2006 /// Subtract `Days` from `NaiveDateTime`.
2007 ///
2008 /// # Panics
2009 ///
2010 /// Panics if the resulting date would be out of range.
2011 /// Consider using `checked_sub_days` to get an `Option` instead.
2012 impl Sub<Days> for NaiveDateTime {
2013     type Output = NaiveDateTime;
2014 
sub(self, days: Days) -> Self::Output2015     fn sub(self, days: Days) -> Self::Output {
2016         self.checked_sub_days(days).expect("`NaiveDateTime - Days` out of range")
2017     }
2018 }
2019 
2020 /// The `Debug` output of the naive date and time `dt` is the same as
2021 /// [`dt.format("%Y-%m-%dT%H:%M:%S%.f")`](crate::format::strftime).
2022 ///
2023 /// The string printed can be readily parsed via the `parse` method on `str`.
2024 ///
2025 /// It should be noted that, for leap seconds not on the minute boundary,
2026 /// it may print a representation not distinguishable from non-leap seconds.
2027 /// This doesn't matter in practice, since such leap seconds never happened.
2028 /// (By the time of the first leap second on 1972-06-30,
2029 /// every time zone offset around the world has standardized to the 5-minute alignment.)
2030 ///
2031 /// # Example
2032 ///
2033 /// ```
2034 /// use chrono::NaiveDate;
2035 ///
2036 /// let dt = NaiveDate::from_ymd_opt(2016, 11, 15).unwrap().and_hms_opt(7, 39, 24).unwrap();
2037 /// assert_eq!(format!("{:?}", dt), "2016-11-15T07:39:24");
2038 /// ```
2039 ///
2040 /// Leap seconds may also be used.
2041 ///
2042 /// ```
2043 /// # use chrono::NaiveDate;
2044 /// let dt =
2045 ///     NaiveDate::from_ymd_opt(2015, 6, 30).unwrap().and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
2046 /// assert_eq!(format!("{:?}", dt), "2015-06-30T23:59:60.500");
2047 /// ```
2048 impl fmt::Debug for NaiveDateTime {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result2049     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2050         self.date.fmt(f)?;
2051         f.write_char('T')?;
2052         self.time.fmt(f)
2053     }
2054 }
2055 
2056 /// The `Display` output of the naive date and time `dt` is the same as
2057 /// [`dt.format("%Y-%m-%d %H:%M:%S%.f")`](crate::format::strftime).
2058 ///
2059 /// It should be noted that, for leap seconds not on the minute boundary,
2060 /// it may print a representation not distinguishable from non-leap seconds.
2061 /// This doesn't matter in practice, since such leap seconds never happened.
2062 /// (By the time of the first leap second on 1972-06-30,
2063 /// every time zone offset around the world has standardized to the 5-minute alignment.)
2064 ///
2065 /// # Example
2066 ///
2067 /// ```
2068 /// use chrono::NaiveDate;
2069 ///
2070 /// let dt = NaiveDate::from_ymd_opt(2016, 11, 15).unwrap().and_hms_opt(7, 39, 24).unwrap();
2071 /// assert_eq!(format!("{}", dt), "2016-11-15 07:39:24");
2072 /// ```
2073 ///
2074 /// Leap seconds may also be used.
2075 ///
2076 /// ```
2077 /// # use chrono::NaiveDate;
2078 /// let dt =
2079 ///     NaiveDate::from_ymd_opt(2015, 6, 30).unwrap().and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
2080 /// assert_eq!(format!("{}", dt), "2015-06-30 23:59:60.500");
2081 /// ```
2082 impl fmt::Display for NaiveDateTime {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result2083     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2084         self.date.fmt(f)?;
2085         f.write_char(' ')?;
2086         self.time.fmt(f)
2087     }
2088 }
2089 
2090 /// Parsing a `str` into a `NaiveDateTime` uses the same format,
2091 /// [`%Y-%m-%dT%H:%M:%S%.f`](crate::format::strftime), as in `Debug`.
2092 ///
2093 /// # Example
2094 ///
2095 /// ```
2096 /// use chrono::{NaiveDateTime, NaiveDate};
2097 ///
2098 /// let dt = NaiveDate::from_ymd_opt(2015, 9, 18).unwrap().and_hms_opt(23, 56, 4).unwrap();
2099 /// assert_eq!("2015-09-18T23:56:04".parse::<NaiveDateTime>(), Ok(dt));
2100 ///
2101 /// let dt = NaiveDate::from_ymd_opt(12345, 6, 7).unwrap().and_hms_milli_opt(7, 59, 59, 1_500).unwrap(); // leap second
2102 /// assert_eq!("+12345-6-7T7:59:60.5".parse::<NaiveDateTime>(), Ok(dt));
2103 ///
2104 /// assert!("foo".parse::<NaiveDateTime>().is_err());
2105 /// ```
2106 impl str::FromStr for NaiveDateTime {
2107     type Err = ParseError;
2108 
from_str(s: &str) -> ParseResult<NaiveDateTime>2109     fn from_str(s: &str) -> ParseResult<NaiveDateTime> {
2110         const ITEMS: &[Item<'static>] = &[
2111             Item::Numeric(Numeric::Year, Pad::Zero),
2112             Item::Space(""),
2113             Item::Literal("-"),
2114             Item::Numeric(Numeric::Month, Pad::Zero),
2115             Item::Space(""),
2116             Item::Literal("-"),
2117             Item::Numeric(Numeric::Day, Pad::Zero),
2118             Item::Space(""),
2119             Item::Literal("T"), // XXX shouldn't this be case-insensitive?
2120             Item::Numeric(Numeric::Hour, Pad::Zero),
2121             Item::Space(""),
2122             Item::Literal(":"),
2123             Item::Numeric(Numeric::Minute, Pad::Zero),
2124             Item::Space(""),
2125             Item::Literal(":"),
2126             Item::Numeric(Numeric::Second, Pad::Zero),
2127             Item::Fixed(Fixed::Nanosecond),
2128             Item::Space(""),
2129         ];
2130 
2131         let mut parsed = Parsed::new();
2132         parse(&mut parsed, s, ITEMS.iter())?;
2133         parsed.to_naive_datetime_with_offset(0)
2134     }
2135 }
2136 
2137 /// The default value for a NaiveDateTime is one with epoch 0
2138 /// that is, 1st of January 1970 at 00:00:00.
2139 ///
2140 /// # Example
2141 ///
2142 /// ```rust
2143 /// use chrono::NaiveDateTime;
2144 ///
2145 /// assert_eq!(NaiveDateTime::default(), NaiveDateTime::UNIX_EPOCH);
2146 /// ```
2147 impl Default for NaiveDateTime {
default() -> Self2148     fn default() -> Self {
2149         Self::UNIX_EPOCH
2150     }
2151 }
2152