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