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