chrono/naive/datetime/
mod.rs

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")]
7use core::borrow::Borrow;
8use core::fmt::Write;
9use core::ops::{Add, AddAssign, Sub, SubAssign};
10use core::time::Duration;
11use core::{fmt, str};
12
13#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
14use rkyv::{Archive, Deserialize, Serialize};
15
16#[cfg(feature = "alloc")]
17use crate::format::DelayedFormat;
18use crate::format::{Fixed, Item, Numeric, Pad};
19use crate::format::{ParseError, ParseResult, Parsed, StrftimeItems, parse, parse_and_remainder};
20use crate::naive::{Days, IsoWeek, NaiveDate, NaiveTime};
21use crate::offset::Utc;
22use crate::time_delta::NANOS_PER_SEC;
23use crate::{
24    DateTime, Datelike, FixedOffset, MappedLocalTime, Months, TimeDelta, TimeZone, Timelike,
25    Weekday, expect, try_opt,
26};
27
28/// Tools to help serializing/deserializing `NaiveDateTime`s
29#[cfg(feature = "serde")]
30pub(crate) mod serde;
31
32#[cfg(test)]
33mod tests;
34
35/// The minimum possible `NaiveDateTime`.
36#[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MIN instead")]
37pub const MIN_DATETIME: NaiveDateTime = NaiveDateTime::MIN;
38/// The maximum possible `NaiveDateTime`.
39#[deprecated(since = "0.4.20", note = "Use NaiveDateTime::MAX instead")]
40pub 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))]
76pub struct NaiveDateTime {
77    date: NaiveDate,
78    time: NaiveTime,
79}
80
81impl 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]
99    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]
122    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]
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]
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]
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]
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    /// ```
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    /// ```
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]
330    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]
345    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]
356    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]
367    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]
378    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)]
398    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]
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]
428    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]
439    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")]
448    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]
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]
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]
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.
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]
609    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
626    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]
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]
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]
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]
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]
818    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]
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]
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]
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]
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 datetime of the Unix Epoch, 1970-01-01 00:00:00.
948    ///
949    /// Note that while this may look like the UNIX epoch, it is missing the
950    /// time zone. The actual UNIX epoch cannot be expressed by this type,
951    /// however it is available as [`DateTime::UNIX_EPOCH`].
952    #[deprecated(since = "0.4.41", note = "use `DateTime::UNIX_EPOCH` instead")]
953    pub const UNIX_EPOCH: Self = DateTime::UNIX_EPOCH.naive_utc();
954}
955
956impl From<NaiveDate> for NaiveDateTime {
957    /// Converts a `NaiveDate` to a `NaiveDateTime` of the same date but at midnight.
958    ///
959    /// # Example
960    ///
961    /// ```
962    /// use chrono::{NaiveDate, NaiveDateTime};
963    ///
964    /// let nd = NaiveDate::from_ymd_opt(2016, 5, 28).unwrap();
965    /// let ndt = NaiveDate::from_ymd_opt(2016, 5, 28).unwrap().and_hms_opt(0, 0, 0).unwrap();
966    /// assert_eq!(ndt, NaiveDateTime::from(nd));
967    fn from(date: NaiveDate) -> Self {
968        date.and_hms_opt(0, 0, 0).unwrap()
969    }
970}
971
972impl Datelike for NaiveDateTime {
973    /// Returns the year number in the [calendar date](./struct.NaiveDate.html#calendar-date).
974    ///
975    /// See also the [`NaiveDate::year`](./struct.NaiveDate.html#method.year) method.
976    ///
977    /// # Example
978    ///
979    /// ```
980    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
981    ///
982    /// let dt: NaiveDateTime =
983    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
984    /// assert_eq!(dt.year(), 2015);
985    /// ```
986    #[inline]
987    fn year(&self) -> i32 {
988        self.date.year()
989    }
990
991    /// Returns the month number starting from 1.
992    ///
993    /// The return value ranges from 1 to 12.
994    ///
995    /// See also the [`NaiveDate::month`](./struct.NaiveDate.html#method.month) method.
996    ///
997    /// # Example
998    ///
999    /// ```
1000    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1001    ///
1002    /// let dt: NaiveDateTime =
1003    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1004    /// assert_eq!(dt.month(), 9);
1005    /// ```
1006    #[inline]
1007    fn month(&self) -> u32 {
1008        self.date.month()
1009    }
1010
1011    /// Returns the month number starting from 0.
1012    ///
1013    /// The return value ranges from 0 to 11.
1014    ///
1015    /// See also the [`NaiveDate::month0`] method.
1016    ///
1017    /// # Example
1018    ///
1019    /// ```
1020    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1021    ///
1022    /// let dt: NaiveDateTime =
1023    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1024    /// assert_eq!(dt.month0(), 8);
1025    /// ```
1026    #[inline]
1027    fn month0(&self) -> u32 {
1028        self.date.month0()
1029    }
1030
1031    /// Returns the day of month starting from 1.
1032    ///
1033    /// The return value ranges from 1 to 31. (The last day of month differs by months.)
1034    ///
1035    /// See also the [`NaiveDate::day`](./struct.NaiveDate.html#method.day) method.
1036    ///
1037    /// # Example
1038    ///
1039    /// ```
1040    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1041    ///
1042    /// let dt: NaiveDateTime =
1043    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1044    /// assert_eq!(dt.day(), 25);
1045    /// ```
1046    #[inline]
1047    fn day(&self) -> u32 {
1048        self.date.day()
1049    }
1050
1051    /// Returns the day of month starting from 0.
1052    ///
1053    /// The return value ranges from 0 to 30. (The last day of month differs by months.)
1054    ///
1055    /// See also the [`NaiveDate::day0`] method.
1056    ///
1057    /// # Example
1058    ///
1059    /// ```
1060    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1061    ///
1062    /// let dt: NaiveDateTime =
1063    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1064    /// assert_eq!(dt.day0(), 24);
1065    /// ```
1066    #[inline]
1067    fn day0(&self) -> u32 {
1068        self.date.day0()
1069    }
1070
1071    /// Returns the day of year starting from 1.
1072    ///
1073    /// The return value ranges from 1 to 366. (The last day of year differs by years.)
1074    ///
1075    /// See also the [`NaiveDate::ordinal`](./struct.NaiveDate.html#method.ordinal) method.
1076    ///
1077    /// # Example
1078    ///
1079    /// ```
1080    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1081    ///
1082    /// let dt: NaiveDateTime =
1083    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1084    /// assert_eq!(dt.ordinal(), 268);
1085    /// ```
1086    #[inline]
1087    fn ordinal(&self) -> u32 {
1088        self.date.ordinal()
1089    }
1090
1091    /// Returns the day of year starting from 0.
1092    ///
1093    /// The return value ranges from 0 to 365. (The last day of year differs by years.)
1094    ///
1095    /// See also the [`NaiveDate::ordinal0`] method.
1096    ///
1097    /// # Example
1098    ///
1099    /// ```
1100    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1101    ///
1102    /// let dt: NaiveDateTime =
1103    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1104    /// assert_eq!(dt.ordinal0(), 267);
1105    /// ```
1106    #[inline]
1107    fn ordinal0(&self) -> u32 {
1108        self.date.ordinal0()
1109    }
1110
1111    /// Returns the day of week.
1112    ///
1113    /// See also the [`NaiveDate::weekday`](./struct.NaiveDate.html#method.weekday) method.
1114    ///
1115    /// # Example
1116    ///
1117    /// ```
1118    /// use chrono::{Datelike, NaiveDate, NaiveDateTime, Weekday};
1119    ///
1120    /// let dt: NaiveDateTime =
1121    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1122    /// assert_eq!(dt.weekday(), Weekday::Fri);
1123    /// ```
1124    #[inline]
1125    fn weekday(&self) -> Weekday {
1126        self.date.weekday()
1127    }
1128
1129    #[inline]
1130    fn iso_week(&self) -> IsoWeek {
1131        self.date.iso_week()
1132    }
1133
1134    /// Makes a new `NaiveDateTime` with the year number changed, while keeping the same month and
1135    /// day.
1136    ///
1137    /// See also the [`NaiveDate::with_year`] method.
1138    ///
1139    /// # Errors
1140    ///
1141    /// Returns `None` if:
1142    /// - The resulting date does not exist (February 29 in a non-leap year).
1143    /// - The year is out of range for a `NaiveDate`.
1144    ///
1145    /// # Example
1146    ///
1147    /// ```
1148    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1149    ///
1150    /// let dt: NaiveDateTime =
1151    ///     NaiveDate::from_ymd_opt(2015, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap();
1152    /// assert_eq!(
1153    ///     dt.with_year(2016),
1154    ///     Some(NaiveDate::from_ymd_opt(2016, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap())
1155    /// );
1156    /// assert_eq!(
1157    ///     dt.with_year(-308),
1158    ///     Some(NaiveDate::from_ymd_opt(-308, 9, 25).unwrap().and_hms_opt(12, 34, 56).unwrap())
1159    /// );
1160    /// ```
1161    #[inline]
1162    fn with_year(&self, year: i32) -> Option<NaiveDateTime> {
1163        self.date.with_year(year).map(|d| NaiveDateTime { date: d, ..*self })
1164    }
1165
1166    /// Makes a new `NaiveDateTime` with the month number (starting from 1) changed.
1167    ///
1168    /// Don't combine multiple `Datelike::with_*` methods. The intermediate value may not exist.
1169    ///
1170    /// See also the [`NaiveDate::with_month`] method.
1171    ///
1172    /// # Errors
1173    ///
1174    /// Returns `None` if:
1175    /// - The resulting date does not exist (for example `month(4)` when day of the month is 31).
1176    /// - The value for `month` is invalid.
1177    ///
1178    /// # Example
1179    ///
1180    /// ```
1181    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1182    ///
1183    /// let dt: NaiveDateTime =
1184    ///     NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap();
1185    /// assert_eq!(
1186    ///     dt.with_month(10),
1187    ///     Some(NaiveDate::from_ymd_opt(2015, 10, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1188    /// );
1189    /// assert_eq!(dt.with_month(13), None); // No month 13
1190    /// assert_eq!(dt.with_month(2), None); // No February 30
1191    /// ```
1192    #[inline]
1193    fn with_month(&self, month: u32) -> Option<NaiveDateTime> {
1194        self.date.with_month(month).map(|d| NaiveDateTime { date: d, ..*self })
1195    }
1196
1197    /// Makes a new `NaiveDateTime` with the month number (starting from 0) changed.
1198    ///
1199    /// See also the [`NaiveDate::with_month0`] method.
1200    ///
1201    /// # Errors
1202    ///
1203    /// Returns `None` if:
1204    /// - The resulting date does not exist (for example `month0(3)` when day of the month is 31).
1205    /// - The value for `month0` is invalid.
1206    ///
1207    /// # Example
1208    ///
1209    /// ```
1210    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1211    ///
1212    /// let dt: NaiveDateTime =
1213    ///     NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap();
1214    /// assert_eq!(
1215    ///     dt.with_month0(9),
1216    ///     Some(NaiveDate::from_ymd_opt(2015, 10, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1217    /// );
1218    /// assert_eq!(dt.with_month0(12), None); // No month 13
1219    /// assert_eq!(dt.with_month0(1), None); // No February 30
1220    /// ```
1221    #[inline]
1222    fn with_month0(&self, month0: u32) -> Option<NaiveDateTime> {
1223        self.date.with_month0(month0).map(|d| NaiveDateTime { date: d, ..*self })
1224    }
1225
1226    /// Makes a new `NaiveDateTime` with the day of month (starting from 1) changed.
1227    ///
1228    /// See also the [`NaiveDate::with_day`] method.
1229    ///
1230    /// # Errors
1231    ///
1232    /// Returns `None` if:
1233    /// - The resulting date does not exist (for example `day(31)` in April).
1234    /// - The value for `day` is invalid.
1235    ///
1236    /// # Example
1237    ///
1238    /// ```
1239    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1240    ///
1241    /// let dt: NaiveDateTime =
1242    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1243    /// assert_eq!(
1244    ///     dt.with_day(30),
1245    ///     Some(NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1246    /// );
1247    /// assert_eq!(dt.with_day(31), None); // no September 31
1248    /// ```
1249    #[inline]
1250    fn with_day(&self, day: u32) -> Option<NaiveDateTime> {
1251        self.date.with_day(day).map(|d| NaiveDateTime { date: d, ..*self })
1252    }
1253
1254    /// Makes a new `NaiveDateTime` with the day of month (starting from 0) changed.
1255    ///
1256    /// See also the [`NaiveDate::with_day0`] method.
1257    ///
1258    /// # Errors
1259    ///
1260    /// Returns `None` if:
1261    /// - The resulting date does not exist (for example `day(30)` in April).
1262    /// - The value for `day0` is invalid.
1263    ///
1264    /// # Example
1265    ///
1266    /// ```
1267    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1268    ///
1269    /// let dt: NaiveDateTime =
1270    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1271    /// assert_eq!(
1272    ///     dt.with_day0(29),
1273    ///     Some(NaiveDate::from_ymd_opt(2015, 9, 30).unwrap().and_hms_opt(12, 34, 56).unwrap())
1274    /// );
1275    /// assert_eq!(dt.with_day0(30), None); // no September 31
1276    /// ```
1277    #[inline]
1278    fn with_day0(&self, day0: u32) -> Option<NaiveDateTime> {
1279        self.date.with_day0(day0).map(|d| NaiveDateTime { date: d, ..*self })
1280    }
1281
1282    /// Makes a new `NaiveDateTime` with the day of year (starting from 1) changed.
1283    ///
1284    /// See also the [`NaiveDate::with_ordinal`] method.
1285    ///
1286    /// # Errors
1287    ///
1288    /// Returns `None` if:
1289    /// - The resulting date does not exist (`with_ordinal(366)` in a non-leap year).
1290    /// - The value for `ordinal` is invalid.
1291    ///
1292    /// # Example
1293    ///
1294    /// ```
1295    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1296    ///
1297    /// let dt: NaiveDateTime =
1298    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1299    /// assert_eq!(
1300    ///     dt.with_ordinal(60),
1301    ///     Some(NaiveDate::from_ymd_opt(2015, 3, 1).unwrap().and_hms_opt(12, 34, 56).unwrap())
1302    /// );
1303    /// assert_eq!(dt.with_ordinal(366), None); // 2015 had only 365 days
1304    ///
1305    /// let dt: NaiveDateTime =
1306    ///     NaiveDate::from_ymd_opt(2016, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1307    /// assert_eq!(
1308    ///     dt.with_ordinal(60),
1309    ///     Some(NaiveDate::from_ymd_opt(2016, 2, 29).unwrap().and_hms_opt(12, 34, 56).unwrap())
1310    /// );
1311    /// assert_eq!(
1312    ///     dt.with_ordinal(366),
1313    ///     Some(NaiveDate::from_ymd_opt(2016, 12, 31).unwrap().and_hms_opt(12, 34, 56).unwrap())
1314    /// );
1315    /// ```
1316    #[inline]
1317    fn with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime> {
1318        self.date.with_ordinal(ordinal).map(|d| NaiveDateTime { date: d, ..*self })
1319    }
1320
1321    /// Makes a new `NaiveDateTime` with the day of year (starting from 0) changed.
1322    ///
1323    /// See also the [`NaiveDate::with_ordinal0`] method.
1324    ///
1325    /// # Errors
1326    ///
1327    /// Returns `None` if:
1328    /// - The resulting date does not exist (`with_ordinal0(365)` in a non-leap year).
1329    /// - The value for `ordinal0` is invalid.
1330    ///
1331    /// # Example
1332    ///
1333    /// ```
1334    /// use chrono::{Datelike, NaiveDate, NaiveDateTime};
1335    ///
1336    /// let dt: NaiveDateTime =
1337    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1338    /// assert_eq!(
1339    ///     dt.with_ordinal0(59),
1340    ///     Some(NaiveDate::from_ymd_opt(2015, 3, 1).unwrap().and_hms_opt(12, 34, 56).unwrap())
1341    /// );
1342    /// assert_eq!(dt.with_ordinal0(365), None); // 2015 had only 365 days
1343    ///
1344    /// let dt: NaiveDateTime =
1345    ///     NaiveDate::from_ymd_opt(2016, 9, 8).unwrap().and_hms_opt(12, 34, 56).unwrap();
1346    /// assert_eq!(
1347    ///     dt.with_ordinal0(59),
1348    ///     Some(NaiveDate::from_ymd_opt(2016, 2, 29).unwrap().and_hms_opt(12, 34, 56).unwrap())
1349    /// );
1350    /// assert_eq!(
1351    ///     dt.with_ordinal0(365),
1352    ///     Some(NaiveDate::from_ymd_opt(2016, 12, 31).unwrap().and_hms_opt(12, 34, 56).unwrap())
1353    /// );
1354    /// ```
1355    #[inline]
1356    fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime> {
1357        self.date.with_ordinal0(ordinal0).map(|d| NaiveDateTime { date: d, ..*self })
1358    }
1359}
1360
1361impl Timelike for NaiveDateTime {
1362    /// Returns the hour number from 0 to 23.
1363    ///
1364    /// See also the [`NaiveTime::hour`] method.
1365    ///
1366    /// # Example
1367    ///
1368    /// ```
1369    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1370    ///
1371    /// let dt: NaiveDateTime =
1372    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1373    /// assert_eq!(dt.hour(), 12);
1374    /// ```
1375    #[inline]
1376    fn hour(&self) -> u32 {
1377        self.time.hour()
1378    }
1379
1380    /// Returns the minute number from 0 to 59.
1381    ///
1382    /// See also the [`NaiveTime::minute`] method.
1383    ///
1384    /// # Example
1385    ///
1386    /// ```
1387    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1388    ///
1389    /// let dt: NaiveDateTime =
1390    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1391    /// assert_eq!(dt.minute(), 34);
1392    /// ```
1393    #[inline]
1394    fn minute(&self) -> u32 {
1395        self.time.minute()
1396    }
1397
1398    /// Returns the second number from 0 to 59.
1399    ///
1400    /// See also the [`NaiveTime::second`] method.
1401    ///
1402    /// # Example
1403    ///
1404    /// ```
1405    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1406    ///
1407    /// let dt: NaiveDateTime =
1408    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1409    /// assert_eq!(dt.second(), 56);
1410    /// ```
1411    #[inline]
1412    fn second(&self) -> u32 {
1413        self.time.second()
1414    }
1415
1416    /// Returns the number of nanoseconds since the whole non-leap second.
1417    /// The range from 1,000,000,000 to 1,999,999,999 represents
1418    /// the [leap second](./struct.NaiveTime.html#leap-second-handling).
1419    ///
1420    /// See also the [`NaiveTime#method.nanosecond`] method.
1421    ///
1422    /// # Example
1423    ///
1424    /// ```
1425    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1426    ///
1427    /// let dt: NaiveDateTime =
1428    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1429    /// assert_eq!(dt.nanosecond(), 789_000_000);
1430    /// ```
1431    #[inline]
1432    fn nanosecond(&self) -> u32 {
1433        self.time.nanosecond()
1434    }
1435
1436    /// Makes a new `NaiveDateTime` with the hour number changed.
1437    ///
1438    /// See also the [`NaiveTime::with_hour`] method.
1439    ///
1440    /// # Errors
1441    ///
1442    /// Returns `None` if the value for `hour` is invalid.
1443    ///
1444    /// # Example
1445    ///
1446    /// ```
1447    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1448    ///
1449    /// let dt: NaiveDateTime =
1450    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1451    /// assert_eq!(
1452    ///     dt.with_hour(7),
1453    ///     Some(
1454    ///         NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(7, 34, 56, 789).unwrap()
1455    ///     )
1456    /// );
1457    /// assert_eq!(dt.with_hour(24), None);
1458    /// ```
1459    #[inline]
1460    fn with_hour(&self, hour: u32) -> Option<NaiveDateTime> {
1461        self.time.with_hour(hour).map(|t| NaiveDateTime { time: t, ..*self })
1462    }
1463
1464    /// Makes a new `NaiveDateTime` with the minute number changed.
1465    ///
1466    /// See also the [`NaiveTime::with_minute`] method.
1467    ///
1468    /// # Errors
1469    ///
1470    /// Returns `None` if the value for `minute` is invalid.
1471    ///
1472    /// # Example
1473    ///
1474    /// ```
1475    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1476    ///
1477    /// let dt: NaiveDateTime =
1478    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1479    /// assert_eq!(
1480    ///     dt.with_minute(45),
1481    ///     Some(
1482    ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1483    ///             .unwrap()
1484    ///             .and_hms_milli_opt(12, 45, 56, 789)
1485    ///             .unwrap()
1486    ///     )
1487    /// );
1488    /// assert_eq!(dt.with_minute(60), None);
1489    /// ```
1490    #[inline]
1491    fn with_minute(&self, min: u32) -> Option<NaiveDateTime> {
1492        self.time.with_minute(min).map(|t| NaiveDateTime { time: t, ..*self })
1493    }
1494
1495    /// Makes a new `NaiveDateTime` with the second number changed.
1496    ///
1497    /// As with the [`second`](#method.second) method,
1498    /// the input range is restricted to 0 through 59.
1499    ///
1500    /// See also the [`NaiveTime::with_second`] method.
1501    ///
1502    /// # Errors
1503    ///
1504    /// Returns `None` if the value for `second` is invalid.
1505    ///
1506    /// # Example
1507    ///
1508    /// ```
1509    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1510    ///
1511    /// let dt: NaiveDateTime =
1512    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 56, 789).unwrap();
1513    /// assert_eq!(
1514    ///     dt.with_second(17),
1515    ///     Some(
1516    ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1517    ///             .unwrap()
1518    ///             .and_hms_milli_opt(12, 34, 17, 789)
1519    ///             .unwrap()
1520    ///     )
1521    /// );
1522    /// assert_eq!(dt.with_second(60), None);
1523    /// ```
1524    #[inline]
1525    fn with_second(&self, sec: u32) -> Option<NaiveDateTime> {
1526        self.time.with_second(sec).map(|t| NaiveDateTime { time: t, ..*self })
1527    }
1528
1529    /// Makes a new `NaiveDateTime` with nanoseconds since the whole non-leap second changed.
1530    ///
1531    /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1532    /// As with the [`NaiveDateTime::nanosecond`] method,
1533    /// the input range can exceed 1,000,000,000 for leap seconds.
1534    ///
1535    /// See also the [`NaiveTime::with_nanosecond`] method.
1536    ///
1537    /// # Errors
1538    ///
1539    /// Returns `None` if `nanosecond >= 2,000,000,000`.
1540    ///
1541    /// # Example
1542    ///
1543    /// ```
1544    /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1545    ///
1546    /// let dt: NaiveDateTime =
1547    ///     NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().and_hms_milli_opt(12, 34, 59, 789).unwrap();
1548    /// assert_eq!(
1549    ///     dt.with_nanosecond(333_333_333),
1550    ///     Some(
1551    ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1552    ///             .unwrap()
1553    ///             .and_hms_nano_opt(12, 34, 59, 333_333_333)
1554    ///             .unwrap()
1555    ///     )
1556    /// );
1557    /// assert_eq!(
1558    ///     dt.with_nanosecond(1_333_333_333), // leap second
1559    ///     Some(
1560    ///         NaiveDate::from_ymd_opt(2015, 9, 8)
1561    ///             .unwrap()
1562    ///             .and_hms_nano_opt(12, 34, 59, 1_333_333_333)
1563    ///             .unwrap()
1564    ///     )
1565    /// );
1566    /// assert_eq!(dt.with_nanosecond(2_000_000_000), None);
1567    /// ```
1568    #[inline]
1569    fn with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime> {
1570        self.time.with_nanosecond(nano).map(|t| NaiveDateTime { time: t, ..*self })
1571    }
1572}
1573
1574/// Add `TimeDelta` to `NaiveDateTime`.
1575///
1576/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1577/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1578/// the assumption becomes that **there is exactly a single leap second ever**.
1579///
1580/// # Panics
1581///
1582/// Panics if the resulting date would be out of range.
1583/// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1584///
1585/// # Example
1586///
1587/// ```
1588/// use chrono::{NaiveDate, TimeDelta};
1589///
1590/// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1591///
1592/// let d = from_ymd(2016, 7, 8);
1593/// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
1594/// assert_eq!(hms(3, 5, 7) + TimeDelta::zero(), hms(3, 5, 7));
1595/// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(1).unwrap(), hms(3, 5, 8));
1596/// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(-1).unwrap(), hms(3, 5, 6));
1597/// assert_eq!(hms(3, 5, 7) + TimeDelta::try_seconds(3600 + 60).unwrap(), hms(4, 6, 7));
1598/// assert_eq!(
1599///     hms(3, 5, 7) + TimeDelta::try_seconds(86_400).unwrap(),
1600///     from_ymd(2016, 7, 9).and_hms_opt(3, 5, 7).unwrap()
1601/// );
1602/// assert_eq!(
1603///     hms(3, 5, 7) + TimeDelta::try_days(365).unwrap(),
1604///     from_ymd(2017, 7, 8).and_hms_opt(3, 5, 7).unwrap()
1605/// );
1606///
1607/// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
1608/// assert_eq!(hmsm(3, 5, 7, 980) + TimeDelta::try_milliseconds(450).unwrap(), hmsm(3, 5, 8, 430));
1609/// ```
1610///
1611/// Leap seconds are handled,
1612/// but the addition assumes that it is the only leap second happened.
1613///
1614/// ```
1615/// # use chrono::{TimeDelta, NaiveDate};
1616/// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1617/// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
1618/// let leap = hmsm(3, 5, 59, 1_300);
1619/// assert_eq!(leap + TimeDelta::zero(), hmsm(3, 5, 59, 1_300));
1620/// assert_eq!(leap + TimeDelta::try_milliseconds(-500).unwrap(), hmsm(3, 5, 59, 800));
1621/// assert_eq!(leap + TimeDelta::try_milliseconds(500).unwrap(), hmsm(3, 5, 59, 1_800));
1622/// assert_eq!(leap + TimeDelta::try_milliseconds(800).unwrap(), hmsm(3, 6, 0, 100));
1623/// assert_eq!(leap + TimeDelta::try_seconds(10).unwrap(), hmsm(3, 6, 9, 300));
1624/// assert_eq!(leap + TimeDelta::try_seconds(-10).unwrap(), hmsm(3, 5, 50, 300));
1625/// assert_eq!(leap + TimeDelta::try_days(1).unwrap(),
1626///            from_ymd(2016, 7, 9).and_hms_milli_opt(3, 5, 59, 300).unwrap());
1627/// ```
1628///
1629/// [leap second handling]: crate::NaiveTime#leap-second-handling
1630impl Add<TimeDelta> for NaiveDateTime {
1631    type Output = NaiveDateTime;
1632
1633    #[inline]
1634    fn add(self, rhs: TimeDelta) -> NaiveDateTime {
1635        self.checked_add_signed(rhs).expect("`NaiveDateTime + TimeDelta` overflowed")
1636    }
1637}
1638
1639/// Add `std::time::Duration` to `NaiveDateTime`.
1640///
1641/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1642/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1643/// the assumption becomes that **there is exactly a single leap second ever**.
1644///
1645/// # Panics
1646///
1647/// Panics if the resulting date would be out of range.
1648/// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1649impl Add<Duration> for NaiveDateTime {
1650    type Output = NaiveDateTime;
1651
1652    #[inline]
1653    fn add(self, rhs: Duration) -> NaiveDateTime {
1654        let rhs = TimeDelta::from_std(rhs)
1655            .expect("overflow converting from core::time::Duration to TimeDelta");
1656        self.checked_add_signed(rhs).expect("`NaiveDateTime + TimeDelta` overflowed")
1657    }
1658}
1659
1660/// Add-assign `TimeDelta` to `NaiveDateTime`.
1661///
1662/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1663/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1664/// the assumption becomes that **there is exactly a single leap second ever**.
1665///
1666/// # Panics
1667///
1668/// Panics if the resulting date would be out of range.
1669/// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1670impl AddAssign<TimeDelta> for NaiveDateTime {
1671    #[inline]
1672    fn add_assign(&mut self, rhs: TimeDelta) {
1673        *self = self.add(rhs);
1674    }
1675}
1676
1677/// Add-assign `std::time::Duration` to `NaiveDateTime`.
1678///
1679/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1680/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1681/// the assumption becomes that **there is exactly a single leap second ever**.
1682///
1683/// # Panics
1684///
1685/// Panics if the resulting date would be out of range.
1686/// Consider using [`NaiveDateTime::checked_add_signed`] to get an `Option` instead.
1687impl AddAssign<Duration> for NaiveDateTime {
1688    #[inline]
1689    fn add_assign(&mut self, rhs: Duration) {
1690        *self = self.add(rhs);
1691    }
1692}
1693
1694/// Add `FixedOffset` to `NaiveDateTime`.
1695///
1696/// # Panics
1697///
1698/// Panics if the resulting date would be out of range.
1699/// Consider using `checked_add_offset` to get an `Option` instead.
1700impl Add<FixedOffset> for NaiveDateTime {
1701    type Output = NaiveDateTime;
1702
1703    #[inline]
1704    fn add(self, rhs: FixedOffset) -> NaiveDateTime {
1705        self.checked_add_offset(rhs).expect("`NaiveDateTime + FixedOffset` out of range")
1706    }
1707}
1708
1709/// Add `Months` to `NaiveDateTime`.
1710///
1711/// The result will be clamped to valid days in the resulting month, see `checked_add_months` for
1712/// details.
1713///
1714/// # Panics
1715///
1716/// Panics if the resulting date would be out of range.
1717/// Consider using `checked_add_months` to get an `Option` instead.
1718///
1719/// # Example
1720///
1721/// ```
1722/// use chrono::{Months, NaiveDate};
1723///
1724/// assert_eq!(
1725///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(1, 0, 0).unwrap() + Months::new(1),
1726///     NaiveDate::from_ymd_opt(2014, 2, 1).unwrap().and_hms_opt(1, 0, 0).unwrap()
1727/// );
1728/// assert_eq!(
1729///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 2, 0).unwrap()
1730///         + Months::new(11),
1731///     NaiveDate::from_ymd_opt(2014, 12, 1).unwrap().and_hms_opt(0, 2, 0).unwrap()
1732/// );
1733/// assert_eq!(
1734///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 0, 3).unwrap()
1735///         + Months::new(12),
1736///     NaiveDate::from_ymd_opt(2015, 1, 1).unwrap().and_hms_opt(0, 0, 3).unwrap()
1737/// );
1738/// assert_eq!(
1739///     NaiveDate::from_ymd_opt(2014, 1, 1).unwrap().and_hms_opt(0, 0, 4).unwrap()
1740///         + Months::new(13),
1741///     NaiveDate::from_ymd_opt(2015, 2, 1).unwrap().and_hms_opt(0, 0, 4).unwrap()
1742/// );
1743/// assert_eq!(
1744///     NaiveDate::from_ymd_opt(2014, 1, 31).unwrap().and_hms_opt(0, 5, 0).unwrap()
1745///         + Months::new(1),
1746///     NaiveDate::from_ymd_opt(2014, 2, 28).unwrap().and_hms_opt(0, 5, 0).unwrap()
1747/// );
1748/// assert_eq!(
1749///     NaiveDate::from_ymd_opt(2020, 1, 31).unwrap().and_hms_opt(6, 0, 0).unwrap()
1750///         + Months::new(1),
1751///     NaiveDate::from_ymd_opt(2020, 2, 29).unwrap().and_hms_opt(6, 0, 0).unwrap()
1752/// );
1753/// ```
1754impl Add<Months> for NaiveDateTime {
1755    type Output = NaiveDateTime;
1756
1757    fn add(self, rhs: Months) -> Self::Output {
1758        self.checked_add_months(rhs).expect("`NaiveDateTime + Months` out of range")
1759    }
1760}
1761
1762/// Subtract `TimeDelta` from `NaiveDateTime`.
1763///
1764/// This is the same as the addition with a negated `TimeDelta`.
1765///
1766/// As a part of Chrono's [leap second handling] the subtraction assumes that **there is no leap
1767/// second ever**, except when the `NaiveDateTime` itself represents a leap second in which case
1768/// the assumption becomes that **there is exactly a single leap second ever**.
1769///
1770/// # Panics
1771///
1772/// Panics if the resulting date would be out of range.
1773/// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1774///
1775/// # Example
1776///
1777/// ```
1778/// use chrono::{NaiveDate, TimeDelta};
1779///
1780/// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1781///
1782/// let d = from_ymd(2016, 7, 8);
1783/// let hms = |h, m, s| d.and_hms_opt(h, m, s).unwrap();
1784/// assert_eq!(hms(3, 5, 7) - TimeDelta::zero(), hms(3, 5, 7));
1785/// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(1).unwrap(), hms(3, 5, 6));
1786/// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(-1).unwrap(), hms(3, 5, 8));
1787/// assert_eq!(hms(3, 5, 7) - TimeDelta::try_seconds(3600 + 60).unwrap(), hms(2, 4, 7));
1788/// assert_eq!(
1789///     hms(3, 5, 7) - TimeDelta::try_seconds(86_400).unwrap(),
1790///     from_ymd(2016, 7, 7).and_hms_opt(3, 5, 7).unwrap()
1791/// );
1792/// assert_eq!(
1793///     hms(3, 5, 7) - TimeDelta::try_days(365).unwrap(),
1794///     from_ymd(2015, 7, 9).and_hms_opt(3, 5, 7).unwrap()
1795/// );
1796///
1797/// let hmsm = |h, m, s, milli| d.and_hms_milli_opt(h, m, s, milli).unwrap();
1798/// assert_eq!(hmsm(3, 5, 7, 450) - TimeDelta::try_milliseconds(670).unwrap(), hmsm(3, 5, 6, 780));
1799/// ```
1800///
1801/// Leap seconds are handled,
1802/// but the subtraction assumes that it is the only leap second happened.
1803///
1804/// ```
1805/// # use chrono::{TimeDelta, NaiveDate};
1806/// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1807/// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli_opt(h, m, s, milli).unwrap();
1808/// let leap = hmsm(3, 5, 59, 1_300);
1809/// assert_eq!(leap - TimeDelta::zero(), hmsm(3, 5, 59, 1_300));
1810/// assert_eq!(leap - TimeDelta::try_milliseconds(200).unwrap(), hmsm(3, 5, 59, 1_100));
1811/// assert_eq!(leap - TimeDelta::try_milliseconds(500).unwrap(), hmsm(3, 5, 59, 800));
1812/// assert_eq!(leap - TimeDelta::try_seconds(60).unwrap(), hmsm(3, 5, 0, 300));
1813/// assert_eq!(leap - TimeDelta::try_days(1).unwrap(),
1814///            from_ymd(2016, 7, 7).and_hms_milli_opt(3, 6, 0, 300).unwrap());
1815/// ```
1816///
1817/// [leap second handling]: crate::NaiveTime#leap-second-handling
1818impl Sub<TimeDelta> for NaiveDateTime {
1819    type Output = NaiveDateTime;
1820
1821    #[inline]
1822    fn sub(self, rhs: TimeDelta) -> NaiveDateTime {
1823        self.checked_sub_signed(rhs).expect("`NaiveDateTime - TimeDelta` overflowed")
1824    }
1825}
1826
1827/// Subtract `std::time::Duration` from `NaiveDateTime`.
1828///
1829/// As a part of Chrono's [leap second handling] the subtraction assumes that **there is no leap
1830/// second ever**, except when the `NaiveDateTime` itself represents a leap second in which case
1831/// the assumption becomes that **there is exactly a single leap second ever**.
1832///
1833/// # Panics
1834///
1835/// Panics if the resulting date would be out of range.
1836/// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1837impl Sub<Duration> for NaiveDateTime {
1838    type Output = NaiveDateTime;
1839
1840    #[inline]
1841    fn sub(self, rhs: Duration) -> NaiveDateTime {
1842        let rhs = TimeDelta::from_std(rhs)
1843            .expect("overflow converting from core::time::Duration to TimeDelta");
1844        self.checked_sub_signed(rhs).expect("`NaiveDateTime - TimeDelta` overflowed")
1845    }
1846}
1847
1848/// Subtract-assign `TimeDelta` from `NaiveDateTime`.
1849///
1850/// This is the same as the addition with a negated `TimeDelta`.
1851///
1852/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1853/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1854/// the assumption becomes that **there is exactly a single leap second ever**.
1855///
1856/// # Panics
1857///
1858/// Panics if the resulting date would be out of range.
1859/// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1860impl SubAssign<TimeDelta> for NaiveDateTime {
1861    #[inline]
1862    fn sub_assign(&mut self, rhs: TimeDelta) {
1863        *self = self.sub(rhs);
1864    }
1865}
1866
1867/// Subtract-assign `std::time::Duration` from `NaiveDateTime`.
1868///
1869/// As a part of Chrono's [leap second handling], the addition assumes that **there is no leap
1870/// second ever**, except when the `NaiveDateTime` itself represents a leap  second in which case
1871/// the assumption becomes that **there is exactly a single leap second ever**.
1872///
1873/// # Panics
1874///
1875/// Panics if the resulting date would be out of range.
1876/// Consider using [`NaiveDateTime::checked_sub_signed`] to get an `Option` instead.
1877impl SubAssign<Duration> for NaiveDateTime {
1878    #[inline]
1879    fn sub_assign(&mut self, rhs: Duration) {
1880        *self = self.sub(rhs);
1881    }
1882}
1883
1884/// Subtract `FixedOffset` from `NaiveDateTime`.
1885///
1886/// # Panics
1887///
1888/// Panics if the resulting date would be out of range.
1889/// Consider using `checked_sub_offset` to get an `Option` instead.
1890impl Sub<FixedOffset> for NaiveDateTime {
1891    type Output = NaiveDateTime;
1892
1893    #[inline]
1894    fn sub(self, rhs: FixedOffset) -> NaiveDateTime {
1895        self.checked_sub_offset(rhs).expect("`NaiveDateTime - FixedOffset` out of range")
1896    }
1897}
1898
1899/// Subtract `Months` from `NaiveDateTime`.
1900///
1901/// The result will be clamped to valid days in the resulting month, see
1902/// [`NaiveDateTime::checked_sub_months`] for details.
1903///
1904/// # Panics
1905///
1906/// Panics if the resulting date would be out of range.
1907/// Consider using [`NaiveDateTime::checked_sub_months`] to get an `Option` instead.
1908///
1909/// # Example
1910///
1911/// ```
1912/// use chrono::{Months, NaiveDate};
1913///
1914/// assert_eq!(
1915///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(01, 00, 00).unwrap()
1916///         - Months::new(11),
1917///     NaiveDate::from_ymd_opt(2013, 02, 01).unwrap().and_hms_opt(01, 00, 00).unwrap()
1918/// );
1919/// assert_eq!(
1920///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(00, 02, 00).unwrap()
1921///         - Months::new(12),
1922///     NaiveDate::from_ymd_opt(2013, 01, 01).unwrap().and_hms_opt(00, 02, 00).unwrap()
1923/// );
1924/// assert_eq!(
1925///     NaiveDate::from_ymd_opt(2014, 01, 01).unwrap().and_hms_opt(00, 00, 03).unwrap()
1926///         - Months::new(13),
1927///     NaiveDate::from_ymd_opt(2012, 12, 01).unwrap().and_hms_opt(00, 00, 03).unwrap()
1928/// );
1929/// ```
1930impl Sub<Months> for NaiveDateTime {
1931    type Output = NaiveDateTime;
1932
1933    fn sub(self, rhs: Months) -> Self::Output {
1934        self.checked_sub_months(rhs).expect("`NaiveDateTime - Months` out of range")
1935    }
1936}
1937
1938/// Subtracts another `NaiveDateTime` from the current date and time.
1939/// This does not overflow or underflow at all.
1940///
1941/// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
1942/// the subtraction assumes that **there is no leap second ever**,
1943/// except when any of the `NaiveDateTime`s themselves represents a leap second
1944/// in which case the assumption becomes that
1945/// **there are exactly one (or two) leap second(s) ever**.
1946///
1947/// The implementation is a wrapper around [`NaiveDateTime::signed_duration_since`].
1948///
1949/// # Example
1950///
1951/// ```
1952/// use chrono::{NaiveDate, TimeDelta};
1953///
1954/// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1955///
1956/// let d = from_ymd(2016, 7, 8);
1957/// assert_eq!(
1958///     d.and_hms_opt(3, 5, 7).unwrap() - d.and_hms_opt(2, 4, 6).unwrap(),
1959///     TimeDelta::try_seconds(3600 + 60 + 1).unwrap()
1960/// );
1961///
1962/// // July 8 is 190th day in the year 2016
1963/// let d0 = from_ymd(2016, 1, 1);
1964/// assert_eq!(
1965///     d.and_hms_milli_opt(0, 7, 6, 500).unwrap() - d0.and_hms_opt(0, 0, 0).unwrap(),
1966///     TimeDelta::try_seconds(189 * 86_400 + 7 * 60 + 6).unwrap()
1967///         + TimeDelta::try_milliseconds(500).unwrap()
1968/// );
1969/// ```
1970///
1971/// Leap seconds are handled, but the subtraction assumes that no other leap
1972/// seconds happened.
1973///
1974/// ```
1975/// # use chrono::{TimeDelta, NaiveDate};
1976/// # let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
1977/// let leap = from_ymd(2015, 6, 30).and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
1978/// assert_eq!(
1979///     leap - from_ymd(2015, 6, 30).and_hms_opt(23, 0, 0).unwrap(),
1980///     TimeDelta::try_seconds(3600).unwrap() + TimeDelta::try_milliseconds(500).unwrap()
1981/// );
1982/// assert_eq!(
1983///     from_ymd(2015, 7, 1).and_hms_opt(1, 0, 0).unwrap() - leap,
1984///     TimeDelta::try_seconds(3600).unwrap() - TimeDelta::try_milliseconds(500).unwrap()
1985/// );
1986/// ```
1987impl Sub<NaiveDateTime> for NaiveDateTime {
1988    type Output = TimeDelta;
1989
1990    #[inline]
1991    fn sub(self, rhs: NaiveDateTime) -> TimeDelta {
1992        self.signed_duration_since(rhs)
1993    }
1994}
1995
1996/// Add `Days` to `NaiveDateTime`.
1997///
1998/// # Panics
1999///
2000/// Panics if the resulting date would be out of range.
2001/// Consider using `checked_add_days` to get an `Option` instead.
2002impl Add<Days> for NaiveDateTime {
2003    type Output = NaiveDateTime;
2004
2005    fn add(self, days: Days) -> Self::Output {
2006        self.checked_add_days(days).expect("`NaiveDateTime + Days` out of range")
2007    }
2008}
2009
2010/// Subtract `Days` from `NaiveDateTime`.
2011///
2012/// # Panics
2013///
2014/// Panics if the resulting date would be out of range.
2015/// Consider using `checked_sub_days` to get an `Option` instead.
2016impl Sub<Days> for NaiveDateTime {
2017    type Output = NaiveDateTime;
2018
2019    fn sub(self, days: Days) -> Self::Output {
2020        self.checked_sub_days(days).expect("`NaiveDateTime - Days` out of range")
2021    }
2022}
2023
2024/// The `Debug` output of the naive date and time `dt` is the same as
2025/// [`dt.format("%Y-%m-%dT%H:%M:%S%.f")`](crate::format::strftime).
2026///
2027/// The string printed can be readily parsed via the `parse` method on `str`.
2028///
2029/// It should be noted that, for leap seconds not on the minute boundary,
2030/// it may print a representation not distinguishable from non-leap seconds.
2031/// This doesn't matter in practice, since such leap seconds never happened.
2032/// (By the time of the first leap second on 1972-06-30,
2033/// every time zone offset around the world has standardized to the 5-minute alignment.)
2034///
2035/// # Example
2036///
2037/// ```
2038/// use chrono::NaiveDate;
2039///
2040/// let dt = NaiveDate::from_ymd_opt(2016, 11, 15).unwrap().and_hms_opt(7, 39, 24).unwrap();
2041/// assert_eq!(format!("{:?}", dt), "2016-11-15T07:39:24");
2042/// ```
2043///
2044/// Leap seconds may also be used.
2045///
2046/// ```
2047/// # use chrono::NaiveDate;
2048/// let dt =
2049///     NaiveDate::from_ymd_opt(2015, 6, 30).unwrap().and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
2050/// assert_eq!(format!("{:?}", dt), "2015-06-30T23:59:60.500");
2051/// ```
2052impl fmt::Debug for NaiveDateTime {
2053    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2054        self.date.fmt(f)?;
2055        f.write_char('T')?;
2056        self.time.fmt(f)
2057    }
2058}
2059
2060/// The `Display` output of the naive date and time `dt` is the same as
2061/// [`dt.format("%Y-%m-%d %H:%M:%S%.f")`](crate::format::strftime).
2062///
2063/// It should be noted that, for leap seconds not on the minute boundary,
2064/// it may print a representation not distinguishable from non-leap seconds.
2065/// This doesn't matter in practice, since such leap seconds never happened.
2066/// (By the time of the first leap second on 1972-06-30,
2067/// every time zone offset around the world has standardized to the 5-minute alignment.)
2068///
2069/// # Example
2070///
2071/// ```
2072/// use chrono::NaiveDate;
2073///
2074/// let dt = NaiveDate::from_ymd_opt(2016, 11, 15).unwrap().and_hms_opt(7, 39, 24).unwrap();
2075/// assert_eq!(format!("{}", dt), "2016-11-15 07:39:24");
2076/// ```
2077///
2078/// Leap seconds may also be used.
2079///
2080/// ```
2081/// # use chrono::NaiveDate;
2082/// let dt =
2083///     NaiveDate::from_ymd_opt(2015, 6, 30).unwrap().and_hms_milli_opt(23, 59, 59, 1_500).unwrap();
2084/// assert_eq!(format!("{}", dt), "2015-06-30 23:59:60.500");
2085/// ```
2086impl fmt::Display for NaiveDateTime {
2087    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2088        self.date.fmt(f)?;
2089        f.write_char(' ')?;
2090        self.time.fmt(f)
2091    }
2092}
2093
2094/// Parsing a `str` into a `NaiveDateTime` uses the same format,
2095/// [`%Y-%m-%dT%H:%M:%S%.f`](crate::format::strftime), as in `Debug`.
2096///
2097/// # Example
2098///
2099/// ```
2100/// use chrono::{NaiveDateTime, NaiveDate};
2101///
2102/// let dt = NaiveDate::from_ymd_opt(2015, 9, 18).unwrap().and_hms_opt(23, 56, 4).unwrap();
2103/// assert_eq!("2015-09-18T23:56:04".parse::<NaiveDateTime>(), Ok(dt));
2104///
2105/// let dt = NaiveDate::from_ymd_opt(12345, 6, 7).unwrap().and_hms_milli_opt(7, 59, 59, 1_500).unwrap(); // leap second
2106/// assert_eq!("+12345-6-7T7:59:60.5".parse::<NaiveDateTime>(), Ok(dt));
2107///
2108/// assert!("foo".parse::<NaiveDateTime>().is_err());
2109/// ```
2110impl str::FromStr for NaiveDateTime {
2111    type Err = ParseError;
2112
2113    fn from_str(s: &str) -> ParseResult<NaiveDateTime> {
2114        const ITEMS: &[Item<'static>] = &[
2115            Item::Numeric(Numeric::Year, Pad::Zero),
2116            Item::Space(""),
2117            Item::Literal("-"),
2118            Item::Numeric(Numeric::Month, Pad::Zero),
2119            Item::Space(""),
2120            Item::Literal("-"),
2121            Item::Numeric(Numeric::Day, Pad::Zero),
2122            Item::Space(""),
2123            Item::Literal("T"), // XXX shouldn't this be case-insensitive?
2124            Item::Numeric(Numeric::Hour, Pad::Zero),
2125            Item::Space(""),
2126            Item::Literal(":"),
2127            Item::Numeric(Numeric::Minute, Pad::Zero),
2128            Item::Space(""),
2129            Item::Literal(":"),
2130            Item::Numeric(Numeric::Second, Pad::Zero),
2131            Item::Fixed(Fixed::Nanosecond),
2132            Item::Space(""),
2133        ];
2134
2135        let mut parsed = Parsed::new();
2136        parse(&mut parsed, s, ITEMS.iter())?;
2137        parsed.to_naive_datetime_with_offset(0)
2138    }
2139}
2140
2141/// The default value for a NaiveDateTime is 1st of January 1970 at 00:00:00.
2142///
2143/// Note that while this may look like the UNIX epoch, it is missing the
2144/// time zone. The actual UNIX epoch cannot be expressed by this type,
2145/// however it is available as [`DateTime::UNIX_EPOCH`].
2146impl Default for NaiveDateTime {
2147    fn default() -> Self {
2148        DateTime::UNIX_EPOCH.naive_local()
2149    }
2150}