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