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