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