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