1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
3 
4 //! ISO 8601 date and time without timezone.
5 
6 #[cfg(any(feature = "alloc", feature = "std", test))]
7 use core::borrow::Borrow;
8 use core::ops::{Add, AddAssign, Sub, SubAssign};
9 use core::{fmt, hash, str};
10 use num_traits::ToPrimitive;
11 use oldtime::Duration as OldDuration;
12 
13 use div::div_mod_floor;
14 #[cfg(any(feature = "alloc", feature = "std", test))]
15 use format::DelayedFormat;
16 use format::{parse, ParseError, ParseResult, Parsed, StrftimeItems};
17 use format::{Fixed, Item, Numeric, Pad};
18 use naive::date::{MAX_DATE, MIN_DATE};
19 use naive::time::{MAX_TIME, MIN_TIME};
20 use naive::{IsoWeek, NaiveDate, NaiveTime};
21 use {Datelike, Timelike, Weekday};
22 
23 /// The tight upper bound guarantees that a duration with `|Duration| >= 2^MAX_SECS_BITS`
24 /// will always overflow the addition with any date and time type.
25 ///
26 /// So why is this needed? `Duration::seconds(rhs)` may overflow, and we don't have
27 /// an alternative returning `Option` or `Result`. Thus we need some early bound to avoid
28 /// touching that call when we are already sure that it WILL overflow...
29 const MAX_SECS_BITS: usize = 44;
30 
31 /// The minimum possible `NaiveDateTime`.
32 pub const MIN_DATETIME: NaiveDateTime = NaiveDateTime { date: MIN_DATE, time: MIN_TIME };
33 /// The maximum possible `NaiveDateTime`.
34 pub const MAX_DATETIME: NaiveDateTime = NaiveDateTime { date: MAX_DATE, time: MAX_TIME };
35 
36 /// ISO 8601 combined date and time without timezone.
37 ///
38 /// # Example
39 ///
40 /// `NaiveDateTime` is commonly created from [`NaiveDate`](./struct.NaiveDate.html).
41 ///
42 /// ~~~~
43 /// use chrono::{NaiveDate, NaiveDateTime};
44 ///
45 /// let dt: NaiveDateTime = NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11);
46 /// # let _ = dt;
47 /// ~~~~
48 ///
49 /// You can use typical [date-like](../trait.Datelike.html) and
50 /// [time-like](../trait.Timelike.html) methods,
51 /// provided that relevant traits are in the scope.
52 ///
53 /// ~~~~
54 /// # use chrono::{NaiveDate, NaiveDateTime};
55 /// # let dt: NaiveDateTime = NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11);
56 /// use chrono::{Datelike, Timelike, Weekday};
57 ///
58 /// assert_eq!(dt.weekday(), Weekday::Fri);
59 /// assert_eq!(dt.num_seconds_from_midnight(), 33011);
60 /// ~~~~
61 #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
62 pub struct NaiveDateTime {
63     date: NaiveDate,
64     time: NaiveTime,
65 }
66 
67 impl NaiveDateTime {
68     /// Makes a new `NaiveDateTime` from date and time components.
69     /// Equivalent to [`date.and_time(time)`](./struct.NaiveDate.html#method.and_time)
70     /// and many other helper constructors on `NaiveDate`.
71     ///
72     /// # Example
73     ///
74     /// ~~~~
75     /// use chrono::{NaiveDate, NaiveTime, NaiveDateTime};
76     ///
77     /// let d = NaiveDate::from_ymd(2015, 6, 3);
78     /// let t = NaiveTime::from_hms_milli(12, 34, 56, 789);
79     ///
80     /// let dt = NaiveDateTime::new(d, t);
81     /// assert_eq!(dt.date(), d);
82     /// assert_eq!(dt.time(), t);
83     /// ~~~~
84     #[inline]
new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime85     pub fn new(date: NaiveDate, time: NaiveTime) -> NaiveDateTime {
86         NaiveDateTime { date: date, time: time }
87     }
88 
89     /// Makes a new `NaiveDateTime` corresponding to a UTC date and time,
90     /// from the number of non-leap seconds
91     /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp")
92     /// and the number of nanoseconds since the last whole non-leap second.
93     ///
94     /// For a non-naive version of this function see
95     /// [`TimeZone::timestamp`](../offset/trait.TimeZone.html#method.timestamp).
96     ///
97     /// The nanosecond part can exceed 1,000,000,000 in order to represent the
98     /// [leap second](./struct.NaiveTime.html#leap-second-handling). (The true "UNIX
99     /// timestamp" cannot represent a leap second unambiguously.)
100     ///
101     /// Panics on the out-of-range number of seconds and/or invalid nanosecond.
102     ///
103     /// # Example
104     ///
105     /// ~~~~
106     /// use chrono::{NaiveDateTime, NaiveDate};
107     ///
108     /// let dt = NaiveDateTime::from_timestamp(0, 42_000_000);
109     /// assert_eq!(dt, NaiveDate::from_ymd(1970, 1, 1).and_hms_milli(0, 0, 0, 42));
110     ///
111     /// let dt = NaiveDateTime::from_timestamp(1_000_000_000, 0);
112     /// assert_eq!(dt, NaiveDate::from_ymd(2001, 9, 9).and_hms(1, 46, 40));
113     /// ~~~~
114     #[inline]
from_timestamp(secs: i64, nsecs: u32) -> NaiveDateTime115     pub fn from_timestamp(secs: i64, nsecs: u32) -> NaiveDateTime {
116         let datetime = NaiveDateTime::from_timestamp_opt(secs, nsecs);
117         datetime.expect("invalid or out-of-range datetime")
118     }
119 
120     /// Makes a new `NaiveDateTime` corresponding to a UTC date and time,
121     /// from the number of non-leap seconds
122     /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp")
123     /// and the number of nanoseconds since the last whole non-leap second.
124     ///
125     /// The nanosecond part can exceed 1,000,000,000
126     /// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
127     /// (The true "UNIX timestamp" cannot represent a leap second unambiguously.)
128     ///
129     /// Returns `None` on the out-of-range number of seconds and/or invalid nanosecond.
130     ///
131     /// # Example
132     ///
133     /// ~~~~
134     /// use chrono::{NaiveDateTime, NaiveDate};
135     /// use std::i64;
136     ///
137     /// let from_timestamp_opt = NaiveDateTime::from_timestamp_opt;
138     ///
139     /// assert!(from_timestamp_opt(0, 0).is_some());
140     /// assert!(from_timestamp_opt(0, 999_999_999).is_some());
141     /// assert!(from_timestamp_opt(0, 1_500_000_000).is_some()); // leap second
142     /// assert!(from_timestamp_opt(0, 2_000_000_000).is_none());
143     /// assert!(from_timestamp_opt(i64::MAX, 0).is_none());
144     /// ~~~~
145     #[inline]
from_timestamp_opt(secs: i64, nsecs: u32) -> Option<NaiveDateTime>146     pub fn from_timestamp_opt(secs: i64, nsecs: u32) -> Option<NaiveDateTime> {
147         let (days, secs) = div_mod_floor(secs, 86_400);
148         let date = days
149             .to_i32()
150             .and_then(|days| days.checked_add(719_163))
151             .and_then(NaiveDate::from_num_days_from_ce_opt);
152         let time = NaiveTime::from_num_seconds_from_midnight_opt(secs as u32, nsecs);
153         match (date, time) {
154             (Some(date), Some(time)) => Some(NaiveDateTime { date: date, time: time }),
155             (_, _) => None,
156         }
157     }
158 
159     /// Parses a string with the specified format string and returns a new `NaiveDateTime`.
160     /// See the [`format::strftime` module](../format/strftime/index.html)
161     /// on the supported escape sequences.
162     ///
163     /// # Example
164     ///
165     /// ~~~~
166     /// use chrono::{NaiveDateTime, NaiveDate};
167     ///
168     /// let parse_from_str = NaiveDateTime::parse_from_str;
169     ///
170     /// assert_eq!(parse_from_str("2015-09-05 23:56:04", "%Y-%m-%d %H:%M:%S"),
171     ///            Ok(NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4)));
172     /// assert_eq!(parse_from_str("5sep2015pm012345.6789", "%d%b%Y%p%I%M%S%.f"),
173     ///            Ok(NaiveDate::from_ymd(2015, 9, 5).and_hms_micro(13, 23, 45, 678_900)));
174     /// ~~~~
175     ///
176     /// Offset is ignored for the purpose of parsing.
177     ///
178     /// ~~~~
179     /// # use chrono::{NaiveDateTime, NaiveDate};
180     /// # let parse_from_str = NaiveDateTime::parse_from_str;
181     /// assert_eq!(parse_from_str("2014-5-17T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
182     ///            Ok(NaiveDate::from_ymd(2014, 5, 17).and_hms(12, 34, 56)));
183     /// ~~~~
184     ///
185     /// [Leap seconds](./struct.NaiveTime.html#leap-second-handling) are correctly handled by
186     /// treating any time of the form `hh:mm:60` as a leap second.
187     /// (This equally applies to the formatting, so the round trip is possible.)
188     ///
189     /// ~~~~
190     /// # use chrono::{NaiveDateTime, NaiveDate};
191     /// # let parse_from_str = NaiveDateTime::parse_from_str;
192     /// assert_eq!(parse_from_str("2015-07-01 08:59:60.123", "%Y-%m-%d %H:%M:%S%.f"),
193     ///            Ok(NaiveDate::from_ymd(2015, 7, 1).and_hms_milli(8, 59, 59, 1_123)));
194     /// ~~~~
195     ///
196     /// Missing seconds are assumed to be zero,
197     /// but out-of-bound times or insufficient fields are errors otherwise.
198     ///
199     /// ~~~~
200     /// # use chrono::{NaiveDateTime, NaiveDate};
201     /// # let parse_from_str = NaiveDateTime::parse_from_str;
202     /// assert_eq!(parse_from_str("94/9/4 7:15", "%y/%m/%d %H:%M"),
203     ///            Ok(NaiveDate::from_ymd(1994, 9, 4).and_hms(7, 15, 0)));
204     ///
205     /// assert!(parse_from_str("04m33s", "%Mm%Ss").is_err());
206     /// assert!(parse_from_str("94/9/4 12", "%y/%m/%d %H").is_err());
207     /// assert!(parse_from_str("94/9/4 17:60", "%y/%m/%d %H:%M").is_err());
208     /// assert!(parse_from_str("94/9/4 24:00:00", "%y/%m/%d %H:%M:%S").is_err());
209     /// ~~~~
210     ///
211     /// All parsed fields should be consistent to each other, otherwise it's an error.
212     ///
213     /// ~~~~
214     /// # use chrono::NaiveDateTime;
215     /// # let parse_from_str = NaiveDateTime::parse_from_str;
216     /// let fmt = "%Y-%m-%d %H:%M:%S = UNIX timestamp %s";
217     /// assert!(parse_from_str("2001-09-09 01:46:39 = UNIX timestamp 999999999", fmt).is_ok());
218     /// assert!(parse_from_str("1970-01-01 00:00:00 = UNIX timestamp 1", fmt).is_err());
219     /// ~~~~
parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime>220     pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDateTime> {
221         let mut parsed = Parsed::new();
222         parse(&mut parsed, s, StrftimeItems::new(fmt))?;
223         parsed.to_naive_datetime_with_offset(0) // no offset adjustment
224     }
225 
226     /// Retrieves a date component.
227     ///
228     /// # Example
229     ///
230     /// ~~~~
231     /// use chrono::NaiveDate;
232     ///
233     /// let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11);
234     /// assert_eq!(dt.date(), NaiveDate::from_ymd(2016, 7, 8));
235     /// ~~~~
236     #[inline]
date(&self) -> NaiveDate237     pub fn date(&self) -> NaiveDate {
238         self.date
239     }
240 
241     /// Retrieves a time component.
242     ///
243     /// # Example
244     ///
245     /// ~~~~
246     /// use chrono::{NaiveDate, NaiveTime};
247     ///
248     /// let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11);
249     /// assert_eq!(dt.time(), NaiveTime::from_hms(9, 10, 11));
250     /// ~~~~
251     #[inline]
time(&self) -> NaiveTime252     pub fn time(&self) -> NaiveTime {
253         self.time
254     }
255 
256     /// Returns the number of non-leap seconds since the midnight on January 1, 1970.
257     ///
258     /// Note that this does *not* account for the timezone!
259     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
260     ///
261     /// # Example
262     ///
263     /// ~~~~
264     /// use chrono::NaiveDate;
265     ///
266     /// let dt = NaiveDate::from_ymd(1970, 1, 1).and_hms_milli(0, 0, 1, 980);
267     /// assert_eq!(dt.timestamp(), 1);
268     ///
269     /// let dt = NaiveDate::from_ymd(2001, 9, 9).and_hms(1, 46, 40);
270     /// assert_eq!(dt.timestamp(), 1_000_000_000);
271     ///
272     /// let dt = NaiveDate::from_ymd(1969, 12, 31).and_hms(23, 59, 59);
273     /// assert_eq!(dt.timestamp(), -1);
274     ///
275     /// let dt = NaiveDate::from_ymd(-1, 1, 1).and_hms(0, 0, 0);
276     /// assert_eq!(dt.timestamp(), -62198755200);
277     /// ~~~~
278     #[inline]
timestamp(&self) -> i64279     pub fn timestamp(&self) -> i64 {
280         const UNIX_EPOCH_DAY: i64 = 719_163;
281         let gregorian_day = i64::from(self.date.num_days_from_ce());
282         let seconds_from_midnight = i64::from(self.time.num_seconds_from_midnight());
283         (gregorian_day - UNIX_EPOCH_DAY) * 86_400 + seconds_from_midnight
284     }
285 
286     /// Returns the number of non-leap *milliseconds* since midnight on January 1, 1970.
287     ///
288     /// Note that this does *not* account for the timezone!
289     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
290     ///
291     /// Note also that this does reduce the number of years that can be
292     /// represented from ~584 Billion to ~584 Million. (If this is a problem,
293     /// please file an issue to let me know what domain needs millisecond
294     /// precision over billions of years, I'm curious.)
295     ///
296     /// # Example
297     ///
298     /// ~~~~
299     /// use chrono::NaiveDate;
300     ///
301     /// let dt = NaiveDate::from_ymd(1970, 1, 1).and_hms_milli(0, 0, 1, 444);
302     /// assert_eq!(dt.timestamp_millis(), 1_444);
303     ///
304     /// let dt = NaiveDate::from_ymd(2001, 9, 9).and_hms_milli(1, 46, 40, 555);
305     /// assert_eq!(dt.timestamp_millis(), 1_000_000_000_555);
306     ///
307     /// let dt = NaiveDate::from_ymd(1969, 12, 31).and_hms_milli(23, 59, 59, 100);
308     /// assert_eq!(dt.timestamp_millis(), -900);
309     /// ~~~~
310     #[inline]
timestamp_millis(&self) -> i64311     pub fn timestamp_millis(&self) -> i64 {
312         let as_ms = self.timestamp() * 1000;
313         as_ms + i64::from(self.timestamp_subsec_millis())
314     }
315 
316     /// Returns the number of non-leap *nanoseconds* since midnight on January 1, 1970.
317     ///
318     /// Note that this does *not* account for the timezone!
319     /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch.
320     ///
321     /// # Panics
322     ///
323     /// Note also that this does reduce the number of years that can be
324     /// represented from ~584 Billion to ~584 years. The dates that can be
325     /// represented as nanoseconds are between 1677-09-21T00:12:44.0 and
326     /// 2262-04-11T23:47:16.854775804.
327     ///
328     /// (If this is a problem, please file an issue to let me know what domain
329     /// needs nanosecond precision over millennia, I'm curious.)
330     ///
331     /// # Example
332     ///
333     /// ~~~~
334     /// use chrono::{NaiveDate, NaiveDateTime};
335     ///
336     /// let dt = NaiveDate::from_ymd(1970, 1, 1).and_hms_nano(0, 0, 1, 444);
337     /// assert_eq!(dt.timestamp_nanos(), 1_000_000_444);
338     ///
339     /// let dt = NaiveDate::from_ymd(2001, 9, 9).and_hms_nano(1, 46, 40, 555);
340     ///
341     /// const A_BILLION: i64 = 1_000_000_000;
342     /// let nanos = dt.timestamp_nanos();
343     /// assert_eq!(nanos, 1_000_000_000_000_000_555);
344     /// assert_eq!(
345     ///     dt,
346     ///     NaiveDateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32)
347     /// );
348     /// ~~~~
349     #[inline]
timestamp_nanos(&self) -> i64350     pub fn timestamp_nanos(&self) -> i64 {
351         let as_ns = self.timestamp() * 1_000_000_000;
352         as_ns + i64::from(self.timestamp_subsec_nanos())
353     }
354 
355     /// Returns the number of milliseconds since the last whole non-leap second.
356     ///
357     /// The return value ranges from 0 to 999,
358     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999.
359     ///
360     /// # Example
361     ///
362     /// ~~~~
363     /// use chrono::NaiveDate;
364     ///
365     /// let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms_nano(9, 10, 11, 123_456_789);
366     /// assert_eq!(dt.timestamp_subsec_millis(), 123);
367     ///
368     /// let dt = NaiveDate::from_ymd(2015, 7, 1).and_hms_nano(8, 59, 59, 1_234_567_890);
369     /// assert_eq!(dt.timestamp_subsec_millis(), 1_234);
370     /// ~~~~
371     #[inline]
timestamp_subsec_millis(&self) -> u32372     pub fn timestamp_subsec_millis(&self) -> u32 {
373         self.timestamp_subsec_nanos() / 1_000_000
374     }
375 
376     /// Returns the number of microseconds since the last whole non-leap second.
377     ///
378     /// The return value ranges from 0 to 999,999,
379     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999,999.
380     ///
381     /// # Example
382     ///
383     /// ~~~~
384     /// use chrono::NaiveDate;
385     ///
386     /// let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms_nano(9, 10, 11, 123_456_789);
387     /// assert_eq!(dt.timestamp_subsec_micros(), 123_456);
388     ///
389     /// let dt = NaiveDate::from_ymd(2015, 7, 1).and_hms_nano(8, 59, 59, 1_234_567_890);
390     /// assert_eq!(dt.timestamp_subsec_micros(), 1_234_567);
391     /// ~~~~
392     #[inline]
timestamp_subsec_micros(&self) -> u32393     pub fn timestamp_subsec_micros(&self) -> u32 {
394         self.timestamp_subsec_nanos() / 1_000
395     }
396 
397     /// Returns the number of nanoseconds since the last whole non-leap second.
398     ///
399     /// The return value ranges from 0 to 999,999,999,
400     /// or for [leap seconds](./struct.NaiveTime.html#leap-second-handling), to 1,999,999,999.
401     ///
402     /// # Example
403     ///
404     /// ~~~~
405     /// use chrono::NaiveDate;
406     ///
407     /// let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms_nano(9, 10, 11, 123_456_789);
408     /// assert_eq!(dt.timestamp_subsec_nanos(), 123_456_789);
409     ///
410     /// let dt = NaiveDate::from_ymd(2015, 7, 1).and_hms_nano(8, 59, 59, 1_234_567_890);
411     /// assert_eq!(dt.timestamp_subsec_nanos(), 1_234_567_890);
412     /// ~~~~
413     #[inline]
timestamp_subsec_nanos(&self) -> u32414     pub fn timestamp_subsec_nanos(&self) -> u32 {
415         self.time.nanosecond()
416     }
417 
418     /// Adds given `Duration` to the current date and time.
419     ///
420     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
421     /// the addition assumes that **there is no leap second ever**,
422     /// except when the `NaiveDateTime` itself represents a leap second
423     /// in which case the assumption becomes that **there is exactly a single leap second ever**.
424     ///
425     /// Returns `None` when it will result in overflow.
426     ///
427     /// # Example
428     ///
429     /// ~~~~
430     /// # extern crate chrono; fn main() {
431     /// use chrono::{Duration, NaiveDate};
432     ///
433     /// let from_ymd = NaiveDate::from_ymd;
434     ///
435     /// let d = from_ymd(2016, 7, 8);
436     /// let hms = |h, m, s| d.and_hms(h, m, s);
437     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::zero()),
438     ///            Some(hms(3, 5, 7)));
439     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::seconds(1)),
440     ///            Some(hms(3, 5, 8)));
441     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::seconds(-1)),
442     ///            Some(hms(3, 5, 6)));
443     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::seconds(3600 + 60)),
444     ///            Some(hms(4, 6, 7)));
445     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::seconds(86_400)),
446     ///            Some(from_ymd(2016, 7, 9).and_hms(3, 5, 7)));
447     ///
448     /// let hmsm = |h, m, s, milli| d.and_hms_milli(h, m, s, milli);
449     /// assert_eq!(hmsm(3, 5, 7, 980).checked_add_signed(Duration::milliseconds(450)),
450     ///            Some(hmsm(3, 5, 8, 430)));
451     /// # }
452     /// ~~~~
453     ///
454     /// Overflow returns `None`.
455     ///
456     /// ~~~~
457     /// # extern crate chrono; fn main() {
458     /// # use chrono::{Duration, NaiveDate};
459     /// # let hms = |h, m, s| NaiveDate::from_ymd(2016, 7, 8).and_hms(h, m, s);
460     /// assert_eq!(hms(3, 5, 7).checked_add_signed(Duration::days(1_000_000_000)), None);
461     /// # }
462     /// ~~~~
463     ///
464     /// Leap seconds are handled,
465     /// but the addition assumes that it is the only leap second happened.
466     ///
467     /// ~~~~
468     /// # extern crate chrono; fn main() {
469     /// # use chrono::{Duration, NaiveDate};
470     /// # let from_ymd = NaiveDate::from_ymd;
471     /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli(h, m, s, milli);
472     /// let leap = hmsm(3, 5, 59, 1_300);
473     /// assert_eq!(leap.checked_add_signed(Duration::zero()),
474     ///            Some(hmsm(3, 5, 59, 1_300)));
475     /// assert_eq!(leap.checked_add_signed(Duration::milliseconds(-500)),
476     ///            Some(hmsm(3, 5, 59, 800)));
477     /// assert_eq!(leap.checked_add_signed(Duration::milliseconds(500)),
478     ///            Some(hmsm(3, 5, 59, 1_800)));
479     /// assert_eq!(leap.checked_add_signed(Duration::milliseconds(800)),
480     ///            Some(hmsm(3, 6, 0, 100)));
481     /// assert_eq!(leap.checked_add_signed(Duration::seconds(10)),
482     ///            Some(hmsm(3, 6, 9, 300)));
483     /// assert_eq!(leap.checked_add_signed(Duration::seconds(-10)),
484     ///            Some(hmsm(3, 5, 50, 300)));
485     /// assert_eq!(leap.checked_add_signed(Duration::days(1)),
486     ///            Some(from_ymd(2016, 7, 9).and_hms_milli(3, 5, 59, 300)));
487     /// # }
488     /// ~~~~
checked_add_signed(self, rhs: OldDuration) -> Option<NaiveDateTime>489     pub fn checked_add_signed(self, rhs: OldDuration) -> Option<NaiveDateTime> {
490         let (time, rhs) = self.time.overflowing_add_signed(rhs);
491 
492         // early checking to avoid overflow in OldDuration::seconds
493         if rhs <= (-1 << MAX_SECS_BITS) || rhs >= (1 << MAX_SECS_BITS) {
494             return None;
495         }
496 
497         let date = try_opt!(self.date.checked_add_signed(OldDuration::seconds(rhs)));
498         Some(NaiveDateTime { date: date, time: time })
499     }
500 
501     /// Subtracts given `Duration` from the current date and time.
502     ///
503     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
504     /// the subtraction assumes that **there is no leap second ever**,
505     /// except when the `NaiveDateTime` itself represents a leap second
506     /// in which case the assumption becomes that **there is exactly a single leap second ever**.
507     ///
508     /// Returns `None` when it will result in overflow.
509     ///
510     /// # Example
511     ///
512     /// ~~~~
513     /// # extern crate chrono; fn main() {
514     /// use chrono::{Duration, NaiveDate};
515     ///
516     /// let from_ymd = NaiveDate::from_ymd;
517     ///
518     /// let d = from_ymd(2016, 7, 8);
519     /// let hms = |h, m, s| d.and_hms(h, m, s);
520     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::zero()),
521     ///            Some(hms(3, 5, 7)));
522     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::seconds(1)),
523     ///            Some(hms(3, 5, 6)));
524     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::seconds(-1)),
525     ///            Some(hms(3, 5, 8)));
526     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::seconds(3600 + 60)),
527     ///            Some(hms(2, 4, 7)));
528     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::seconds(86_400)),
529     ///            Some(from_ymd(2016, 7, 7).and_hms(3, 5, 7)));
530     ///
531     /// let hmsm = |h, m, s, milli| d.and_hms_milli(h, m, s, milli);
532     /// assert_eq!(hmsm(3, 5, 7, 450).checked_sub_signed(Duration::milliseconds(670)),
533     ///            Some(hmsm(3, 5, 6, 780)));
534     /// # }
535     /// ~~~~
536     ///
537     /// Overflow returns `None`.
538     ///
539     /// ~~~~
540     /// # extern crate chrono; fn main() {
541     /// # use chrono::{Duration, NaiveDate};
542     /// # let hms = |h, m, s| NaiveDate::from_ymd(2016, 7, 8).and_hms(h, m, s);
543     /// assert_eq!(hms(3, 5, 7).checked_sub_signed(Duration::days(1_000_000_000)), None);
544     /// # }
545     /// ~~~~
546     ///
547     /// Leap seconds are handled,
548     /// but the subtraction assumes that it is the only leap second happened.
549     ///
550     /// ~~~~
551     /// # extern crate chrono; fn main() {
552     /// # use chrono::{Duration, NaiveDate};
553     /// # let from_ymd = NaiveDate::from_ymd;
554     /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli(h, m, s, milli);
555     /// let leap = hmsm(3, 5, 59, 1_300);
556     /// assert_eq!(leap.checked_sub_signed(Duration::zero()),
557     ///            Some(hmsm(3, 5, 59, 1_300)));
558     /// assert_eq!(leap.checked_sub_signed(Duration::milliseconds(200)),
559     ///            Some(hmsm(3, 5, 59, 1_100)));
560     /// assert_eq!(leap.checked_sub_signed(Duration::milliseconds(500)),
561     ///            Some(hmsm(3, 5, 59, 800)));
562     /// assert_eq!(leap.checked_sub_signed(Duration::seconds(60)),
563     ///            Some(hmsm(3, 5, 0, 300)));
564     /// assert_eq!(leap.checked_sub_signed(Duration::days(1)),
565     ///            Some(from_ymd(2016, 7, 7).and_hms_milli(3, 6, 0, 300)));
566     /// # }
567     /// ~~~~
checked_sub_signed(self, rhs: OldDuration) -> Option<NaiveDateTime>568     pub fn checked_sub_signed(self, rhs: OldDuration) -> Option<NaiveDateTime> {
569         let (time, rhs) = self.time.overflowing_sub_signed(rhs);
570 
571         // early checking to avoid overflow in OldDuration::seconds
572         if rhs <= (-1 << MAX_SECS_BITS) || rhs >= (1 << MAX_SECS_BITS) {
573             return None;
574         }
575 
576         let date = try_opt!(self.date.checked_sub_signed(OldDuration::seconds(rhs)));
577         Some(NaiveDateTime { date: date, time: time })
578     }
579 
580     /// Subtracts another `NaiveDateTime` from the current date and time.
581     /// This does not overflow or underflow at all.
582     ///
583     /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
584     /// the subtraction assumes that **there is no leap second ever**,
585     /// except when any of the `NaiveDateTime`s themselves represents a leap second
586     /// in which case the assumption becomes that
587     /// **there are exactly one (or two) leap second(s) ever**.
588     ///
589     /// # Example
590     ///
591     /// ~~~~
592     /// # extern crate chrono; fn main() {
593     /// use chrono::{Duration, NaiveDate};
594     ///
595     /// let from_ymd = NaiveDate::from_ymd;
596     ///
597     /// let d = from_ymd(2016, 7, 8);
598     /// assert_eq!(d.and_hms(3, 5, 7).signed_duration_since(d.and_hms(2, 4, 6)),
599     ///            Duration::seconds(3600 + 60 + 1));
600     ///
601     /// // July 8 is 190th day in the year 2016
602     /// let d0 = from_ymd(2016, 1, 1);
603     /// assert_eq!(d.and_hms_milli(0, 7, 6, 500).signed_duration_since(d0.and_hms(0, 0, 0)),
604     ///            Duration::seconds(189 * 86_400 + 7 * 60 + 6) + Duration::milliseconds(500));
605     /// # }
606     /// ~~~~
607     ///
608     /// Leap seconds are handled, but the subtraction assumes that
609     /// there were no other leap seconds happened.
610     ///
611     /// ~~~~
612     /// # extern crate chrono; fn main() {
613     /// # use chrono::{Duration, NaiveDate};
614     /// # let from_ymd = NaiveDate::from_ymd;
615     /// let leap = from_ymd(2015, 6, 30).and_hms_milli(23, 59, 59, 1_500);
616     /// assert_eq!(leap.signed_duration_since(from_ymd(2015, 6, 30).and_hms(23, 0, 0)),
617     ///            Duration::seconds(3600) + Duration::milliseconds(500));
618     /// assert_eq!(from_ymd(2015, 7, 1).and_hms(1, 0, 0).signed_duration_since(leap),
619     ///            Duration::seconds(3600) - Duration::milliseconds(500));
620     /// # }
621     /// ~~~~
signed_duration_since(self, rhs: NaiveDateTime) -> OldDuration622     pub fn signed_duration_since(self, rhs: NaiveDateTime) -> OldDuration {
623         self.date.signed_duration_since(rhs.date) + self.time.signed_duration_since(rhs.time)
624     }
625 
626     /// Formats the combined date and time with the specified formatting items.
627     /// Otherwise it is the same as the ordinary [`format`](#method.format) method.
628     ///
629     /// The `Iterator` of items should be `Clone`able,
630     /// since the resulting `DelayedFormat` value may be formatted multiple times.
631     ///
632     /// # Example
633     ///
634     /// ~~~~
635     /// use chrono::NaiveDate;
636     /// use chrono::format::strftime::StrftimeItems;
637     ///
638     /// let fmt = StrftimeItems::new("%Y-%m-%d %H:%M:%S");
639     /// let dt = NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4);
640     /// assert_eq!(dt.format_with_items(fmt.clone()).to_string(), "2015-09-05 23:56:04");
641     /// assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(),    "2015-09-05 23:56:04");
642     /// ~~~~
643     ///
644     /// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
645     ///
646     /// ~~~~
647     /// # use chrono::NaiveDate;
648     /// # use chrono::format::strftime::StrftimeItems;
649     /// # let fmt = StrftimeItems::new("%Y-%m-%d %H:%M:%S").clone();
650     /// # let dt = NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4);
651     /// assert_eq!(format!("{}", dt.format_with_items(fmt)), "2015-09-05 23:56:04");
652     /// ~~~~
653     #[cfg(any(feature = "alloc", feature = "std", test))]
654     #[inline]
format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I> where I: Iterator<Item = B> + Clone, B: Borrow<Item<'a>>,655     pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
656     where
657         I: Iterator<Item = B> + Clone,
658         B: Borrow<Item<'a>>,
659     {
660         DelayedFormat::new(Some(self.date), Some(self.time), items)
661     }
662 
663     /// Formats the combined date and time with the specified format string.
664     /// See the [`format::strftime` module](../format/strftime/index.html)
665     /// on the supported escape sequences.
666     ///
667     /// This returns a `DelayedFormat`,
668     /// which gets converted to a string only when actual formatting happens.
669     /// You may use the `to_string` method to get a `String`,
670     /// or just feed it into `print!` and other formatting macros.
671     /// (In this way it avoids the redundant memory allocation.)
672     ///
673     /// A wrong format string does *not* issue an error immediately.
674     /// Rather, converting or formatting the `DelayedFormat` fails.
675     /// You are recommended to immediately use `DelayedFormat` for this reason.
676     ///
677     /// # Example
678     ///
679     /// ~~~~
680     /// use chrono::NaiveDate;
681     ///
682     /// let dt = NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4);
683     /// assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2015-09-05 23:56:04");
684     /// assert_eq!(dt.format("around %l %p on %b %-d").to_string(), "around 11 PM on Sep 5");
685     /// ~~~~
686     ///
687     /// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
688     ///
689     /// ~~~~
690     /// # use chrono::NaiveDate;
691     /// # let dt = NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4);
692     /// assert_eq!(format!("{}", dt.format("%Y-%m-%d %H:%M:%S")), "2015-09-05 23:56:04");
693     /// assert_eq!(format!("{}", dt.format("around %l %p on %b %-d")), "around 11 PM on Sep 5");
694     /// ~~~~
695     #[cfg(any(feature = "alloc", feature = "std", test))]
696     #[inline]
format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>>697     pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
698         self.format_with_items(StrftimeItems::new(fmt))
699     }
700 }
701 
702 impl Datelike for NaiveDateTime {
703     /// Returns the year number in the [calendar date](./index.html#calendar-date).
704     ///
705     /// See also the [`NaiveDate::year`](./struct.NaiveDate.html#method.year) method.
706     ///
707     /// # Example
708     ///
709     /// ~~~~
710     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
711     ///
712     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
713     /// assert_eq!(dt.year(), 2015);
714     /// ~~~~
715     #[inline]
year(&self) -> i32716     fn year(&self) -> i32 {
717         self.date.year()
718     }
719 
720     /// Returns the month number starting from 1.
721     ///
722     /// The return value ranges from 1 to 12.
723     ///
724     /// See also the [`NaiveDate::month`](./struct.NaiveDate.html#method.month) method.
725     ///
726     /// # Example
727     ///
728     /// ~~~~
729     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
730     ///
731     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
732     /// assert_eq!(dt.month(), 9);
733     /// ~~~~
734     #[inline]
month(&self) -> u32735     fn month(&self) -> u32 {
736         self.date.month()
737     }
738 
739     /// Returns the month number starting from 0.
740     ///
741     /// The return value ranges from 0 to 11.
742     ///
743     /// See also the [`NaiveDate::month0`](./struct.NaiveDate.html#method.month0) method.
744     ///
745     /// # Example
746     ///
747     /// ~~~~
748     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
749     ///
750     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
751     /// assert_eq!(dt.month0(), 8);
752     /// ~~~~
753     #[inline]
month0(&self) -> u32754     fn month0(&self) -> u32 {
755         self.date.month0()
756     }
757 
758     /// Returns the day of month starting from 1.
759     ///
760     /// The return value ranges from 1 to 31. (The last day of month differs by months.)
761     ///
762     /// See also the [`NaiveDate::day`](./struct.NaiveDate.html#method.day) method.
763     ///
764     /// # Example
765     ///
766     /// ~~~~
767     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
768     ///
769     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
770     /// assert_eq!(dt.day(), 25);
771     /// ~~~~
772     #[inline]
day(&self) -> u32773     fn day(&self) -> u32 {
774         self.date.day()
775     }
776 
777     /// Returns the day of month starting from 0.
778     ///
779     /// The return value ranges from 0 to 30. (The last day of month differs by months.)
780     ///
781     /// See also the [`NaiveDate::day0`](./struct.NaiveDate.html#method.day0) method.
782     ///
783     /// # Example
784     ///
785     /// ~~~~
786     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
787     ///
788     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
789     /// assert_eq!(dt.day0(), 24);
790     /// ~~~~
791     #[inline]
day0(&self) -> u32792     fn day0(&self) -> u32 {
793         self.date.day0()
794     }
795 
796     /// Returns the day of year starting from 1.
797     ///
798     /// The return value ranges from 1 to 366. (The last day of year differs by years.)
799     ///
800     /// See also the [`NaiveDate::ordinal`](./struct.NaiveDate.html#method.ordinal) method.
801     ///
802     /// # Example
803     ///
804     /// ~~~~
805     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
806     ///
807     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
808     /// assert_eq!(dt.ordinal(), 268);
809     /// ~~~~
810     #[inline]
ordinal(&self) -> u32811     fn ordinal(&self) -> u32 {
812         self.date.ordinal()
813     }
814 
815     /// Returns the day of year starting from 0.
816     ///
817     /// The return value ranges from 0 to 365. (The last day of year differs by years.)
818     ///
819     /// See also the [`NaiveDate::ordinal0`](./struct.NaiveDate.html#method.ordinal0) method.
820     ///
821     /// # Example
822     ///
823     /// ~~~~
824     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
825     ///
826     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
827     /// assert_eq!(dt.ordinal0(), 267);
828     /// ~~~~
829     #[inline]
ordinal0(&self) -> u32830     fn ordinal0(&self) -> u32 {
831         self.date.ordinal0()
832     }
833 
834     /// Returns the day of week.
835     ///
836     /// See also the [`NaiveDate::weekday`](./struct.NaiveDate.html#method.weekday) method.
837     ///
838     /// # Example
839     ///
840     /// ~~~~
841     /// use chrono::{NaiveDate, NaiveDateTime, Datelike, Weekday};
842     ///
843     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
844     /// assert_eq!(dt.weekday(), Weekday::Fri);
845     /// ~~~~
846     #[inline]
weekday(&self) -> Weekday847     fn weekday(&self) -> Weekday {
848         self.date.weekday()
849     }
850 
851     #[inline]
iso_week(&self) -> IsoWeek852     fn iso_week(&self) -> IsoWeek {
853         self.date.iso_week()
854     }
855 
856     /// Makes a new `NaiveDateTime` with the year number changed.
857     ///
858     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
859     ///
860     /// See also the
861     /// [`NaiveDate::with_year`](./struct.NaiveDate.html#method.with_year) method.
862     ///
863     /// # Example
864     ///
865     /// ~~~~
866     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
867     ///
868     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).and_hms(12, 34, 56);
869     /// assert_eq!(dt.with_year(2016), Some(NaiveDate::from_ymd(2016, 9, 25).and_hms(12, 34, 56)));
870     /// assert_eq!(dt.with_year(-308), Some(NaiveDate::from_ymd(-308, 9, 25).and_hms(12, 34, 56)));
871     /// ~~~~
872     #[inline]
with_year(&self, year: i32) -> Option<NaiveDateTime>873     fn with_year(&self, year: i32) -> Option<NaiveDateTime> {
874         self.date.with_year(year).map(|d| NaiveDateTime { date: d, ..*self })
875     }
876 
877     /// Makes a new `NaiveDateTime` with the month number (starting from 1) changed.
878     ///
879     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
880     ///
881     /// See also the
882     /// [`NaiveDate::with_month`](./struct.NaiveDate.html#method.with_month) method.
883     ///
884     /// # Example
885     ///
886     /// ~~~~
887     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
888     ///
889     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 30).and_hms(12, 34, 56);
890     /// assert_eq!(dt.with_month(10), Some(NaiveDate::from_ymd(2015, 10, 30).and_hms(12, 34, 56)));
891     /// assert_eq!(dt.with_month(13), None); // no month 13
892     /// assert_eq!(dt.with_month(2), None); // no February 30
893     /// ~~~~
894     #[inline]
with_month(&self, month: u32) -> Option<NaiveDateTime>895     fn with_month(&self, month: u32) -> Option<NaiveDateTime> {
896         self.date.with_month(month).map(|d| NaiveDateTime { date: d, ..*self })
897     }
898 
899     /// Makes a new `NaiveDateTime` with the month number (starting from 0) changed.
900     ///
901     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
902     ///
903     /// See also the
904     /// [`NaiveDate::with_month0`](./struct.NaiveDate.html#method.with_month0) method.
905     ///
906     /// # Example
907     ///
908     /// ~~~~
909     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
910     ///
911     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 30).and_hms(12, 34, 56);
912     /// assert_eq!(dt.with_month0(9), Some(NaiveDate::from_ymd(2015, 10, 30).and_hms(12, 34, 56)));
913     /// assert_eq!(dt.with_month0(12), None); // no month 13
914     /// assert_eq!(dt.with_month0(1), None); // no February 30
915     /// ~~~~
916     #[inline]
with_month0(&self, month0: u32) -> Option<NaiveDateTime>917     fn with_month0(&self, month0: u32) -> Option<NaiveDateTime> {
918         self.date.with_month0(month0).map(|d| NaiveDateTime { date: d, ..*self })
919     }
920 
921     /// Makes a new `NaiveDateTime` with the day of month (starting from 1) changed.
922     ///
923     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
924     ///
925     /// See also the
926     /// [`NaiveDate::with_day`](./struct.NaiveDate.html#method.with_day) method.
927     ///
928     /// # Example
929     ///
930     /// ~~~~
931     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
932     ///
933     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms(12, 34, 56);
934     /// assert_eq!(dt.with_day(30), Some(NaiveDate::from_ymd(2015, 9, 30).and_hms(12, 34, 56)));
935     /// assert_eq!(dt.with_day(31), None); // no September 31
936     /// ~~~~
937     #[inline]
with_day(&self, day: u32) -> Option<NaiveDateTime>938     fn with_day(&self, day: u32) -> Option<NaiveDateTime> {
939         self.date.with_day(day).map(|d| NaiveDateTime { date: d, ..*self })
940     }
941 
942     /// Makes a new `NaiveDateTime` with the day of month (starting from 0) changed.
943     ///
944     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
945     ///
946     /// See also the
947     /// [`NaiveDate::with_day0`](./struct.NaiveDate.html#method.with_day0) method.
948     ///
949     /// # Example
950     ///
951     /// ~~~~
952     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
953     ///
954     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms(12, 34, 56);
955     /// assert_eq!(dt.with_day0(29), Some(NaiveDate::from_ymd(2015, 9, 30).and_hms(12, 34, 56)));
956     /// assert_eq!(dt.with_day0(30), None); // no September 31
957     /// ~~~~
958     #[inline]
with_day0(&self, day0: u32) -> Option<NaiveDateTime>959     fn with_day0(&self, day0: u32) -> Option<NaiveDateTime> {
960         self.date.with_day0(day0).map(|d| NaiveDateTime { date: d, ..*self })
961     }
962 
963     /// Makes a new `NaiveDateTime` with the day of year (starting from 1) changed.
964     ///
965     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
966     ///
967     /// See also the
968     /// [`NaiveDate::with_ordinal`](./struct.NaiveDate.html#method.with_ordinal) method.
969     ///
970     /// # Example
971     ///
972     /// ~~~~
973     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
974     ///
975     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms(12, 34, 56);
976     /// assert_eq!(dt.with_ordinal(60),
977     ///            Some(NaiveDate::from_ymd(2015, 3, 1).and_hms(12, 34, 56)));
978     /// assert_eq!(dt.with_ordinal(366), None); // 2015 had only 365 days
979     ///
980     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2016, 9, 8).and_hms(12, 34, 56);
981     /// assert_eq!(dt.with_ordinal(60),
982     ///            Some(NaiveDate::from_ymd(2016, 2, 29).and_hms(12, 34, 56)));
983     /// assert_eq!(dt.with_ordinal(366),
984     ///            Some(NaiveDate::from_ymd(2016, 12, 31).and_hms(12, 34, 56)));
985     /// ~~~~
986     #[inline]
with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime>987     fn with_ordinal(&self, ordinal: u32) -> Option<NaiveDateTime> {
988         self.date.with_ordinal(ordinal).map(|d| NaiveDateTime { date: d, ..*self })
989     }
990 
991     /// Makes a new `NaiveDateTime` with the day of year (starting from 0) changed.
992     ///
993     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
994     ///
995     /// See also the
996     /// [`NaiveDate::with_ordinal0`](./struct.NaiveDate.html#method.with_ordinal0) method.
997     ///
998     /// # Example
999     ///
1000     /// ~~~~
1001     /// use chrono::{NaiveDate, NaiveDateTime, Datelike};
1002     ///
1003     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms(12, 34, 56);
1004     /// assert_eq!(dt.with_ordinal0(59),
1005     ///            Some(NaiveDate::from_ymd(2015, 3, 1).and_hms(12, 34, 56)));
1006     /// assert_eq!(dt.with_ordinal0(365), None); // 2015 had only 365 days
1007     ///
1008     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2016, 9, 8).and_hms(12, 34, 56);
1009     /// assert_eq!(dt.with_ordinal0(59),
1010     ///            Some(NaiveDate::from_ymd(2016, 2, 29).and_hms(12, 34, 56)));
1011     /// assert_eq!(dt.with_ordinal0(365),
1012     ///            Some(NaiveDate::from_ymd(2016, 12, 31).and_hms(12, 34, 56)));
1013     /// ~~~~
1014     #[inline]
with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime>1015     fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDateTime> {
1016         self.date.with_ordinal0(ordinal0).map(|d| NaiveDateTime { date: d, ..*self })
1017     }
1018 }
1019 
1020 impl Timelike for NaiveDateTime {
1021     /// Returns the hour number from 0 to 23.
1022     ///
1023     /// See also the [`NaiveTime::hour`](./struct.NaiveTime.html#method.hour) method.
1024     ///
1025     /// # Example
1026     ///
1027     /// ~~~~
1028     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1029     ///
1030     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1031     /// assert_eq!(dt.hour(), 12);
1032     /// ~~~~
1033     #[inline]
hour(&self) -> u321034     fn hour(&self) -> u32 {
1035         self.time.hour()
1036     }
1037 
1038     /// Returns the minute number from 0 to 59.
1039     ///
1040     /// See also the [`NaiveTime::minute`](./struct.NaiveTime.html#method.minute) method.
1041     ///
1042     /// # Example
1043     ///
1044     /// ~~~~
1045     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1046     ///
1047     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1048     /// assert_eq!(dt.minute(), 34);
1049     /// ~~~~
1050     #[inline]
minute(&self) -> u321051     fn minute(&self) -> u32 {
1052         self.time.minute()
1053     }
1054 
1055     /// Returns the second number from 0 to 59.
1056     ///
1057     /// See also the [`NaiveTime::second`](./struct.NaiveTime.html#method.second) method.
1058     ///
1059     /// # Example
1060     ///
1061     /// ~~~~
1062     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1063     ///
1064     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1065     /// assert_eq!(dt.second(), 56);
1066     /// ~~~~
1067     #[inline]
second(&self) -> u321068     fn second(&self) -> u32 {
1069         self.time.second()
1070     }
1071 
1072     /// Returns the number of nanoseconds since the whole non-leap second.
1073     /// The range from 1,000,000,000 to 1,999,999,999 represents
1074     /// the [leap second](./struct.NaiveTime.html#leap-second-handling).
1075     ///
1076     /// See also the
1077     /// [`NaiveTime::nanosecond`](./struct.NaiveTime.html#method.nanosecond) method.
1078     ///
1079     /// # Example
1080     ///
1081     /// ~~~~
1082     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1083     ///
1084     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1085     /// assert_eq!(dt.nanosecond(), 789_000_000);
1086     /// ~~~~
1087     #[inline]
nanosecond(&self) -> u321088     fn nanosecond(&self) -> u32 {
1089         self.time.nanosecond()
1090     }
1091 
1092     /// Makes a new `NaiveDateTime` with the hour number changed.
1093     ///
1094     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1095     ///
1096     /// See also the
1097     /// [`NaiveTime::with_hour`](./struct.NaiveTime.html#method.with_hour) method.
1098     ///
1099     /// # Example
1100     ///
1101     /// ~~~~
1102     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1103     ///
1104     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1105     /// assert_eq!(dt.with_hour(7),
1106     ///            Some(NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(7, 34, 56, 789)));
1107     /// assert_eq!(dt.with_hour(24), None);
1108     /// ~~~~
1109     #[inline]
with_hour(&self, hour: u32) -> Option<NaiveDateTime>1110     fn with_hour(&self, hour: u32) -> Option<NaiveDateTime> {
1111         self.time.with_hour(hour).map(|t| NaiveDateTime { time: t, ..*self })
1112     }
1113 
1114     /// Makes a new `NaiveDateTime` with the minute number changed.
1115     ///
1116     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1117     ///
1118     /// See also the
1119     /// [`NaiveTime::with_minute`](./struct.NaiveTime.html#method.with_minute) method.
1120     ///
1121     /// # Example
1122     ///
1123     /// ~~~~
1124     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1125     ///
1126     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1127     /// assert_eq!(dt.with_minute(45),
1128     ///            Some(NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 45, 56, 789)));
1129     /// assert_eq!(dt.with_minute(60), None);
1130     /// ~~~~
1131     #[inline]
with_minute(&self, min: u32) -> Option<NaiveDateTime>1132     fn with_minute(&self, min: u32) -> Option<NaiveDateTime> {
1133         self.time.with_minute(min).map(|t| NaiveDateTime { time: t, ..*self })
1134     }
1135 
1136     /// Makes a new `NaiveDateTime` with the second number changed.
1137     ///
1138     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1139     /// As with the [`second`](#method.second) method,
1140     /// the input range is restricted to 0 through 59.
1141     ///
1142     /// See also the
1143     /// [`NaiveTime::with_second`](./struct.NaiveTime.html#method.with_second) method.
1144     ///
1145     /// # Example
1146     ///
1147     /// ~~~~
1148     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1149     ///
1150     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1151     /// assert_eq!(dt.with_second(17),
1152     ///            Some(NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 17, 789)));
1153     /// assert_eq!(dt.with_second(60), None);
1154     /// ~~~~
1155     #[inline]
with_second(&self, sec: u32) -> Option<NaiveDateTime>1156     fn with_second(&self, sec: u32) -> Option<NaiveDateTime> {
1157         self.time.with_second(sec).map(|t| NaiveDateTime { time: t, ..*self })
1158     }
1159 
1160     /// Makes a new `NaiveDateTime` with nanoseconds since the whole non-leap second changed.
1161     ///
1162     /// Returns `None` when the resulting `NaiveDateTime` would be invalid.
1163     /// As with the [`nanosecond`](#method.nanosecond) method,
1164     /// the input range can exceed 1,000,000,000 for leap seconds.
1165     ///
1166     /// See also the
1167     /// [`NaiveTime::with_nanosecond`](./struct.NaiveTime.html#method.with_nanosecond)
1168     /// method.
1169     ///
1170     /// # Example
1171     ///
1172     /// ~~~~
1173     /// use chrono::{NaiveDate, NaiveDateTime, Timelike};
1174     ///
1175     /// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 8).and_hms_milli(12, 34, 56, 789);
1176     /// assert_eq!(dt.with_nanosecond(333_333_333),
1177     ///            Some(NaiveDate::from_ymd(2015, 9, 8).and_hms_nano(12, 34, 56, 333_333_333)));
1178     /// assert_eq!(dt.with_nanosecond(1_333_333_333), // leap second
1179     ///            Some(NaiveDate::from_ymd(2015, 9, 8).and_hms_nano(12, 34, 56, 1_333_333_333)));
1180     /// assert_eq!(dt.with_nanosecond(2_000_000_000), None);
1181     /// ~~~~
1182     #[inline]
with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime>1183     fn with_nanosecond(&self, nano: u32) -> Option<NaiveDateTime> {
1184         self.time.with_nanosecond(nano).map(|t| NaiveDateTime { time: t, ..*self })
1185     }
1186 }
1187 
1188 /// `NaiveDateTime` can be used as a key to the hash maps (in principle).
1189 ///
1190 /// Practically this also takes account of fractional seconds, so it is not recommended.
1191 /// (For the obvious reason this also distinguishes leap seconds from non-leap seconds.)
1192 impl hash::Hash for NaiveDateTime {
hash<H: hash::Hasher>(&self, state: &mut H)1193     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1194         self.date.hash(state);
1195         self.time.hash(state);
1196     }
1197 }
1198 
1199 /// An addition of `Duration` to `NaiveDateTime` yields another `NaiveDateTime`.
1200 ///
1201 /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
1202 /// the addition assumes that **there is no leap second ever**,
1203 /// except when the `NaiveDateTime` itself represents a leap second
1204 /// in which case the assumption becomes that **there is exactly a single leap second ever**.
1205 ///
1206 /// Panics on underflow or overflow.
1207 /// Use [`NaiveDateTime::checked_add_signed`](#method.checked_add_signed) to detect that.
1208 ///
1209 /// # Example
1210 ///
1211 /// ~~~~
1212 /// # extern crate chrono; fn main() {
1213 /// use chrono::{Duration, NaiveDate};
1214 ///
1215 /// let from_ymd = NaiveDate::from_ymd;
1216 ///
1217 /// let d = from_ymd(2016, 7, 8);
1218 /// let hms = |h, m, s| d.and_hms(h, m, s);
1219 /// assert_eq!(hms(3, 5, 7) + Duration::zero(),             hms(3, 5, 7));
1220 /// assert_eq!(hms(3, 5, 7) + Duration::seconds(1),         hms(3, 5, 8));
1221 /// assert_eq!(hms(3, 5, 7) + Duration::seconds(-1),        hms(3, 5, 6));
1222 /// assert_eq!(hms(3, 5, 7) + Duration::seconds(3600 + 60), hms(4, 6, 7));
1223 /// assert_eq!(hms(3, 5, 7) + Duration::seconds(86_400),
1224 ///            from_ymd(2016, 7, 9).and_hms(3, 5, 7));
1225 /// assert_eq!(hms(3, 5, 7) + Duration::days(365),
1226 ///            from_ymd(2017, 7, 8).and_hms(3, 5, 7));
1227 ///
1228 /// let hmsm = |h, m, s, milli| d.and_hms_milli(h, m, s, milli);
1229 /// assert_eq!(hmsm(3, 5, 7, 980) + Duration::milliseconds(450), hmsm(3, 5, 8, 430));
1230 /// # }
1231 /// ~~~~
1232 ///
1233 /// Leap seconds are handled,
1234 /// but the addition assumes that it is the only leap second happened.
1235 ///
1236 /// ~~~~
1237 /// # extern crate chrono; fn main() {
1238 /// # use chrono::{Duration, NaiveDate};
1239 /// # let from_ymd = NaiveDate::from_ymd;
1240 /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli(h, m, s, milli);
1241 /// let leap = hmsm(3, 5, 59, 1_300);
1242 /// assert_eq!(leap + Duration::zero(),             hmsm(3, 5, 59, 1_300));
1243 /// assert_eq!(leap + Duration::milliseconds(-500), hmsm(3, 5, 59, 800));
1244 /// assert_eq!(leap + Duration::milliseconds(500),  hmsm(3, 5, 59, 1_800));
1245 /// assert_eq!(leap + Duration::milliseconds(800),  hmsm(3, 6, 0, 100));
1246 /// assert_eq!(leap + Duration::seconds(10),        hmsm(3, 6, 9, 300));
1247 /// assert_eq!(leap + Duration::seconds(-10),       hmsm(3, 5, 50, 300));
1248 /// assert_eq!(leap + Duration::days(1),
1249 ///            from_ymd(2016, 7, 9).and_hms_milli(3, 5, 59, 300));
1250 /// # }
1251 /// ~~~~
1252 impl Add<OldDuration> for NaiveDateTime {
1253     type Output = NaiveDateTime;
1254 
1255     #[inline]
add(self, rhs: OldDuration) -> NaiveDateTime1256     fn add(self, rhs: OldDuration) -> NaiveDateTime {
1257         self.checked_add_signed(rhs).expect("`NaiveDateTime + Duration` overflowed")
1258     }
1259 }
1260 
1261 impl AddAssign<OldDuration> for NaiveDateTime {
1262     #[inline]
add_assign(&mut self, rhs: OldDuration)1263     fn add_assign(&mut self, rhs: OldDuration) {
1264         *self = self.add(rhs);
1265     }
1266 }
1267 
1268 /// A subtraction of `Duration` from `NaiveDateTime` yields another `NaiveDateTime`.
1269 /// It is the same as the addition with a negated `Duration`.
1270 ///
1271 /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
1272 /// the addition assumes that **there is no leap second ever**,
1273 /// except when the `NaiveDateTime` itself represents a leap second
1274 /// in which case the assumption becomes that **there is exactly a single leap second ever**.
1275 ///
1276 /// Panics on underflow or overflow.
1277 /// Use [`NaiveDateTime::checked_sub_signed`](#method.checked_sub_signed) to detect that.
1278 ///
1279 /// # Example
1280 ///
1281 /// ~~~~
1282 /// # extern crate chrono; fn main() {
1283 /// use chrono::{Duration, NaiveDate};
1284 ///
1285 /// let from_ymd = NaiveDate::from_ymd;
1286 ///
1287 /// let d = from_ymd(2016, 7, 8);
1288 /// let hms = |h, m, s| d.and_hms(h, m, s);
1289 /// assert_eq!(hms(3, 5, 7) - Duration::zero(),             hms(3, 5, 7));
1290 /// assert_eq!(hms(3, 5, 7) - Duration::seconds(1),         hms(3, 5, 6));
1291 /// assert_eq!(hms(3, 5, 7) - Duration::seconds(-1),        hms(3, 5, 8));
1292 /// assert_eq!(hms(3, 5, 7) - Duration::seconds(3600 + 60), hms(2, 4, 7));
1293 /// assert_eq!(hms(3, 5, 7) - Duration::seconds(86_400),
1294 ///            from_ymd(2016, 7, 7).and_hms(3, 5, 7));
1295 /// assert_eq!(hms(3, 5, 7) - Duration::days(365),
1296 ///            from_ymd(2015, 7, 9).and_hms(3, 5, 7));
1297 ///
1298 /// let hmsm = |h, m, s, milli| d.and_hms_milli(h, m, s, milli);
1299 /// assert_eq!(hmsm(3, 5, 7, 450) - Duration::milliseconds(670), hmsm(3, 5, 6, 780));
1300 /// # }
1301 /// ~~~~
1302 ///
1303 /// Leap seconds are handled,
1304 /// but the subtraction assumes that it is the only leap second happened.
1305 ///
1306 /// ~~~~
1307 /// # extern crate chrono; fn main() {
1308 /// # use chrono::{Duration, NaiveDate};
1309 /// # let from_ymd = NaiveDate::from_ymd;
1310 /// # let hmsm = |h, m, s, milli| from_ymd(2016, 7, 8).and_hms_milli(h, m, s, milli);
1311 /// let leap = hmsm(3, 5, 59, 1_300);
1312 /// assert_eq!(leap - Duration::zero(),            hmsm(3, 5, 59, 1_300));
1313 /// assert_eq!(leap - Duration::milliseconds(200), hmsm(3, 5, 59, 1_100));
1314 /// assert_eq!(leap - Duration::milliseconds(500), hmsm(3, 5, 59, 800));
1315 /// assert_eq!(leap - Duration::seconds(60),       hmsm(3, 5, 0, 300));
1316 /// assert_eq!(leap - Duration::days(1),
1317 ///            from_ymd(2016, 7, 7).and_hms_milli(3, 6, 0, 300));
1318 /// # }
1319 /// ~~~~
1320 impl Sub<OldDuration> for NaiveDateTime {
1321     type Output = NaiveDateTime;
1322 
1323     #[inline]
sub(self, rhs: OldDuration) -> NaiveDateTime1324     fn sub(self, rhs: OldDuration) -> NaiveDateTime {
1325         self.checked_sub_signed(rhs).expect("`NaiveDateTime - Duration` overflowed")
1326     }
1327 }
1328 
1329 impl SubAssign<OldDuration> for NaiveDateTime {
1330     #[inline]
sub_assign(&mut self, rhs: OldDuration)1331     fn sub_assign(&mut self, rhs: OldDuration) {
1332         *self = self.sub(rhs);
1333     }
1334 }
1335 
1336 /// Subtracts another `NaiveDateTime` from the current date and time.
1337 /// This does not overflow or underflow at all.
1338 ///
1339 /// As a part of Chrono's [leap second handling](./struct.NaiveTime.html#leap-second-handling),
1340 /// the subtraction assumes that **there is no leap second ever**,
1341 /// except when any of the `NaiveDateTime`s themselves represents a leap second
1342 /// in which case the assumption becomes that
1343 /// **there are exactly one (or two) leap second(s) ever**.
1344 ///
1345 /// The implementation is a wrapper around
1346 /// [`NaiveDateTime::signed_duration_since`](#method.signed_duration_since).
1347 ///
1348 /// # Example
1349 ///
1350 /// ~~~~
1351 /// # extern crate chrono; fn main() {
1352 /// use chrono::{Duration, NaiveDate};
1353 ///
1354 /// let from_ymd = NaiveDate::from_ymd;
1355 ///
1356 /// let d = from_ymd(2016, 7, 8);
1357 /// assert_eq!(d.and_hms(3, 5, 7) - d.and_hms(2, 4, 6), Duration::seconds(3600 + 60 + 1));
1358 ///
1359 /// // July 8 is 190th day in the year 2016
1360 /// let d0 = from_ymd(2016, 1, 1);
1361 /// assert_eq!(d.and_hms_milli(0, 7, 6, 500) - d0.and_hms(0, 0, 0),
1362 ///            Duration::seconds(189 * 86_400 + 7 * 60 + 6) + Duration::milliseconds(500));
1363 /// # }
1364 /// ~~~~
1365 ///
1366 /// Leap seconds are handled, but the subtraction assumes that
1367 /// there were no other leap seconds happened.
1368 ///
1369 /// ~~~~
1370 /// # extern crate chrono; fn main() {
1371 /// # use chrono::{Duration, NaiveDate};
1372 /// # let from_ymd = NaiveDate::from_ymd;
1373 /// let leap = from_ymd(2015, 6, 30).and_hms_milli(23, 59, 59, 1_500);
1374 /// assert_eq!(leap - from_ymd(2015, 6, 30).and_hms(23, 0, 0),
1375 ///            Duration::seconds(3600) + Duration::milliseconds(500));
1376 /// assert_eq!(from_ymd(2015, 7, 1).and_hms(1, 0, 0) - leap,
1377 ///            Duration::seconds(3600) - Duration::milliseconds(500));
1378 /// # }
1379 /// ~~~~
1380 impl Sub<NaiveDateTime> for NaiveDateTime {
1381     type Output = OldDuration;
1382 
1383     #[inline]
sub(self, rhs: NaiveDateTime) -> OldDuration1384     fn sub(self, rhs: NaiveDateTime) -> OldDuration {
1385         self.signed_duration_since(rhs)
1386     }
1387 }
1388 
1389 /// The `Debug` output of the naive date and time `dt` is the same as
1390 /// [`dt.format("%Y-%m-%dT%H:%M:%S%.f")`](../format/strftime/index.html).
1391 ///
1392 /// The string printed can be readily parsed via the `parse` method on `str`.
1393 ///
1394 /// It should be noted that, for leap seconds not on the minute boundary,
1395 /// it may print a representation not distinguishable from non-leap seconds.
1396 /// This doesn't matter in practice, since such leap seconds never happened.
1397 /// (By the time of the first leap second on 1972-06-30,
1398 /// every time zone offset around the world has standardized to the 5-minute alignment.)
1399 ///
1400 /// # Example
1401 ///
1402 /// ~~~~
1403 /// use chrono::NaiveDate;
1404 ///
1405 /// let dt = NaiveDate::from_ymd(2016, 11, 15).and_hms(7, 39, 24);
1406 /// assert_eq!(format!("{:?}", dt), "2016-11-15T07:39:24");
1407 /// ~~~~
1408 ///
1409 /// Leap seconds may also be used.
1410 ///
1411 /// ~~~~
1412 /// # use chrono::NaiveDate;
1413 /// let dt = NaiveDate::from_ymd(2015, 6, 30).and_hms_milli(23, 59, 59, 1_500);
1414 /// assert_eq!(format!("{:?}", dt), "2015-06-30T23:59:60.500");
1415 /// ~~~~
1416 impl fmt::Debug for NaiveDateTime {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1417     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1418         write!(f, "{:?}T{:?}", self.date, self.time)
1419     }
1420 }
1421 
1422 /// The `Display` output of the naive date and time `dt` is the same as
1423 /// [`dt.format("%Y-%m-%d %H:%M:%S%.f")`](../format/strftime/index.html).
1424 ///
1425 /// It should be noted that, for leap seconds not on the minute boundary,
1426 /// it may print a representation not distinguishable from non-leap seconds.
1427 /// This doesn't matter in practice, since such leap seconds never happened.
1428 /// (By the time of the first leap second on 1972-06-30,
1429 /// every time zone offset around the world has standardized to the 5-minute alignment.)
1430 ///
1431 /// # Example
1432 ///
1433 /// ~~~~
1434 /// use chrono::NaiveDate;
1435 ///
1436 /// let dt = NaiveDate::from_ymd(2016, 11, 15).and_hms(7, 39, 24);
1437 /// assert_eq!(format!("{}", dt), "2016-11-15 07:39:24");
1438 /// ~~~~
1439 ///
1440 /// Leap seconds may also be used.
1441 ///
1442 /// ~~~~
1443 /// # use chrono::NaiveDate;
1444 /// let dt = NaiveDate::from_ymd(2015, 6, 30).and_hms_milli(23, 59, 59, 1_500);
1445 /// assert_eq!(format!("{}", dt), "2015-06-30 23:59:60.500");
1446 /// ~~~~
1447 impl fmt::Display for NaiveDateTime {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1448     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1449         write!(f, "{} {}", self.date, self.time)
1450     }
1451 }
1452 
1453 /// Parsing a `str` into a `NaiveDateTime` uses the same format,
1454 /// [`%Y-%m-%dT%H:%M:%S%.f`](../format/strftime/index.html), as in `Debug`.
1455 ///
1456 /// # Example
1457 ///
1458 /// ~~~~
1459 /// use chrono::{NaiveDateTime, NaiveDate};
1460 ///
1461 /// let dt = NaiveDate::from_ymd(2015, 9, 18).and_hms(23, 56, 4);
1462 /// assert_eq!("2015-09-18T23:56:04".parse::<NaiveDateTime>(), Ok(dt));
1463 ///
1464 /// let dt = NaiveDate::from_ymd(12345, 6, 7).and_hms_milli(7, 59, 59, 1_500); // leap second
1465 /// assert_eq!("+12345-6-7T7:59:60.5".parse::<NaiveDateTime>(), Ok(dt));
1466 ///
1467 /// assert!("foo".parse::<NaiveDateTime>().is_err());
1468 /// ~~~~
1469 impl str::FromStr for NaiveDateTime {
1470     type Err = ParseError;
1471 
from_str(s: &str) -> ParseResult<NaiveDateTime>1472     fn from_str(s: &str) -> ParseResult<NaiveDateTime> {
1473         const ITEMS: &'static [Item<'static>] = &[
1474             Item::Numeric(Numeric::Year, Pad::Zero),
1475             Item::Space(""),
1476             Item::Literal("-"),
1477             Item::Numeric(Numeric::Month, Pad::Zero),
1478             Item::Space(""),
1479             Item::Literal("-"),
1480             Item::Numeric(Numeric::Day, Pad::Zero),
1481             Item::Space(""),
1482             Item::Literal("T"), // XXX shouldn't this be case-insensitive?
1483             Item::Numeric(Numeric::Hour, Pad::Zero),
1484             Item::Space(""),
1485             Item::Literal(":"),
1486             Item::Numeric(Numeric::Minute, Pad::Zero),
1487             Item::Space(""),
1488             Item::Literal(":"),
1489             Item::Numeric(Numeric::Second, Pad::Zero),
1490             Item::Fixed(Fixed::Nanosecond),
1491             Item::Space(""),
1492         ];
1493 
1494         let mut parsed = Parsed::new();
1495         parse(&mut parsed, s, ITEMS.iter())?;
1496         parsed.to_naive_datetime_with_offset(0)
1497     }
1498 }
1499 
1500 #[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,1501 fn test_encodable_json<F, E>(to_string: F)
1502 where
1503     F: Fn(&NaiveDateTime) -> Result<String, E>,
1504     E: ::std::fmt::Debug,
1505 {
1506     use naive::{MAX_DATE, MIN_DATE};
1507 
1508     assert_eq!(
1509         to_string(&NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90)).ok(),
1510         Some(r#""2016-07-08T09:10:48.090""#.into())
1511     );
1512     assert_eq!(
1513         to_string(&NaiveDate::from_ymd(2014, 7, 24).and_hms(12, 34, 6)).ok(),
1514         Some(r#""2014-07-24T12:34:06""#.into())
1515     );
1516     assert_eq!(
1517         to_string(&NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000)).ok(),
1518         Some(r#""0000-01-01T00:00:60""#.into())
1519     );
1520     assert_eq!(
1521         to_string(&NaiveDate::from_ymd(-1, 12, 31).and_hms_nano(23, 59, 59, 7)).ok(),
1522         Some(r#""-0001-12-31T23:59:59.000000007""#.into())
1523     );
1524     assert_eq!(
1525         to_string(&MIN_DATE.and_hms(0, 0, 0)).ok(),
1526         Some(r#""-262144-01-01T00:00:00""#.into())
1527     );
1528     assert_eq!(
1529         to_string(&MAX_DATE.and_hms_nano(23, 59, 59, 1_999_999_999)).ok(),
1530         Some(r#""+262143-12-31T23:59:60.999999999""#.into())
1531     );
1532 }
1533 
1534 #[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,1535 fn test_decodable_json<F, E>(from_str: F)
1536 where
1537     F: Fn(&str) -> Result<NaiveDateTime, E>,
1538     E: ::std::fmt::Debug,
1539 {
1540     use naive::{MAX_DATE, MIN_DATE};
1541 
1542     assert_eq!(
1543         from_str(r#""2016-07-08T09:10:48.090""#).ok(),
1544         Some(NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90))
1545     );
1546     assert_eq!(
1547         from_str(r#""2016-7-8T9:10:48.09""#).ok(),
1548         Some(NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90))
1549     );
1550     assert_eq!(
1551         from_str(r#""2014-07-24T12:34:06""#).ok(),
1552         Some(NaiveDate::from_ymd(2014, 7, 24).and_hms(12, 34, 6))
1553     );
1554     assert_eq!(
1555         from_str(r#""0000-01-01T00:00:60""#).ok(),
1556         Some(NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000))
1557     );
1558     assert_eq!(
1559         from_str(r#""0-1-1T0:0:60""#).ok(),
1560         Some(NaiveDate::from_ymd(0, 1, 1).and_hms_milli(0, 0, 59, 1_000))
1561     );
1562     assert_eq!(
1563         from_str(r#""-0001-12-31T23:59:59.000000007""#).ok(),
1564         Some(NaiveDate::from_ymd(-1, 12, 31).and_hms_nano(23, 59, 59, 7))
1565     );
1566     assert_eq!(from_str(r#""-262144-01-01T00:00:00""#).ok(), Some(MIN_DATE.and_hms(0, 0, 0)));
1567     assert_eq!(
1568         from_str(r#""+262143-12-31T23:59:60.999999999""#).ok(),
1569         Some(MAX_DATE.and_hms_nano(23, 59, 59, 1_999_999_999))
1570     );
1571     assert_eq!(
1572         from_str(r#""+262143-12-31T23:59:60.9999999999997""#).ok(), // excess digits are ignored
1573         Some(MAX_DATE.and_hms_nano(23, 59, 59, 1_999_999_999))
1574     );
1575 
1576     // bad formats
1577     assert!(from_str(r#""""#).is_err());
1578     assert!(from_str(r#""2016-07-08""#).is_err());
1579     assert!(from_str(r#""09:10:48.090""#).is_err());
1580     assert!(from_str(r#""20160708T091048.090""#).is_err());
1581     assert!(from_str(r#""2000-00-00T00:00:00""#).is_err());
1582     assert!(from_str(r#""2000-02-30T00:00:00""#).is_err());
1583     assert!(from_str(r#""2001-02-29T00:00:00""#).is_err());
1584     assert!(from_str(r#""2002-02-28T24:00:00""#).is_err());
1585     assert!(from_str(r#""2002-02-28T23:60:00""#).is_err());
1586     assert!(from_str(r#""2002-02-28T23:59:61""#).is_err());
1587     assert!(from_str(r#""2016-07-08T09:10:48,090""#).is_err());
1588     assert!(from_str(r#""2016-07-08 09:10:48.090""#).is_err());
1589     assert!(from_str(r#""2016-007-08T09:10:48.090""#).is_err());
1590     assert!(from_str(r#""yyyy-mm-ddThh:mm:ss.fffffffff""#).is_err());
1591     assert!(from_str(r#"20160708000000"#).is_err());
1592     assert!(from_str(r#"{}"#).is_err());
1593     // pre-0.3.0 rustc-serialize format is now invalid
1594     assert!(from_str(r#"{"date":{"ymdf":20},"time":{"secs":0,"frac":0}}"#).is_err());
1595     assert!(from_str(r#"null"#).is_err());
1596 }
1597 
1598 #[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,1599 fn test_decodable_json_timestamp<F, E>(from_str: F)
1600 where
1601     F: Fn(&str) -> Result<rustc_serialize::TsSeconds, E>,
1602     E: ::std::fmt::Debug,
1603 {
1604     assert_eq!(
1605         *from_str("0").unwrap(),
1606         NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0),
1607         "should parse integers as timestamps"
1608     );
1609     assert_eq!(
1610         *from_str("-1").unwrap(),
1611         NaiveDate::from_ymd(1969, 12, 31).and_hms(23, 59, 59),
1612         "should parse integers as timestamps"
1613     );
1614 }
1615 
1616 #[cfg(feature = "rustc-serialize")]
1617 pub mod rustc_serialize {
1618     use super::NaiveDateTime;
1619     use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
1620     use std::ops::Deref;
1621 
1622     impl Encodable for NaiveDateTime {
encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>1623         fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1624             format!("{:?}", self).encode(s)
1625         }
1626     }
1627 
1628     impl Decodable for NaiveDateTime {
decode<D: Decoder>(d: &mut D) -> Result<NaiveDateTime, D::Error>1629         fn decode<D: Decoder>(d: &mut D) -> Result<NaiveDateTime, D::Error> {
1630             d.read_str()?.parse().map_err(|_| d.error("invalid date time string"))
1631         }
1632     }
1633 
1634     /// A `DateTime` that can be deserialized from a seconds-based timestamp
1635     #[derive(Debug)]
1636     #[deprecated(
1637         since = "1.4.2",
1638         note = "RustcSerialize will be removed before chrono 1.0, use Serde instead"
1639     )]
1640     pub struct TsSeconds(NaiveDateTime);
1641 
1642     #[allow(deprecated)]
1643     impl From<TsSeconds> for NaiveDateTime {
1644         /// Pull the internal NaiveDateTime out
1645         #[allow(deprecated)]
from(obj: TsSeconds) -> NaiveDateTime1646         fn from(obj: TsSeconds) -> NaiveDateTime {
1647             obj.0
1648         }
1649     }
1650 
1651     #[allow(deprecated)]
1652     impl Deref for TsSeconds {
1653         type Target = NaiveDateTime;
1654 
1655         #[allow(deprecated)]
deref(&self) -> &Self::Target1656         fn deref(&self) -> &Self::Target {
1657             &self.0
1658         }
1659     }
1660 
1661     #[allow(deprecated)]
1662     impl Decodable for TsSeconds {
1663         #[allow(deprecated)]
decode<D: Decoder>(d: &mut D) -> Result<TsSeconds, D::Error>1664         fn decode<D: Decoder>(d: &mut D) -> Result<TsSeconds, D::Error> {
1665             Ok(TsSeconds(
1666                 NaiveDateTime::from_timestamp_opt(d.read_i64()?, 0)
1667                     .ok_or_else(|| d.error("invalid timestamp"))?,
1668             ))
1669         }
1670     }
1671 
1672     #[cfg(test)]
1673     use rustc_serialize::json;
1674 
1675     #[test]
test_encodable()1676     fn test_encodable() {
1677         super::test_encodable_json(json::encode);
1678     }
1679 
1680     #[test]
test_decodable()1681     fn test_decodable() {
1682         super::test_decodable_json(json::decode);
1683     }
1684 
1685     #[test]
test_decodable_timestamps()1686     fn test_decodable_timestamps() {
1687         super::test_decodable_json_timestamp(json::decode);
1688     }
1689 }
1690 
1691 /// Tools to help serializing/deserializing `NaiveDateTime`s
1692 #[cfg(feature = "serde")]
1693 pub mod serde {
1694     use super::NaiveDateTime;
1695     use core::fmt;
1696     use serdelib::{de, ser};
1697 
1698     /// Serialize a `NaiveDateTime` as an RFC 3339 string
1699     ///
1700     /// See [the `serde` module](./serde/index.html) for alternate
1701     /// serialization formats.
1702     impl ser::Serialize for NaiveDateTime {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer,1703         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1704         where
1705             S: ser::Serializer,
1706         {
1707             struct FormatWrapped<'a, D: 'a> {
1708                 inner: &'a D,
1709             }
1710 
1711             impl<'a, D: fmt::Debug> fmt::Display for FormatWrapped<'a, D> {
1712                 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1713                     self.inner.fmt(f)
1714                 }
1715             }
1716 
1717             serializer.collect_str(&FormatWrapped { inner: &self })
1718         }
1719     }
1720 
1721     struct NaiveDateTimeVisitor;
1722 
1723     impl<'de> de::Visitor<'de> for NaiveDateTimeVisitor {
1724         type Value = NaiveDateTime;
1725 
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1726         fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1727             write!(formatter, "a formatted date and time string")
1728         }
1729 
visit_str<E>(self, value: &str) -> Result<NaiveDateTime, E> where E: de::Error,1730         fn visit_str<E>(self, value: &str) -> Result<NaiveDateTime, E>
1731         where
1732             E: de::Error,
1733         {
1734             value.parse().map_err(E::custom)
1735         }
1736     }
1737 
1738     impl<'de> de::Deserialize<'de> for NaiveDateTime {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>,1739         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1740         where
1741             D: de::Deserializer<'de>,
1742         {
1743             deserializer.deserialize_str(NaiveDateTimeVisitor)
1744         }
1745     }
1746 
1747     /// Used to serialize/deserialize from nanosecond-precision timestamps
1748     ///
1749     /// # Example:
1750     ///
1751     /// ```rust
1752     /// # // We mark this ignored so that we can test on 1.13 (which does not
1753     /// # // support custom derive), and run tests with --ignored on beta and
1754     /// # // nightly to actually trigger these.
1755     /// #
1756     /// # #[macro_use] extern crate serde_derive;
1757     /// # extern crate serde_json;
1758     /// # extern crate serde;
1759     /// # extern crate chrono;
1760     /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
1761     /// use chrono::naive::serde::ts_nanoseconds;
1762     /// #[derive(Deserialize, Serialize)]
1763     /// struct S {
1764     ///     #[serde(with = "ts_nanoseconds")]
1765     ///     time: NaiveDateTime
1766     /// }
1767     ///
1768     /// # fn example() -> Result<S, serde_json::Error> {
1769     /// let time = NaiveDate::from_ymd(2018, 5, 17).and_hms_nano(02, 04, 59, 918355733);
1770     /// let my_s = S {
1771     ///     time: time.clone(),
1772     /// };
1773     ///
1774     /// let as_string = serde_json::to_string(&my_s)?;
1775     /// assert_eq!(as_string, r#"{"time":1526522699918355733}"#);
1776     /// let my_s: S = serde_json::from_str(&as_string)?;
1777     /// assert_eq!(my_s.time, time);
1778     /// # Ok(my_s)
1779     /// # }
1780     /// # fn main() { example().unwrap(); }
1781     /// ```
1782     pub mod ts_nanoseconds {
1783         use core::fmt;
1784         use serdelib::{de, ser};
1785 
1786         use {ne_timestamp, NaiveDateTime};
1787 
1788         /// Serialize a UTC datetime into an integer number of nanoseconds since the epoch
1789         ///
1790         /// Intended for use with `serde`s `serialize_with` attribute.
1791         ///
1792         /// # Example:
1793         ///
1794         /// ```rust
1795         /// # // We mark this ignored so that we can test on 1.13 (which does not
1796         /// # // support custom derive), and run tests with --ignored on beta and
1797         /// # // nightly to actually trigger these.
1798         /// #
1799         /// # #[macro_use] extern crate serde_derive;
1800         /// # #[macro_use] extern crate serde_json;
1801         /// # #[macro_use] extern crate serde;
1802         /// # extern crate chrono;
1803         /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
1804         /// # use serde::Serialize;
1805         /// use chrono::naive::serde::ts_nanoseconds::serialize as to_nano_ts;
1806         /// #[derive(Serialize)]
1807         /// struct S {
1808         ///     #[serde(serialize_with = "to_nano_ts")]
1809         ///     time: NaiveDateTime
1810         /// }
1811         ///
1812         /// # fn example() -> Result<String, serde_json::Error> {
1813         /// let my_s = S {
1814         ///     time: NaiveDate::from_ymd(2018, 5, 17).and_hms_nano(02, 04, 59, 918355733),
1815         /// };
1816         /// let as_string = serde_json::to_string(&my_s)?;
1817         /// assert_eq!(as_string, r#"{"time":1526522699918355733}"#);
1818         /// # Ok(as_string)
1819         /// # }
1820         /// # fn main() { example().unwrap(); }
1821         /// ```
serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer,1822         pub fn serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
1823         where
1824             S: ser::Serializer,
1825         {
1826             serializer.serialize_i64(dt.timestamp_nanos())
1827         }
1828 
1829         /// Deserialize a `DateTime` from a nanoseconds timestamp
1830         ///
1831         /// Intended for use with `serde`s `deserialize_with` attribute.
1832         ///
1833         /// # Example:
1834         ///
1835         /// ```rust
1836         /// # // We mark this ignored so that we can test on 1.13 (which does not
1837         /// # // support custom derive), and run tests with --ignored on beta and
1838         /// # // nightly to actually trigger these.
1839         /// #
1840         /// # #[macro_use] extern crate serde_derive;
1841         /// # #[macro_use] extern crate serde_json;
1842         /// # extern crate serde;
1843         /// # extern crate chrono;
1844         /// # use chrono::{NaiveDateTime, Utc};
1845         /// # use serde::Deserialize;
1846         /// use chrono::naive::serde::ts_nanoseconds::deserialize as from_nano_ts;
1847         /// #[derive(Deserialize)]
1848         /// struct S {
1849         ///     #[serde(deserialize_with = "from_nano_ts")]
1850         ///     time: NaiveDateTime
1851         /// }
1852         ///
1853         /// # fn example() -> Result<S, serde_json::Error> {
1854         /// let my_s: S = serde_json::from_str(r#"{ "time": 1526522699918355733 }"#)?;
1855         /// # Ok(my_s)
1856         /// # }
1857         /// # fn main() { example().unwrap(); }
1858         /// ```
deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error> where D: de::Deserializer<'de>,1859         pub fn deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
1860         where
1861             D: de::Deserializer<'de>,
1862         {
1863             Ok(d.deserialize_i64(NaiveDateTimeFromNanoSecondsVisitor)?)
1864         }
1865 
1866         struct NaiveDateTimeFromNanoSecondsVisitor;
1867 
1868         impl<'de> de::Visitor<'de> for NaiveDateTimeFromNanoSecondsVisitor {
1869             type Value = NaiveDateTime;
1870 
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1871             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1872                 formatter.write_str("a unix timestamp")
1873             }
1874 
visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E> where E: de::Error,1875             fn visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E>
1876             where
1877                 E: de::Error,
1878             {
1879                 NaiveDateTime::from_timestamp_opt(
1880                     value / 1_000_000_000,
1881                     (value % 1_000_000_000) as u32,
1882                 )
1883                 .ok_or_else(|| E::custom(ne_timestamp(value)))
1884             }
1885 
visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E> where E: de::Error,1886             fn visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E>
1887             where
1888                 E: de::Error,
1889             {
1890                 NaiveDateTime::from_timestamp_opt(
1891                     value as i64 / 1_000_000_000,
1892                     (value as i64 % 1_000_000_000) as u32,
1893                 )
1894                 .ok_or_else(|| E::custom(ne_timestamp(value)))
1895             }
1896         }
1897     }
1898 
1899     /// Used to serialize/deserialize from millisecond-precision timestamps
1900     ///
1901     /// # Example:
1902     ///
1903     /// ```rust
1904     /// # // We mark this ignored so that we can test on 1.13 (which does not
1905     /// # // support custom derive), and run tests with --ignored on beta and
1906     /// # // nightly to actually trigger these.
1907     /// #
1908     /// # #[macro_use] extern crate serde_derive;
1909     /// # extern crate serde_json;
1910     /// # extern crate serde;
1911     /// # extern crate chrono;
1912     /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
1913     /// use chrono::naive::serde::ts_milliseconds;
1914     /// #[derive(Deserialize, Serialize)]
1915     /// struct S {
1916     ///     #[serde(with = "ts_milliseconds")]
1917     ///     time: NaiveDateTime
1918     /// }
1919     ///
1920     /// # fn example() -> Result<S, serde_json::Error> {
1921     /// let time = NaiveDate::from_ymd(2018, 5, 17).and_hms_milli(02, 04, 59, 918);
1922     /// let my_s = S {
1923     ///     time: time.clone(),
1924     /// };
1925     ///
1926     /// let as_string = serde_json::to_string(&my_s)?;
1927     /// assert_eq!(as_string, r#"{"time":1526522699918}"#);
1928     /// let my_s: S = serde_json::from_str(&as_string)?;
1929     /// assert_eq!(my_s.time, time);
1930     /// # Ok(my_s)
1931     /// # }
1932     /// # fn main() { example().unwrap(); }
1933     /// ```
1934     pub mod ts_milliseconds {
1935         use core::fmt;
1936         use serdelib::{de, ser};
1937 
1938         use {ne_timestamp, NaiveDateTime};
1939 
1940         /// Serialize a UTC datetime into an integer number of milliseconds since the epoch
1941         ///
1942         /// Intended for use with `serde`s `serialize_with` attribute.
1943         ///
1944         /// # Example:
1945         ///
1946         /// ```rust
1947         /// # // We mark this ignored so that we can test on 1.13 (which does not
1948         /// # // support custom derive), and run tests with --ignored on beta and
1949         /// # // nightly to actually trigger these.
1950         /// #
1951         /// # #[macro_use] extern crate serde_derive;
1952         /// # #[macro_use] extern crate serde_json;
1953         /// # #[macro_use] extern crate serde;
1954         /// # extern crate chrono;
1955         /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
1956         /// # use serde::Serialize;
1957         /// use chrono::naive::serde::ts_milliseconds::serialize as to_milli_ts;
1958         /// #[derive(Serialize)]
1959         /// struct S {
1960         ///     #[serde(serialize_with = "to_milli_ts")]
1961         ///     time: NaiveDateTime
1962         /// }
1963         ///
1964         /// # fn example() -> Result<String, serde_json::Error> {
1965         /// let my_s = S {
1966         ///     time: NaiveDate::from_ymd(2018, 5, 17).and_hms_milli(02, 04, 59, 918),
1967         /// };
1968         /// let as_string = serde_json::to_string(&my_s)?;
1969         /// assert_eq!(as_string, r#"{"time":1526522699918}"#);
1970         /// # Ok(as_string)
1971         /// # }
1972         /// # fn main() { example().unwrap(); }
1973         /// ```
serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer,1974         pub fn serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
1975         where
1976             S: ser::Serializer,
1977         {
1978             serializer.serialize_i64(dt.timestamp_millis())
1979         }
1980 
1981         /// Deserialize a `DateTime` from a milliseconds timestamp
1982         ///
1983         /// Intended for use with `serde`s `deserialize_with` attribute.
1984         ///
1985         /// # Example:
1986         ///
1987         /// ```rust
1988         /// # // We mark this ignored so that we can test on 1.13 (which does not
1989         /// # // support custom derive), and run tests with --ignored on beta and
1990         /// # // nightly to actually trigger these.
1991         /// #
1992         /// # #[macro_use] extern crate serde_derive;
1993         /// # #[macro_use] extern crate serde_json;
1994         /// # extern crate serde;
1995         /// # extern crate chrono;
1996         /// # use chrono::{NaiveDateTime, Utc};
1997         /// # use serde::Deserialize;
1998         /// use chrono::naive::serde::ts_milliseconds::deserialize as from_milli_ts;
1999         /// #[derive(Deserialize)]
2000         /// struct S {
2001         ///     #[serde(deserialize_with = "from_milli_ts")]
2002         ///     time: NaiveDateTime
2003         /// }
2004         ///
2005         /// # fn example() -> Result<S, serde_json::Error> {
2006         /// let my_s: S = serde_json::from_str(r#"{ "time": 1526522699918 }"#)?;
2007         /// # Ok(my_s)
2008         /// # }
2009         /// # fn main() { example().unwrap(); }
2010         /// ```
deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error> where D: de::Deserializer<'de>,2011         pub fn deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
2012         where
2013             D: de::Deserializer<'de>,
2014         {
2015             Ok(d.deserialize_i64(NaiveDateTimeFromMilliSecondsVisitor)?)
2016         }
2017 
2018         struct NaiveDateTimeFromMilliSecondsVisitor;
2019 
2020         impl<'de> de::Visitor<'de> for NaiveDateTimeFromMilliSecondsVisitor {
2021             type Value = NaiveDateTime;
2022 
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result2023             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2024                 formatter.write_str("a unix timestamp")
2025             }
2026 
visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E> where E: de::Error,2027             fn visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E>
2028             where
2029                 E: de::Error,
2030             {
2031                 NaiveDateTime::from_timestamp_opt(value / 1000, ((value % 1000) * 1_000_000) as u32)
2032                     .ok_or_else(|| E::custom(ne_timestamp(value)))
2033             }
2034 
visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E> where E: de::Error,2035             fn visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E>
2036             where
2037                 E: de::Error,
2038             {
2039                 NaiveDateTime::from_timestamp_opt(
2040                     (value / 1000) as i64,
2041                     ((value % 1000) * 1_000_000) as u32,
2042                 )
2043                 .ok_or_else(|| E::custom(ne_timestamp(value)))
2044             }
2045         }
2046     }
2047 
2048     /// Used to serialize/deserialize from second-precision timestamps
2049     ///
2050     /// # Example:
2051     ///
2052     /// ```rust
2053     /// # // We mark this ignored so that we can test on 1.13 (which does not
2054     /// # // support custom derive), and run tests with --ignored on beta and
2055     /// # // nightly to actually trigger these.
2056     /// #
2057     /// # #[macro_use] extern crate serde_derive;
2058     /// # extern crate serde_json;
2059     /// # extern crate serde;
2060     /// # extern crate chrono;
2061     /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
2062     /// use chrono::naive::serde::ts_seconds;
2063     /// #[derive(Deserialize, Serialize)]
2064     /// struct S {
2065     ///     #[serde(with = "ts_seconds")]
2066     ///     time: NaiveDateTime
2067     /// }
2068     ///
2069     /// # fn example() -> Result<S, serde_json::Error> {
2070     /// let time = NaiveDate::from_ymd(2015, 5, 15).and_hms(10, 0, 0);
2071     /// let my_s = S {
2072     ///     time: time.clone(),
2073     /// };
2074     ///
2075     /// let as_string = serde_json::to_string(&my_s)?;
2076     /// assert_eq!(as_string, r#"{"time":1431684000}"#);
2077     /// let my_s: S = serde_json::from_str(&as_string)?;
2078     /// assert_eq!(my_s.time, time);
2079     /// # Ok(my_s)
2080     /// # }
2081     /// # fn main() { example().unwrap(); }
2082     /// ```
2083     pub mod ts_seconds {
2084         use core::fmt;
2085         use serdelib::{de, ser};
2086 
2087         use {ne_timestamp, NaiveDateTime};
2088 
2089         /// Serialize a UTC datetime into an integer number of seconds since the epoch
2090         ///
2091         /// Intended for use with `serde`s `serialize_with` attribute.
2092         ///
2093         /// # Example:
2094         ///
2095         /// ```rust
2096         /// # // We mark this ignored so that we can test on 1.13 (which does not
2097         /// # // support custom derive), and run tests with --ignored on beta and
2098         /// # // nightly to actually trigger these.
2099         /// #
2100         /// # #[macro_use] extern crate serde_derive;
2101         /// # #[macro_use] extern crate serde_json;
2102         /// # #[macro_use] extern crate serde;
2103         /// # extern crate chrono;
2104         /// # use chrono::{TimeZone, NaiveDate, NaiveDateTime, Utc};
2105         /// # use serde::Serialize;
2106         /// use chrono::naive::serde::ts_seconds::serialize as to_ts;
2107         /// #[derive(Serialize)]
2108         /// struct S {
2109         ///     #[serde(serialize_with = "to_ts")]
2110         ///     time: NaiveDateTime
2111         /// }
2112         ///
2113         /// # fn example() -> Result<String, serde_json::Error> {
2114         /// let my_s = S {
2115         ///     time: NaiveDate::from_ymd(2015, 5, 15).and_hms(10, 0, 0),
2116         /// };
2117         /// let as_string = serde_json::to_string(&my_s)?;
2118         /// assert_eq!(as_string, r#"{"time":1431684000}"#);
2119         /// # Ok(as_string)
2120         /// # }
2121         /// # fn main() { example().unwrap(); }
2122         /// ```
serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer,2123         pub fn serialize<S>(dt: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
2124         where
2125             S: ser::Serializer,
2126         {
2127             serializer.serialize_i64(dt.timestamp())
2128         }
2129 
2130         /// Deserialize a `DateTime` from a seconds timestamp
2131         ///
2132         /// Intended for use with `serde`s `deserialize_with` attribute.
2133         ///
2134         /// # Example:
2135         ///
2136         /// ```rust
2137         /// # // We mark this ignored so that we can test on 1.13 (which does not
2138         /// # // support custom derive), and run tests with --ignored on beta and
2139         /// # // nightly to actually trigger these.
2140         /// #
2141         /// # #[macro_use] extern crate serde_derive;
2142         /// # #[macro_use] extern crate serde_json;
2143         /// # extern crate serde;
2144         /// # extern crate chrono;
2145         /// # use chrono::{NaiveDateTime, Utc};
2146         /// # use serde::Deserialize;
2147         /// use chrono::naive::serde::ts_seconds::deserialize as from_ts;
2148         /// #[derive(Deserialize)]
2149         /// struct S {
2150         ///     #[serde(deserialize_with = "from_ts")]
2151         ///     time: NaiveDateTime
2152         /// }
2153         ///
2154         /// # fn example() -> Result<S, serde_json::Error> {
2155         /// let my_s: S = serde_json::from_str(r#"{ "time": 1431684000 }"#)?;
2156         /// # Ok(my_s)
2157         /// # }
2158         /// # fn main() { example().unwrap(); }
2159         /// ```
deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error> where D: de::Deserializer<'de>,2160         pub fn deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
2161         where
2162             D: de::Deserializer<'de>,
2163         {
2164             Ok(d.deserialize_i64(NaiveDateTimeFromSecondsVisitor)?)
2165         }
2166 
2167         struct NaiveDateTimeFromSecondsVisitor;
2168 
2169         impl<'de> de::Visitor<'de> for NaiveDateTimeFromSecondsVisitor {
2170             type Value = NaiveDateTime;
2171 
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result2172             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2173                 formatter.write_str("a unix timestamp")
2174             }
2175 
visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E> where E: de::Error,2176             fn visit_i64<E>(self, value: i64) -> Result<NaiveDateTime, E>
2177             where
2178                 E: de::Error,
2179             {
2180                 NaiveDateTime::from_timestamp_opt(value, 0)
2181                     .ok_or_else(|| E::custom(ne_timestamp(value)))
2182             }
2183 
visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E> where E: de::Error,2184             fn visit_u64<E>(self, value: u64) -> Result<NaiveDateTime, E>
2185             where
2186                 E: de::Error,
2187             {
2188                 NaiveDateTime::from_timestamp_opt(value as i64, 0)
2189                     .ok_or_else(|| E::custom(ne_timestamp(value)))
2190             }
2191         }
2192     }
2193 
2194     #[cfg(test)]
2195     extern crate bincode;
2196     #[cfg(test)]
2197     extern crate serde_derive;
2198     #[cfg(test)]
2199     extern crate serde_json;
2200 
2201     #[test]
test_serde_serialize()2202     fn test_serde_serialize() {
2203         super::test_encodable_json(self::serde_json::to_string);
2204     }
2205 
2206     #[test]
test_serde_deserialize()2207     fn test_serde_deserialize() {
2208         super::test_decodable_json(|input| self::serde_json::from_str(&input));
2209     }
2210 
2211     // Bincode is relevant to test separately from JSON because
2212     // it is not self-describing.
2213     #[test]
test_serde_bincode()2214     fn test_serde_bincode() {
2215         use self::bincode::{deserialize, serialize, Infinite};
2216         use naive::NaiveDate;
2217 
2218         let dt = NaiveDate::from_ymd(2016, 7, 8).and_hms_milli(9, 10, 48, 90);
2219         let encoded = serialize(&dt, Infinite).unwrap();
2220         let decoded: NaiveDateTime = deserialize(&encoded).unwrap();
2221         assert_eq!(dt, decoded);
2222     }
2223 
2224     #[test]
test_serde_bincode_optional()2225     fn test_serde_bincode_optional() {
2226         use self::bincode::{deserialize, serialize, Infinite};
2227         use self::serde_derive::{Deserialize, Serialize};
2228         use prelude::*;
2229         use serde::ts_nanoseconds_option;
2230 
2231         #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
2232         struct Test {
2233             one: Option<i64>,
2234             #[serde(with = "ts_nanoseconds_option")]
2235             two: Option<DateTime<Utc>>,
2236         }
2237 
2238         let expected = Test { one: Some(1), two: Some(Utc.ymd(1970, 1, 1).and_hms(0, 1, 1)) };
2239         let bytes: Vec<u8> = serialize(&expected, Infinite).unwrap();
2240         let actual = deserialize::<Test>(&(bytes)).unwrap();
2241 
2242         assert_eq!(expected, actual);
2243     }
2244 }
2245 
2246 #[cfg(test)]
2247 mod tests {
2248     use super::NaiveDateTime;
2249     use naive::{NaiveDate, MAX_DATE, MIN_DATE};
2250     use oldtime::Duration;
2251     use std::i64;
2252     use Datelike;
2253 
2254     #[test]
test_datetime_from_timestamp()2255     fn test_datetime_from_timestamp() {
2256         let from_timestamp = |secs| NaiveDateTime::from_timestamp_opt(secs, 0);
2257         let ymdhms = |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2258         assert_eq!(from_timestamp(-1), Some(ymdhms(1969, 12, 31, 23, 59, 59)));
2259         assert_eq!(from_timestamp(0), Some(ymdhms(1970, 1, 1, 0, 0, 0)));
2260         assert_eq!(from_timestamp(1), Some(ymdhms(1970, 1, 1, 0, 0, 1)));
2261         assert_eq!(from_timestamp(1_000_000_000), Some(ymdhms(2001, 9, 9, 1, 46, 40)));
2262         assert_eq!(from_timestamp(0x7fffffff), Some(ymdhms(2038, 1, 19, 3, 14, 7)));
2263         assert_eq!(from_timestamp(i64::MIN), None);
2264         assert_eq!(from_timestamp(i64::MAX), None);
2265     }
2266 
2267     #[test]
test_datetime_add()2268     fn test_datetime_add() {
2269         fn check(
2270             (y, m, d, h, n, s): (i32, u32, u32, u32, u32, u32),
2271             rhs: Duration,
2272             result: Option<(i32, u32, u32, u32, u32, u32)>,
2273         ) {
2274             let lhs = NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2275             let sum =
2276                 result.map(|(y, m, d, h, n, s)| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s));
2277             assert_eq!(lhs.checked_add_signed(rhs), sum);
2278             assert_eq!(lhs.checked_sub_signed(-rhs), sum);
2279         };
2280 
2281         check(
2282             (2014, 5, 6, 7, 8, 9),
2283             Duration::seconds(3600 + 60 + 1),
2284             Some((2014, 5, 6, 8, 9, 10)),
2285         );
2286         check(
2287             (2014, 5, 6, 7, 8, 9),
2288             Duration::seconds(-(3600 + 60 + 1)),
2289             Some((2014, 5, 6, 6, 7, 8)),
2290         );
2291         check((2014, 5, 6, 7, 8, 9), Duration::seconds(86399), Some((2014, 5, 7, 7, 8, 8)));
2292         check((2014, 5, 6, 7, 8, 9), Duration::seconds(86_400 * 10), Some((2014, 5, 16, 7, 8, 9)));
2293         check((2014, 5, 6, 7, 8, 9), Duration::seconds(-86_400 * 10), Some((2014, 4, 26, 7, 8, 9)));
2294         check((2014, 5, 6, 7, 8, 9), Duration::seconds(86_400 * 10), Some((2014, 5, 16, 7, 8, 9)));
2295 
2296         // overflow check
2297         // assumes that we have correct values for MAX/MIN_DAYS_FROM_YEAR_0 from `naive::date`.
2298         // (they are private constants, but the equivalence is tested in that module.)
2299         let max_days_from_year_0 = MAX_DATE.signed_duration_since(NaiveDate::from_ymd(0, 1, 1));
2300         check((0, 1, 1, 0, 0, 0), max_days_from_year_0, Some((MAX_DATE.year(), 12, 31, 0, 0, 0)));
2301         check(
2302             (0, 1, 1, 0, 0, 0),
2303             max_days_from_year_0 + Duration::seconds(86399),
2304             Some((MAX_DATE.year(), 12, 31, 23, 59, 59)),
2305         );
2306         check((0, 1, 1, 0, 0, 0), max_days_from_year_0 + Duration::seconds(86_400), None);
2307         check((0, 1, 1, 0, 0, 0), Duration::max_value(), None);
2308 
2309         let min_days_from_year_0 = MIN_DATE.signed_duration_since(NaiveDate::from_ymd(0, 1, 1));
2310         check((0, 1, 1, 0, 0, 0), min_days_from_year_0, Some((MIN_DATE.year(), 1, 1, 0, 0, 0)));
2311         check((0, 1, 1, 0, 0, 0), min_days_from_year_0 - Duration::seconds(1), None);
2312         check((0, 1, 1, 0, 0, 0), Duration::min_value(), None);
2313     }
2314 
2315     #[test]
test_datetime_sub()2316     fn test_datetime_sub() {
2317         let ymdhms = |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2318         let since = NaiveDateTime::signed_duration_since;
2319         assert_eq!(
2320             since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 9)),
2321             Duration::zero()
2322         );
2323         assert_eq!(
2324             since(ymdhms(2014, 5, 6, 7, 8, 10), ymdhms(2014, 5, 6, 7, 8, 9)),
2325             Duration::seconds(1)
2326         );
2327         assert_eq!(
2328             since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
2329             Duration::seconds(-1)
2330         );
2331         assert_eq!(
2332             since(ymdhms(2014, 5, 7, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
2333             Duration::seconds(86399)
2334         );
2335         assert_eq!(
2336             since(ymdhms(2001, 9, 9, 1, 46, 39), ymdhms(1970, 1, 1, 0, 0, 0)),
2337             Duration::seconds(999_999_999)
2338         );
2339     }
2340 
2341     #[test]
test_datetime_addassignment()2342     fn test_datetime_addassignment() {
2343         let ymdhms = |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2344         let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
2345         date += Duration::minutes(10_000_000);
2346         assert_eq!(date, ymdhms(2035, 10, 6, 20, 50, 10));
2347         date += Duration::days(10);
2348         assert_eq!(date, ymdhms(2035, 10, 16, 20, 50, 10));
2349     }
2350 
2351     #[test]
test_datetime_subassignment()2352     fn test_datetime_subassignment() {
2353         let ymdhms = |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2354         let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
2355         date -= Duration::minutes(10_000_000);
2356         assert_eq!(date, ymdhms(1997, 9, 26, 23, 30, 10));
2357         date -= Duration::days(10);
2358         assert_eq!(date, ymdhms(1997, 9, 16, 23, 30, 10));
2359     }
2360 
2361     #[test]
test_datetime_timestamp()2362     fn test_datetime_timestamp() {
2363         let to_timestamp =
2364             |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s).timestamp();
2365         assert_eq!(to_timestamp(1969, 12, 31, 23, 59, 59), -1);
2366         assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 0), 0);
2367         assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 1), 1);
2368         assert_eq!(to_timestamp(2001, 9, 9, 1, 46, 40), 1_000_000_000);
2369         assert_eq!(to_timestamp(2038, 1, 19, 3, 14, 7), 0x7fffffff);
2370     }
2371 
2372     #[test]
test_datetime_from_str()2373     fn test_datetime_from_str() {
2374         // valid cases
2375         let valid = [
2376             "2015-2-18T23:16:9.15",
2377             "-77-02-18T23:16:09",
2378             "  +82701  -  05  -  6  T  15  :  9  : 60.898989898989   ",
2379         ];
2380         for &s in &valid {
2381             let d = match s.parse::<NaiveDateTime>() {
2382                 Ok(d) => d,
2383                 Err(e) => panic!("parsing `{}` has failed: {}", s, e),
2384             };
2385             let s_ = format!("{:?}", d);
2386             // `s` and `s_` may differ, but `s.parse()` and `s_.parse()` must be same
2387             let d_ = match s_.parse::<NaiveDateTime>() {
2388                 Ok(d) => d,
2389                 Err(e) => {
2390                     panic!("`{}` is parsed into `{:?}`, but reparsing that has failed: {}", s, d, e)
2391                 }
2392             };
2393             assert!(
2394                 d == d_,
2395                 "`{}` is parsed into `{:?}`, but reparsed result \
2396                               `{:?}` does not match",
2397                 s,
2398                 d,
2399                 d_
2400             );
2401         }
2402 
2403         // some invalid cases
2404         // since `ParseErrorKind` is private, all we can do is to check if there was an error
2405         assert!("".parse::<NaiveDateTime>().is_err());
2406         assert!("x".parse::<NaiveDateTime>().is_err());
2407         assert!("15".parse::<NaiveDateTime>().is_err());
2408         assert!("15:8:9".parse::<NaiveDateTime>().is_err());
2409         assert!("15-8-9".parse::<NaiveDateTime>().is_err());
2410         assert!("2015-15-15T15:15:15".parse::<NaiveDateTime>().is_err());
2411         assert!("2012-12-12T12:12:12x".parse::<NaiveDateTime>().is_err());
2412         assert!("2012-123-12T12:12:12".parse::<NaiveDateTime>().is_err());
2413         assert!("+ 82701-123-12T12:12:12".parse::<NaiveDateTime>().is_err());
2414         assert!("+802701-123-12T12:12:12".parse::<NaiveDateTime>().is_err()); // out-of-bound
2415     }
2416 
2417     #[test]
test_datetime_parse_from_str()2418     fn test_datetime_parse_from_str() {
2419         let ymdhms = |y, m, d, h, n, s| NaiveDate::from_ymd(y, m, d).and_hms(h, n, s);
2420         let ymdhmsn =
2421             |y, m, d, h, n, s, nano| NaiveDate::from_ymd(y, m, d).and_hms_nano(h, n, s, nano);
2422         assert_eq!(
2423             NaiveDateTime::parse_from_str("2014-5-7T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
2424             Ok(ymdhms(2014, 5, 7, 12, 34, 56))
2425         ); // ignore offset
2426         assert_eq!(
2427             NaiveDateTime::parse_from_str("2015-W06-1 000000", "%G-W%V-%u%H%M%S"),
2428             Ok(ymdhms(2015, 2, 2, 0, 0, 0))
2429         );
2430         assert_eq!(
2431             NaiveDateTime::parse_from_str(
2432                 "Fri, 09 Aug 2013 23:54:35 GMT",
2433                 "%a, %d %b %Y %H:%M:%S GMT"
2434             ),
2435             Ok(ymdhms(2013, 8, 9, 23, 54, 35))
2436         );
2437         assert!(NaiveDateTime::parse_from_str(
2438             "Sat, 09 Aug 2013 23:54:35 GMT",
2439             "%a, %d %b %Y %H:%M:%S GMT"
2440         )
2441         .is_err());
2442         assert!(NaiveDateTime::parse_from_str("2014-5-7 12:3456", "%Y-%m-%d %H:%M:%S").is_err());
2443         assert!(NaiveDateTime::parse_from_str("12:34:56", "%H:%M:%S").is_err()); // insufficient
2444         assert_eq!(
2445             NaiveDateTime::parse_from_str("1441497364", "%s"),
2446             Ok(ymdhms(2015, 9, 5, 23, 56, 4))
2447         );
2448         assert_eq!(
2449             NaiveDateTime::parse_from_str("1283929614.1234", "%s.%f"),
2450             Ok(ymdhmsn(2010, 9, 8, 7, 6, 54, 1234))
2451         );
2452         assert_eq!(
2453             NaiveDateTime::parse_from_str("1441497364.649", "%s%.3f"),
2454             Ok(ymdhmsn(2015, 9, 5, 23, 56, 4, 649000000))
2455         );
2456         assert_eq!(
2457             NaiveDateTime::parse_from_str("1497854303.087654", "%s%.6f"),
2458             Ok(ymdhmsn(2017, 6, 19, 6, 38, 23, 87654000))
2459         );
2460         assert_eq!(
2461             NaiveDateTime::parse_from_str("1437742189.918273645", "%s%.9f"),
2462             Ok(ymdhmsn(2015, 7, 24, 12, 49, 49, 918273645))
2463         );
2464     }
2465 
2466     #[test]
test_datetime_format()2467     fn test_datetime_format() {
2468         let dt = NaiveDate::from_ymd(2010, 9, 8).and_hms_milli(7, 6, 54, 321);
2469         assert_eq!(dt.format("%c").to_string(), "Wed Sep  8 07:06:54 2010");
2470         assert_eq!(dt.format("%s").to_string(), "1283929614");
2471         assert_eq!(dt.format("%t%n%%%n%t").to_string(), "\t\n%\n\t");
2472 
2473         // a horror of leap second: coming near to you.
2474         let dt = NaiveDate::from_ymd(2012, 6, 30).and_hms_milli(23, 59, 59, 1_000);
2475         assert_eq!(dt.format("%c").to_string(), "Sat Jun 30 23:59:60 2012");
2476         assert_eq!(dt.format("%s").to_string(), "1341100799"); // not 1341100800, it's intentional.
2477     }
2478 
2479     #[test]
test_datetime_add_sub_invariant()2480     fn test_datetime_add_sub_invariant() {
2481         // issue #37
2482         let base = NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0);
2483         let t = -946684799990000;
2484         let time = base + Duration::microseconds(t);
2485         assert_eq!(t, time.signed_duration_since(base).num_microseconds().unwrap());
2486     }
2487 
2488     #[test]
test_nanosecond_range()2489     fn test_nanosecond_range() {
2490         const A_BILLION: i64 = 1_000_000_000;
2491         let maximum = "2262-04-11T23:47:16.854775804";
2492         let parsed: NaiveDateTime = maximum.parse().unwrap();
2493         let nanos = parsed.timestamp_nanos();
2494         assert_eq!(
2495             parsed,
2496             NaiveDateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32)
2497         );
2498 
2499         let minimum = "1677-09-21T00:12:44.000000000";
2500         let parsed: NaiveDateTime = minimum.parse().unwrap();
2501         let nanos = parsed.timestamp_nanos();
2502         assert_eq!(
2503             parsed,
2504             NaiveDateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32)
2505         );
2506     }
2507 }
2508