Debian Codegraph @

debian/rust-vendor/chrono/src/datetime/tests.rs

raw
1 use super::DateTime;
2 use crate::naive::{NaiveDate, NaiveTime};
3 #[cfg(feature = "clock")]
4 use crate::offset::Local;
5 use crate::offset::{FixedOffset, Offset, TimeZone, Utc};
6 use crate::{Datelike, Days, MappedLocalTime, Months, NaiveDateTime, TimeDelta, Timelike, Weekday};
7
8 #[derive(Clone)]
9 struct DstTester;
10
11 impl DstTester {
12 fn winter_offset() -> FixedOffset {
13 FixedOffset::east_opt(8 * 60 * 60).unwrap()
14 }
15 fn summer_offset() -> FixedOffset {
16 FixedOffset::east_opt(9 * 60 * 60).unwrap()
17 }
18
19 const TO_WINTER_MONTH_DAY: (u32, u32) = (4, 15);
20 const TO_SUMMER_MONTH_DAY: (u32, u32) = (9, 15);
21
22 fn transition_start_local() -> NaiveTime {
23 NaiveTime::from_hms_opt(2, 0, 0).unwrap()
24 }
25 }
26
27 impl TimeZone for DstTester {
28 type Offset = FixedOffset;
29
30 fn from_offset(_: &Self::Offset) -> Self {
31 DstTester
32 }
33
34 fn offset_from_local_date(&self, _: &NaiveDate) -> crate::MappedLocalTime<Self::Offset> {
35 unimplemented!()
36 }
37
38 fn offset_from_local_datetime(
39 &self,
40 local: &NaiveDateTime,
41 ) -> crate::MappedLocalTime<Self::Offset> {
42 let local_to_winter_transition_start = NaiveDate::from_ymd_opt(
43 local.year(),
44 DstTester::TO_WINTER_MONTH_DAY.0,
45 DstTester::TO_WINTER_MONTH_DAY.1,
46 )
47 .unwrap()
48 .and_time(DstTester::transition_start_local());
49
50 let local_to_winter_transition_end = NaiveDate::from_ymd_opt(
51 local.year(),
52 DstTester::TO_WINTER_MONTH_DAY.0,
53 DstTester::TO_WINTER_MONTH_DAY.1,
54 )
55 .unwrap()
56 .and_time(DstTester::transition_start_local() - TimeDelta::try_hours(1).unwrap());
57
58 let local_to_summer_transition_start = NaiveDate::from_ymd_opt(
59 local.year(),
60 DstTester::TO_SUMMER_MONTH_DAY.0,
61 DstTester::TO_SUMMER_MONTH_DAY.1,
62 )
63 .unwrap()
64 .and_time(DstTester::transition_start_local());
65
66 let local_to_summer_transition_end = NaiveDate::from_ymd_opt(
67 local.year(),
68 DstTester::TO_SUMMER_MONTH_DAY.0,
69 DstTester::TO_SUMMER_MONTH_DAY.1,
70 )
71 .unwrap()
72 .and_time(DstTester::transition_start_local() + TimeDelta::try_hours(1).unwrap());
73
74 if *local < local_to_winter_transition_end || *local >= local_to_summer_transition_end {
75 MappedLocalTime::Single(DstTester::summer_offset())
76 } else if *local >= local_to_winter_transition_start
77 && *local < local_to_summer_transition_start
78 {
79 MappedLocalTime::Single(DstTester::winter_offset())
80 } else if *local >= local_to_winter_transition_end
81 && *local < local_to_winter_transition_start
82 {
83 MappedLocalTime::Ambiguous(DstTester::winter_offset(), DstTester::summer_offset())
84 } else if *local >= local_to_summer_transition_start
85 && *local < local_to_summer_transition_end
86 {
87 MappedLocalTime::None
88 } else {
89 panic!("Unexpected local time {local}")
90 }
91 }
92
93 fn offset_from_utc_date(&self, _: &NaiveDate) -> Self::Offset {
94 unimplemented!()
95 }
96
97 fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
98 let utc_to_winter_transition = NaiveDate::from_ymd_opt(
99 utc.year(),
100 DstTester::TO_WINTER_MONTH_DAY.0,
101 DstTester::TO_WINTER_MONTH_DAY.1,
102 )
103 .unwrap()
104 .and_time(DstTester::transition_start_local())
105 - DstTester::summer_offset();
106
107 let utc_to_summer_transition = NaiveDate::from_ymd_opt(
108 utc.year(),
109 DstTester::TO_SUMMER_MONTH_DAY.0,
110 DstTester::TO_SUMMER_MONTH_DAY.1,
111 )
112 .unwrap()
113 .and_time(DstTester::transition_start_local())
114 - DstTester::winter_offset();
115
116 if *utc < utc_to_winter_transition || *utc >= utc_to_summer_transition {
117 DstTester::summer_offset()
118 } else if *utc >= utc_to_winter_transition && *utc < utc_to_summer_transition {
119 DstTester::winter_offset()
120 } else {
121 panic!("Unexpected utc time {utc}")
122 }
123 }
124 }
125
126 #[test]
127 fn test_datetime_from_timestamp_millis() {
128 let valid_map = [
129 (1662921288000, "2022-09-11 18:34:48.000000000"),
130 (1662921288123, "2022-09-11 18:34:48.123000000"),
131 (1662921287890, "2022-09-11 18:34:47.890000000"),
132 (-2208936075000, "1900-01-01 14:38:45.000000000"),
133 (0, "1970-01-01 00:00:00.000000000"),
134 (119731017000, "1973-10-17 18:36:57.000000000"),
135 (1234567890000, "2009-02-13 23:31:30.000000000"),
136 (2034061609000, "2034-06-16 09:06:49.000000000"),
137 ];
138
139 for (timestamp_millis, _formatted) in valid_map.iter().copied() {
140 let datetime = DateTime::from_timestamp_millis(timestamp_millis).unwrap();
141 assert_eq!(timestamp_millis, datetime.timestamp_millis());
142 #[cfg(feature = "alloc")]
143 assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
144 }
145
146 let invalid = [i64::MAX, i64::MIN];
147
148 for timestamp_millis in invalid.iter().copied() {
149 let datetime = DateTime::from_timestamp_millis(timestamp_millis);
150 assert!(datetime.is_none());
151 }
152
153 // Test that the result of `from_timestamp_millis` compares equal to
154 // that of `from_timestamp_opt`.
155 let secs_test = [0, 1, 2, 1000, 1234, 12345678, -1, -2, -1000, -12345678];
156 for secs in secs_test.iter().cloned() {
157 assert_eq!(
158 DateTime::from_timestamp_millis(secs * 1000),
159 DateTime::from_timestamp_secs(secs)
160 );
161 }
162 }
163
164 #[test]
165 fn test_datetime_from_timestamp_micros() {
166 let valid_map = [
167 (1662921288000000, "2022-09-11 18:34:48.000000000"),
168 (1662921288123456, "2022-09-11 18:34:48.123456000"),
169 (1662921287890000, "2022-09-11 18:34:47.890000000"),
170 (-2208936075000000, "1900-01-01 14:38:45.000000000"),
171 (0, "1970-01-01 00:00:00.000000000"),
172 (119731017000000, "1973-10-17 18:36:57.000000000"),
173 (1234567890000000, "2009-02-13 23:31:30.000000000"),
174 (2034061609000000, "2034-06-16 09:06:49.000000000"),
175 ];
176
177 for (timestamp_micros, _formatted) in valid_map.iter().copied() {
178 let datetime = DateTime::from_timestamp_micros(timestamp_micros).unwrap();
179 assert_eq!(timestamp_micros, datetime.timestamp_micros());
180 #[cfg(feature = "alloc")]
181 assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
182 }
183
184 let invalid = [i64::MAX, i64::MIN];
185
186 for timestamp_micros in invalid.iter().copied() {
187 let datetime = DateTime::from_timestamp_micros(timestamp_micros);
188 assert!(datetime.is_none());
189 }
190
191 // Test that the result of `TimeZone::timestamp_micros` compares equal to
192 // that of `TimeZone::timestamp_opt`.
193 let secs_test = [0, 1, 2, 1000, 1234, 12345678, -1, -2, -1000, -12345678];
194 for secs in secs_test.iter().copied() {
195 assert_eq!(
196 DateTime::from_timestamp_micros(secs * 1_000_000),
197 DateTime::from_timestamp_secs(secs)
198 );
199 }
200 }
201
202 #[test]
203 fn test_datetime_from_timestamp_nanos() {
204 let valid_map = [
205 (1662921288000000000, "2022-09-11 18:34:48.000000000"),
206 (1662921288123456000, "2022-09-11 18:34:48.123456000"),
207 (1662921288123456789, "2022-09-11 18:34:48.123456789"),
208 (1662921287890000000, "2022-09-11 18:34:47.890000000"),
209 (-2208936075000000000, "1900-01-01 14:38:45.000000000"),
210 (-5337182663000000000, "1800-11-15 01:15:37.000000000"),
211 (0, "1970-01-01 00:00:00.000000000"),
212 (119731017000000000, "1973-10-17 18:36:57.000000000"),
213 (1234567890000000000, "2009-02-13 23:31:30.000000000"),
214 (2034061609000000000, "2034-06-16 09:06:49.000000000"),
215 ];
216
217 for (timestamp_nanos, _formatted) in valid_map.iter().copied() {
218 let datetime = DateTime::from_timestamp_nanos(timestamp_nanos);
219 assert_eq!(timestamp_nanos, datetime.timestamp_nanos_opt().unwrap());
220 #[cfg(feature = "alloc")]
221 assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
222 }
223
224 const A_BILLION: i64 = 1_000_000_000;
225 // Maximum datetime in nanoseconds
226 let maximum = "2262-04-11T23:47:16.854775804UTC";
227 let parsed: DateTime<Utc> = maximum.parse().unwrap();
228 let nanos = parsed.timestamp_nanos_opt().unwrap();
229 assert_eq!(
230 Some(DateTime::from_timestamp_nanos(nanos)),
231 DateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32)
232 );
233 // Minimum datetime in nanoseconds
234 let minimum = "1677-09-21T00:12:44.000000000UTC";
235 let parsed: DateTime<Utc> = minimum.parse().unwrap();
236 let nanos = parsed.timestamp_nanos_opt().unwrap();
237 assert_eq!(
238 Some(DateTime::from_timestamp_nanos(nanos)),
239 DateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32)
240 );
241
242 // Test that the result of `TimeZone::timestamp_nanos` compares equal to
243 // that of `TimeZone::timestamp_opt`.
244 let secs_test = [0, 1, 2, 1000, 1234, 12345678, -1, -2, -1000, -12345678];
245 for secs in secs_test.iter().copied() {
246 assert_eq!(
247 Some(DateTime::from_timestamp_nanos(secs * 1_000_000_000)),
248 DateTime::from_timestamp_secs(secs)
249 );
250 }
251 }
252
253 #[test]
254 fn test_datetime_from_timestamp_secs() {
255 let valid = [-2208936075, 0, 119731017, 1234567890, 2034061609];
256
257 for timestamp_secs in valid.iter().copied() {
258 let datetime = DateTime::from_timestamp_secs(timestamp_secs).unwrap();
259 assert_eq!(timestamp_secs, datetime.timestamp());
260 assert_eq!(DateTime::from_timestamp(timestamp_secs, 0).unwrap(), datetime);
261 }
262 }
263
264 #[test]
265 fn test_datetime_from_timestamp() {
266 let ymdhms = |y, m, d, h, n, s| {
267 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap().and_utc()
268 };
269 assert_eq!(DateTime::from_timestamp_secs(-1), Some(ymdhms(1969, 12, 31, 23, 59, 59)));
270 assert_eq!(DateTime::from_timestamp_secs(0), Some(ymdhms(1970, 1, 1, 0, 0, 0)));
271 assert_eq!(DateTime::from_timestamp_secs(1), Some(ymdhms(1970, 1, 1, 0, 0, 1)));
272 assert_eq!(DateTime::from_timestamp_secs(1_000_000_000), Some(ymdhms(2001, 9, 9, 1, 46, 40)));
273 assert_eq!(DateTime::from_timestamp_secs(0x7fffffff), Some(ymdhms(2038, 1, 19, 3, 14, 7)));
274 assert_eq!(DateTime::from_timestamp_secs(i64::MIN), None);
275 assert_eq!(DateTime::from_timestamp_secs(i64::MAX), None);
276 }
277
278 #[test]
279 fn test_datetime_timestamp() {
280 let to_timestamp = |y, m, d, h, n, s| {
281 NaiveDate::from_ymd_opt(y, m, d)
282 .unwrap()
283 .and_hms_opt(h, n, s)
284 .unwrap()
285 .and_utc()
286 .timestamp()
287 };
288 assert_eq!(to_timestamp(1969, 12, 31, 23, 59, 59), -1);
289 assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 0), 0);
290 assert_eq!(to_timestamp(1970, 1, 1, 0, 0, 1), 1);
291 assert_eq!(to_timestamp(2001, 9, 9, 1, 46, 40), 1_000_000_000);
292 assert_eq!(to_timestamp(2038, 1, 19, 3, 14, 7), 0x7fffffff);
293 }
294
295 #[test]
296 fn test_nanosecond_range() {
297 const A_BILLION: i64 = 1_000_000_000;
298 let maximum = "2262-04-11T23:47:16.854775804UTC";
299 let parsed: DateTime<Utc> = maximum.parse().unwrap();
300 let nanos = parsed.timestamp_nanos_opt().unwrap();
301 assert_eq!(
302 parsed,
303 DateTime::<Utc>::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32).unwrap()
304 );
305
306 let minimum = "1677-09-21T00:12:44.000000000UTC";
307 let parsed: DateTime<Utc> = minimum.parse().unwrap();
308 let nanos = parsed.timestamp_nanos_opt().unwrap();
309 assert_eq!(
310 parsed,
311 DateTime::<Utc>::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32).unwrap()
312 );
313
314 // Just beyond range
315 let maximum = "2262-04-11T23:47:16.854775804UTC";
316 let parsed: DateTime<Utc> = maximum.parse().unwrap();
317 let beyond_max = parsed + TimeDelta::try_milliseconds(300).unwrap();
318 assert!(beyond_max.timestamp_nanos_opt().is_none());
319
320 // Far beyond range
321 let maximum = "2262-04-11T23:47:16.854775804UTC";
322 let parsed: DateTime<Utc> = maximum.parse().unwrap();
323 let beyond_max = parsed + Days::new(365);
324 assert!(beyond_max.timestamp_nanos_opt().is_none());
325 }
326
327 #[test]
328 fn test_datetime_add_days() {
329 let est = FixedOffset::west_opt(5 * 60 * 60).unwrap();
330 let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
331
332 assert_eq!(
333 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Days::new(5)),
334 "2014-05-11 07:08:09 -05:00"
335 );
336 assert_eq!(
337 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Days::new(5)),
338 "2014-05-11 07:08:09 +09:00"
339 );
340
341 assert_eq!(
342 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Days::new(35)),
343 "2014-06-10 07:08:09 -05:00"
344 );
345 assert_eq!(
346 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Days::new(35)),
347 "2014-06-10 07:08:09 +09:00"
348 );
349
350 assert_eq!(
351 format!("{}", DstTester.with_ymd_and_hms(2014, 4, 6, 7, 8, 9).unwrap() + Days::new(5)),
352 "2014-04-11 07:08:09 +09:00"
353 );
354 assert_eq!(
355 format!("{}", DstTester.with_ymd_and_hms(2014, 4, 6, 7, 8, 9).unwrap() + Days::new(10)),
356 "2014-04-16 07:08:09 +08:00"
357 );
358
359 assert_eq!(
360 format!("{}", DstTester.with_ymd_and_hms(2014, 9, 6, 7, 8, 9).unwrap() + Days::new(5)),
361 "2014-09-11 07:08:09 +08:00"
362 );
363 assert_eq!(
364 format!("{}", DstTester.with_ymd_and_hms(2014, 9, 6, 7, 8, 9).unwrap() + Days::new(10)),
365 "2014-09-16 07:08:09 +09:00"
366 );
367 }
368
369 #[test]
370 fn test_datetime_sub_days() {
371 let est = FixedOffset::west_opt(5 * 60 * 60).unwrap();
372 let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
373
374 assert_eq!(
375 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Days::new(5)),
376 "2014-05-01 07:08:09 -05:00"
377 );
378 assert_eq!(
379 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Days::new(5)),
380 "2014-05-01 07:08:09 +09:00"
381 );
382
383 assert_eq!(
384 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Days::new(35)),
385 "2014-04-01 07:08:09 -05:00"
386 );
387 assert_eq!(
388 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Days::new(35)),
389 "2014-04-01 07:08:09 +09:00"
390 );
391 }
392
393 #[test]
394 fn test_datetime_add_months() {
395 let est = FixedOffset::west_opt(5 * 60 * 60).unwrap();
396 let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
397
398 assert_eq!(
399 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Months::new(1)),
400 "2014-06-06 07:08:09 -05:00"
401 );
402 assert_eq!(
403 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Months::new(1)),
404 "2014-06-06 07:08:09 +09:00"
405 );
406
407 assert_eq!(
408 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Months::new(5)),
409 "2014-10-06 07:08:09 -05:00"
410 );
411 assert_eq!(
412 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() + Months::new(5)),
413 "2014-10-06 07:08:09 +09:00"
414 );
415 }
416
417 #[test]
418 fn test_datetime_sub_months() {
419 let est = FixedOffset::west_opt(5 * 60 * 60).unwrap();
420 let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
421
422 assert_eq!(
423 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Months::new(1)),
424 "2014-04-06 07:08:09 -05:00"
425 );
426 assert_eq!(
427 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Months::new(1)),
428 "2014-04-06 07:08:09 +09:00"
429 );
430
431 assert_eq!(
432 format!("{}", est.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Months::new(5)),
433 "2013-12-06 07:08:09 -05:00"
434 );
435 assert_eq!(
436 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap() - Months::new(5)),
437 "2013-12-06 07:08:09 +09:00"
438 );
439 }
440
441 // local helper function to easily create a DateTime<FixedOffset>
442 #[allow(clippy::too_many_arguments)]
443 fn ymdhms(
444 fixedoffset: &FixedOffset,
445 year: i32,
446 month: u32,
447 day: u32,
448 hour: u32,
449 min: u32,
450 sec: u32,
451 ) -> DateTime<FixedOffset> {
452 fixedoffset.with_ymd_and_hms(year, month, day, hour, min, sec).unwrap()
453 }
454
455 // local helper function to easily create a DateTime<FixedOffset>
456 #[allow(clippy::too_many_arguments)]
457 fn ymdhms_milli(
458 fixedoffset: &FixedOffset,
459 year: i32,
460 month: u32,
461 day: u32,
462 hour: u32,
463 min: u32,
464 sec: u32,
465 milli: u32,
466 ) -> DateTime<FixedOffset> {
467 fixedoffset
468 .with_ymd_and_hms(year, month, day, hour, min, sec)
469 .unwrap()
470 .with_nanosecond(milli * 1_000_000)
471 .unwrap()
472 }
473
474 // local helper function to easily create a DateTime<FixedOffset>
475 #[allow(clippy::too_many_arguments)]
476 #[cfg(feature = "alloc")]
477 fn ymdhms_micro(
478 fixedoffset: &FixedOffset,
479 year: i32,
480 month: u32,
481 day: u32,
482 hour: u32,
483 min: u32,
484 sec: u32,
485 micro: u32,
486 ) -> DateTime<FixedOffset> {
487 fixedoffset
488 .with_ymd_and_hms(year, month, day, hour, min, sec)
489 .unwrap()
490 .with_nanosecond(micro * 1000)
491 .unwrap()
492 }
493
494 // local helper function to easily create a DateTime<FixedOffset>
495 #[allow(clippy::too_many_arguments)]
496 #[cfg(feature = "alloc")]
497 fn ymdhms_nano(
498 fixedoffset: &FixedOffset,
499 year: i32,
500 month: u32,
501 day: u32,
502 hour: u32,
503 min: u32,
504 sec: u32,
505 nano: u32,
506 ) -> DateTime<FixedOffset> {
507 fixedoffset
508 .with_ymd_and_hms(year, month, day, hour, min, sec)
509 .unwrap()
510 .with_nanosecond(nano)
511 .unwrap()
512 }
513
514 // local helper function to easily create a DateTime<Utc>
515 #[cfg(feature = "alloc")]
516 fn ymdhms_utc(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> DateTime<Utc> {
517 Utc.with_ymd_and_hms(year, month, day, hour, min, sec).unwrap()
518 }
519
520 // local helper function to easily create a DateTime<Utc>
521 fn ymdhms_milli_utc(
522 year: i32,
523 month: u32,
524 day: u32,
525 hour: u32,
526 min: u32,
527 sec: u32,
528 milli: u32,
529 ) -> DateTime<Utc> {
530 Utc.with_ymd_and_hms(year, month, day, hour, min, sec)
531 .unwrap()
532 .with_nanosecond(milli * 1_000_000)
533 .unwrap()
534 }
535
536 #[test]
537 fn test_datetime_offset() {
538 let est = FixedOffset::west_opt(5 * 60 * 60).unwrap();
539 let edt = FixedOffset::west_opt(4 * 60 * 60).unwrap();
540 let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
541
542 assert_eq!(
543 format!("{}", Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
544 "2014-05-06 07:08:09 UTC"
545 );
546 assert_eq!(
547 format!("{}", edt.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
548 "2014-05-06 07:08:09 -04:00"
549 );
550 assert_eq!(
551 format!("{}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
552 "2014-05-06 07:08:09 +09:00"
553 );
554 assert_eq!(
555 format!("{:?}", Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
556 "2014-05-06T07:08:09Z"
557 );
558 assert_eq!(
559 format!("{:?}", edt.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
560 "2014-05-06T07:08:09-04:00"
561 );
562 assert_eq!(
563 format!("{:?}", kst.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap()),
564 "2014-05-06T07:08:09+09:00"
565 );
566
567 // edge cases
568 assert_eq!(
569 format!("{:?}", Utc.with_ymd_and_hms(2014, 5, 6, 0, 0, 0).unwrap()),
570 "2014-05-06T00:00:00Z"
571 );
572 assert_eq!(
573 format!("{:?}", edt.with_ymd_and_hms(2014, 5, 6, 0, 0, 0).unwrap()),
574 "2014-05-06T00:00:00-04:00"
575 );
576 assert_eq!(
577 format!("{:?}", kst.with_ymd_and_hms(2014, 5, 6, 0, 0, 0).unwrap()),
578 "2014-05-06T00:00:00+09:00"
579 );
580 assert_eq!(
581 format!("{:?}", Utc.with_ymd_and_hms(2014, 5, 6, 23, 59, 59).unwrap()),
582 "2014-05-06T23:59:59Z"
583 );
584 assert_eq!(
585 format!("{:?}", edt.with_ymd_and_hms(2014, 5, 6, 23, 59, 59).unwrap()),
586 "2014-05-06T23:59:59-04:00"
587 );
588 assert_eq!(
589 format!("{:?}", kst.with_ymd_and_hms(2014, 5, 6, 23, 59, 59).unwrap()),
590 "2014-05-06T23:59:59+09:00"
591 );
592
593 let dt = Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap();
594 assert_eq!(dt, edt.with_ymd_and_hms(2014, 5, 6, 3, 8, 9).unwrap());
595 assert_eq!(
596 dt + TimeDelta::try_seconds(3600 + 60 + 1).unwrap(),
597 Utc.with_ymd_and_hms(2014, 5, 6, 8, 9, 10).unwrap()
598 );
599 assert_eq!(
600 dt.signed_duration_since(edt.with_ymd_and_hms(2014, 5, 6, 10, 11, 12).unwrap()),
601 TimeDelta::try_seconds(-7 * 3600 - 3 * 60 - 3).unwrap()
602 );
603
604 assert_eq!(*Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap().offset(), Utc);
605 assert_eq!(*edt.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap().offset(), edt);
606 assert!(*edt.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap().offset() != est);
607 }
608
609 #[test]
610 #[allow(clippy::needless_borrow, clippy::op_ref)]
611 fn signed_duration_since_autoref() {
612 let dt1 = Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap();
613 let dt2 = Utc.with_ymd_and_hms(2014, 3, 4, 5, 6, 7).unwrap();
614 let diff1 = dt1.signed_duration_since(dt2); // Copy/consume
615 #[allow(clippy::needless_borrows_for_generic_args)]
616 let diff2 = dt2.signed_duration_since(&dt1); // Take by reference
617 assert_eq!(diff1, -diff2);
618
619 let diff1 = dt1 - &dt2; // We can choose to subtract rhs by reference
620 let diff2 = dt2 - dt1; // Or consume rhs
621 assert_eq!(diff1, -diff2);
622 }
623
624 #[test]
625 fn test_datetime_date_and_time() {
626 let tz = FixedOffset::east_opt(5 * 60 * 60).unwrap();
627 let d = tz.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap();
628 assert_eq!(d.time(), NaiveTime::from_hms_opt(7, 8, 9).unwrap());
629 assert_eq!(d.date_naive(), NaiveDate::from_ymd_opt(2014, 5, 6).unwrap());
630
631 let tz = FixedOffset::east_opt(4 * 60 * 60).unwrap();
632 let d = tz.with_ymd_and_hms(2016, 5, 4, 3, 2, 1).unwrap();
633 assert_eq!(d.time(), NaiveTime::from_hms_opt(3, 2, 1).unwrap());
634 assert_eq!(d.date_naive(), NaiveDate::from_ymd_opt(2016, 5, 4).unwrap());
635
636 let tz = FixedOffset::west_opt(13 * 60 * 60).unwrap();
637 let d = tz.with_ymd_and_hms(2017, 8, 9, 12, 34, 56).unwrap();
638 assert_eq!(d.time(), NaiveTime::from_hms_opt(12, 34, 56).unwrap());
639 assert_eq!(d.date_naive(), NaiveDate::from_ymd_opt(2017, 8, 9).unwrap());
640
641 let utc_d = Utc.with_ymd_and_hms(2017, 8, 9, 12, 34, 56).unwrap();
642 assert!(utc_d < d);
643 }
644
645 #[test]
646 #[cfg(feature = "clock")]
647 fn test_datetime_with_timezone() {
648 let local_now = Local::now();
649 let utc_now = local_now.with_timezone(&Utc);
650 let local_now2 = utc_now.with_timezone(&Local);
651 assert_eq!(local_now, local_now2);
652 }
653
654 #[test]
655 #[cfg(feature = "alloc")]
656 fn test_datetime_rfc2822() {
657 let edt = FixedOffset::east_opt(5 * 60 * 60).unwrap();
658
659 // timezone 0
660 assert_eq!(
661 Utc.with_ymd_and_hms(2015, 2, 18, 23, 16, 9).unwrap().to_rfc2822(),
662 "Wed, 18 Feb 2015 23:16:09 +0000"
663 );
664 assert_eq!(
665 Utc.with_ymd_and_hms(2015, 2, 1, 23, 16, 9).unwrap().to_rfc2822(),
666 "Sun, 1 Feb 2015 23:16:09 +0000"
667 );
668 // timezone +05
669 assert_eq!(
670 edt.from_local_datetime(
671 &NaiveDate::from_ymd_opt(2015, 2, 18)
672 .unwrap()
673 .and_hms_milli_opt(23, 16, 9, 150)
674 .unwrap()
675 )
676 .unwrap()
677 .to_rfc2822(),
678 "Wed, 18 Feb 2015 23:16:09 +0500"
679 );
680 assert_eq!(
681 DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:59:60 +0500"),
682 Ok(edt
683 .from_local_datetime(
684 &NaiveDate::from_ymd_opt(2015, 2, 18)
685 .unwrap()
686 .and_hms_milli_opt(23, 59, 59, 1_000)
687 .unwrap()
688 )
689 .unwrap())
690 );
691 assert!(DateTime::parse_from_rfc2822("31 DEC 262143 23:59 -2359").is_err());
692 assert_eq!(
693 DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+05:00"),
694 Ok(edt
695 .from_local_datetime(
696 &NaiveDate::from_ymd_opt(2015, 2, 18)
697 .unwrap()
698 .and_hms_micro_opt(23, 59, 59, 1_234_567)
699 .unwrap()
700 )
701 .unwrap())
702 );
703 // seconds 60
704 assert_eq!(
705 edt.from_local_datetime(
706 &NaiveDate::from_ymd_opt(2015, 2, 18)
707 .unwrap()
708 .and_hms_micro_opt(23, 59, 59, 1_234_567)
709 .unwrap()
710 )
711 .unwrap()
712 .to_rfc2822(),
713 "Wed, 18 Feb 2015 23:59:60 +0500"
714 );
715
716 assert_eq!(
717 DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 +0000"),
718 Ok(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2015, 2, 18, 23, 16, 9).unwrap())
719 );
720 assert_eq!(
721 DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 -0000"),
722 Ok(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2015, 2, 18, 23, 16, 9).unwrap())
723 );
724 assert_eq!(
725 ymdhms_micro(&edt, 2015, 2, 18, 23, 59, 59, 1_234_567).to_rfc2822(),
726 "Wed, 18 Feb 2015 23:59:60 +0500"
727 );
728 assert_eq!(
729 DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:59:58 +0500"),
730 Ok(ymdhms(&edt, 2015, 2, 18, 23, 59, 58))
731 );
732 assert_ne!(
733 DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:59:58 +0500"),
734 Ok(ymdhms_milli(&edt, 2015, 2, 18, 23, 59, 58, 500))
735 );
736
737 // many varying whitespace intermixed
738 assert_eq!(
739 DateTime::parse_from_rfc2822(
740 "\t\t\tWed,\n\t\t18 \r\n\t\tFeb \u{3000} 2015\r\n\t\t\t23:59:58 \t+0500"
741 ),
742 Ok(ymdhms(&edt, 2015, 2, 18, 23, 59, 58))
743 );
744 // example from RFC 2822 Appendix A.5.
745 assert_eq!(
746 DateTime::parse_from_rfc2822(
747 "Thu,\n\t13\n Feb\n 1969\n 23:32\n -0330 (Newfoundland Time)"
748 ),
749 Ok(
750 ymdhms(&FixedOffset::east_opt(-3 * 60 * 60 - 30 * 60).unwrap(), 1969, 2, 13, 23, 32, 0,)
751 )
752 );
753 // example from RFC 2822 Appendix A.5. without trailing " (Newfoundland Time)"
754 assert_eq!(
755 DateTime::parse_from_rfc2822(
756 "Thu,\n\t13\n Feb\n 1969\n 23:32\n -0330"
757 ),
758 Ok(
759 ymdhms(&FixedOffset::east_opt(-3 * 60 * 60 - 30 * 60).unwrap(), 1969, 2, 13, 23, 32, 0,)
760 )
761 );
762
763 // bad year
764 assert!(DateTime::parse_from_rfc2822("31 DEC 262143 23:59 -2359").is_err());
765 // wrong format
766 assert!(DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 +00:00").is_err());
767 // full name day of week
768 assert!(DateTime::parse_from_rfc2822("Wednesday, 18 Feb 2015 23:16:09 +0000").is_err());
769 // full name day of week
770 assert!(DateTime::parse_from_rfc2822("Wednesday 18 Feb 2015 23:16:09 +0000").is_err());
771 // wrong day of week separator '.'
772 assert!(DateTime::parse_from_rfc2822("Wed. 18 Feb 2015 23:16:09 +0000").is_err());
773 // *trailing* space causes failure
774 assert!(DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 +0000 ").is_err());
775 }
776
777 #[test]
778 #[cfg(feature = "alloc")]
779 fn test_datetime_rfc3339() {
780 let edt5 = FixedOffset::east_opt(5 * 60 * 60).unwrap();
781 let edt0 = FixedOffset::east_opt(0).unwrap();
782
783 // timezone 0
784 assert_eq!(
785 Utc.with_ymd_and_hms(2015, 2, 18, 23, 16, 9).unwrap().to_rfc3339(),
786 "2015-02-18T23:16:09+00:00"
787 );
788 // timezone +05
789 assert_eq!(
790 edt5.from_local_datetime(
791 &NaiveDate::from_ymd_opt(2015, 2, 18)
792 .unwrap()
793 .and_hms_milli_opt(23, 16, 9, 150)
794 .unwrap()
795 )
796 .unwrap()
797 .to_rfc3339(),
798 "2015-02-18T23:16:09.150+05:00"
799 );
800
801 assert_eq!(ymdhms_utc(2015, 2, 18, 23, 16, 9).to_rfc3339(), "2015-02-18T23:16:09+00:00");
802 assert_eq!(
803 ymdhms_milli(&edt5, 2015, 2, 18, 23, 16, 9, 150).to_rfc3339(),
804 "2015-02-18T23:16:09.150+05:00"
805 );
806 assert_eq!(
807 ymdhms_micro(&edt5, 2015, 2, 18, 23, 59, 59, 1_234_567).to_rfc3339(),
808 "2015-02-18T23:59:60.234567+05:00"
809 );
810 assert_eq!(
811 DateTime::parse_from_rfc3339("2015-02-18T23:59:59.123+05:00"),
812 Ok(ymdhms_micro(&edt5, 2015, 2, 18, 23, 59, 59, 123_000))
813 );
814 assert_eq!(
815 DateTime::parse_from_rfc3339("2015-02-18T23:59:59.123456+05:00"),
816 Ok(ymdhms_micro(&edt5, 2015, 2, 18, 23, 59, 59, 123_456))
817 );
818 assert_eq!(
819 DateTime::parse_from_rfc3339("2015-02-18T23:59:59.123456789+05:00"),
820 Ok(ymdhms_nano(&edt5, 2015, 2, 18, 23, 59, 59, 123_456_789))
821 );
822 assert_eq!(
823 DateTime::parse_from_rfc3339("2015-02-18T23:16:09Z"),
824 Ok(ymdhms(&edt0, 2015, 2, 18, 23, 16, 9))
825 );
826
827 assert_eq!(
828 ymdhms_micro(&edt5, 2015, 2, 18, 23, 59, 59, 1_234_567).to_rfc3339(),
829 "2015-02-18T23:59:60.234567+05:00"
830 );
831 assert_eq!(
832 ymdhms_milli(&edt5, 2015, 2, 18, 23, 16, 9, 150).to_rfc3339(),
833 "2015-02-18T23:16:09.150+05:00"
834 );
835 assert_eq!(
836 DateTime::parse_from_rfc3339("2015-02-18T00:00:00.234567+05:00"),
837 Ok(ymdhms_micro(&edt5, 2015, 2, 18, 0, 0, 0, 234_567))
838 );
839 assert_eq!(
840 DateTime::parse_from_rfc3339("2015-02-18T23:16:09Z"),
841 Ok(ymdhms(&edt0, 2015, 2, 18, 23, 16, 9))
842 );
843 assert_eq!(
844 DateTime::parse_from_rfc3339("2015-02-18 23:59:60.234567+05:00"),
845 Ok(ymdhms_micro(&edt5, 2015, 2, 18, 23, 59, 59, 1_234_567))
846 );
847 assert_eq!(ymdhms_utc(2015, 2, 18, 23, 16, 9).to_rfc3339(), "2015-02-18T23:16:09+00:00");
848
849 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567 +05:00").is_err());
850 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:059:60.234567+05:00").is_err());
851 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+05:00PST").is_err());
852 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+PST").is_err());
853 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567PST").is_err());
854 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+0500").is_err());
855 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+05:00:00").is_err());
856 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567:+05:00").is_err());
857 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567+05:00 ").is_err());
858 assert!(DateTime::parse_from_rfc3339(" 2015-02-18T23:59:60.234567+05:00").is_err());
859 assert!(DateTime::parse_from_rfc3339("2015- 02-18T23:59:60.234567+05:00").is_err());
860 assert!(DateTime::parse_from_rfc3339("2015-02-18T23:59:60.234567A+05:00").is_err());
861 }
862
863 #[test]
864 #[cfg(feature = "alloc")]
865 fn test_rfc3339_opts() {
866 use crate::SecondsFormat::*;
867 let pst = FixedOffset::east_opt(8 * 60 * 60).unwrap();
868 let dt = pst
869 .from_local_datetime(
870 &NaiveDate::from_ymd_opt(2018, 1, 11)
871 .unwrap()
872 .and_hms_nano_opt(10, 5, 13, 84_660_000)
873 .unwrap(),
874 )
875 .unwrap();
876 assert_eq!(dt.to_rfc3339_opts(Secs, false), "2018-01-11T10:05:13+08:00");
877 assert_eq!(dt.to_rfc3339_opts(Secs, true), "2018-01-11T10:05:13+08:00");
878 assert_eq!(dt.to_rfc3339_opts(Millis, false), "2018-01-11T10:05:13.084+08:00");
879 assert_eq!(dt.to_rfc3339_opts(Micros, false), "2018-01-11T10:05:13.084660+08:00");
880 assert_eq!(dt.to_rfc3339_opts(Nanos, false), "2018-01-11T10:05:13.084660000+08:00");
881 assert_eq!(dt.to_rfc3339_opts(AutoSi, false), "2018-01-11T10:05:13.084660+08:00");
882
883 let ut = dt.naive_utc().and_utc();
884 assert_eq!(ut.to_rfc3339_opts(Secs, false), "2018-01-11T02:05:13+00:00");
885 assert_eq!(ut.to_rfc3339_opts(Secs, true), "2018-01-11T02:05:13Z");
886 assert_eq!(ut.to_rfc3339_opts(Millis, false), "2018-01-11T02:05:13.084+00:00");
887 assert_eq!(ut.to_rfc3339_opts(Millis, true), "2018-01-11T02:05:13.084Z");
888 assert_eq!(ut.to_rfc3339_opts(Micros, true), "2018-01-11T02:05:13.084660Z");
889 assert_eq!(ut.to_rfc3339_opts(Nanos, true), "2018-01-11T02:05:13.084660000Z");
890 assert_eq!(ut.to_rfc3339_opts(AutoSi, true), "2018-01-11T02:05:13.084660Z");
891 }
892
893 #[test]
894 #[should_panic]
895 #[cfg(feature = "alloc")]
896 fn test_rfc3339_opts_nonexhaustive() {
897 use crate::SecondsFormat;
898 let dt = Utc.with_ymd_and_hms(1999, 10, 9, 1, 2, 3).unwrap();
899 let _ = dt.to_rfc3339_opts(SecondsFormat::__NonExhaustive, true);
900 }
901
902 #[test]
903 fn test_datetime_from_str() {
904 assert_eq!(
905 "2015-02-18T23:16:9.15Z".parse::<DateTime<FixedOffset>>(),
906 Ok(FixedOffset::east_opt(0)
907 .unwrap()
908 .from_local_datetime(
909 &NaiveDate::from_ymd_opt(2015, 2, 18)
910 .unwrap()
911 .and_hms_milli_opt(23, 16, 9, 150)
912 .unwrap()
913 )
914 .unwrap())
915 );
916 assert_eq!(
917 "2015-02-18T23:16:9.15Z".parse::<DateTime<Utc>>(),
918 Ok(Utc
919 .from_local_datetime(
920 &NaiveDate::from_ymd_opt(2015, 2, 18)
921 .unwrap()
922 .and_hms_milli_opt(23, 16, 9, 150)
923 .unwrap()
924 )
925 .unwrap())
926 );
927 assert_eq!(
928 "2015-02-18T23:16:9.15 UTC".parse::<DateTime<Utc>>(),
929 Ok(Utc
930 .from_local_datetime(
931 &NaiveDate::from_ymd_opt(2015, 2, 18)
932 .unwrap()
933 .and_hms_milli_opt(23, 16, 9, 150)
934 .unwrap()
935 )
936 .unwrap())
937 );
938 assert_eq!(
939 "2015-02-18T23:16:9.15UTC".parse::<DateTime<Utc>>(),
940 Ok(Utc
941 .from_local_datetime(
942 &NaiveDate::from_ymd_opt(2015, 2, 18)
943 .unwrap()
944 .and_hms_milli_opt(23, 16, 9, 150)
945 .unwrap()
946 )
947 .unwrap())
948 );
949 assert_eq!(
950 "2015-02-18T23:16:9.15Utc".parse::<DateTime<Utc>>(),
951 Ok(Utc
952 .from_local_datetime(
953 &NaiveDate::from_ymd_opt(2015, 2, 18)
954 .unwrap()
955 .and_hms_milli_opt(23, 16, 9, 150)
956 .unwrap()
957 )
958 .unwrap())
959 );
960
961 assert_eq!(
962 "2015-2-18T23:16:9.15Z".parse::<DateTime<FixedOffset>>(),
963 Ok(FixedOffset::east_opt(0)
964 .unwrap()
965 .from_local_datetime(
966 &NaiveDate::from_ymd_opt(2015, 2, 18)
967 .unwrap()
968 .and_hms_milli_opt(23, 16, 9, 150)
969 .unwrap()
970 )
971 .unwrap())
972 );
973 assert_eq!(
974 "2015-2-18T13:16:9.15-10:00".parse::<DateTime<FixedOffset>>(),
975 Ok(FixedOffset::west_opt(10 * 3600)
976 .unwrap()
977 .from_local_datetime(
978 &NaiveDate::from_ymd_opt(2015, 2, 18)
979 .unwrap()
980 .and_hms_milli_opt(13, 16, 9, 150)
981 .unwrap()
982 )
983 .unwrap())
984 );
985 assert!("2015-2-18T23:16:9.15".parse::<DateTime<FixedOffset>>().is_err());
986
987 assert_eq!(
988 "2015-2-18T23:16:9.15Z".parse::<DateTime<Utc>>(),
989 Ok(Utc
990 .from_local_datetime(
991 &NaiveDate::from_ymd_opt(2015, 2, 18)
992 .unwrap()
993 .and_hms_milli_opt(23, 16, 9, 150)
994 .unwrap()
995 )
996 .unwrap())
997 );
998 assert_eq!(
999 "2015-2-18T13:16:9.15-10:00".parse::<DateTime<Utc>>(),
1000 Ok(Utc
1001 .from_local_datetime(
1002 &NaiveDate::from_ymd_opt(2015, 2, 18)
1003 .unwrap()
1004 .and_hms_milli_opt(23, 16, 9, 150)
1005 .unwrap()
1006 )
1007 .unwrap())
1008 );
1009 assert!("2015-2-18T23:16:9.15".parse::<DateTime<Utc>>().is_err());
1010 assert!("2015-02-18T23:16:9.15øøø".parse::<DateTime<Utc>>().is_err());
1011
1012 // no test for `DateTime<Local>`, we cannot verify that much.
1013 }
1014
1015 #[test]
1016 fn test_parse_datetime_utc() {
1017 // valid cases
1018 let valid = [
1019 "2001-02-03T04:05:06Z",
1020 "2001-02-03T04:05:06+0000",
1021 "2001-02-03T04:05:06-00:00",
1022 "2001-02-03T04:05:06-01:00",
1023 "2012-12-12 12:12:12Z",
1024 "2012-12-12t12:12:12Z",
1025 "2012-12-12T12:12:12Z",
1026 "2012 -12-12T12:12:12Z",
1027 "2012 -12-12T12:12:12Z",
1028 "2012- 12-12T12:12:12Z",
1029 "2012- 12-12T12:12:12Z",
1030 "2012-12-12T 12:12:12Z",
1031 "2012-12-12T12 :12:12Z",
1032 "2012-12-12T12 :12:12Z",
1033 "2012-12-12T12: 12:12Z",
1034 "2012-12-12T12: 12:12Z",
1035 "2012-12-12T12 : 12:12Z",
1036 "2012-12-12T12:12:12Z ",
1037 " 2012-12-12T12:12:12Z",
1038 "2015-02-18T23:16:09.153Z",
1039 "2015-2-18T23:16:09.153Z",
1040 "+2015-2-18T23:16:09.153Z",
1041 "-77-02-18T23:16:09Z",
1042 "+82701-05-6T15:9:60.898989898989Z",
1043 ];
1044 for &s in &valid {
1045 eprintln!("test_parse_datetime_utc valid {s:?}");
1046 let d = match s.parse::<DateTime<Utc>>() {
1047 Ok(d) => d,
1048 Err(e) => panic!("parsing `{s}` has failed: {e}"),
1049 };
1050 let s_ = format!("{d:?}");
1051 // `s` and `s_` may differ, but `s.parse()` and `s_.parse()` must be same
1052 let d_ = match s_.parse::<DateTime<Utc>>() {
1053 Ok(d) => d,
1054 Err(e) => {
1055 panic!("`{s}` is parsed into `{d:?}`, but reparsing that has failed: {e}")
1056 }
1057 };
1058 assert!(
1059 d == d_,
1060 "`{s}` is parsed into `{d:?}`, but reparsed result `{d_:?}` does not match"
1061 );
1062 }
1063
1064 // some invalid cases
1065 // since `ParseErrorKind` is private, all we can do is to check if there was an error
1066 let invalid = [
1067 "", // empty
1068 "Z", // missing data
1069 "15Z", // missing data
1070 "15:8:9Z", // missing date
1071 "15-8-9Z", // missing time or date
1072 "Fri, 09 Aug 2013 23:54:35 GMT", // valid datetime, wrong format
1073 "Sat Jun 30 23:59:60 2012", // valid datetime, wrong format
1074 "1441497364.649", // valid datetime, wrong format
1075 "+1441497364.649", // valid datetime, wrong format
1076 "+1441497364", // valid datetime, wrong format
1077 "+1441497364Z", // valid datetime, wrong format
1078 "2014/02/03 04:05:06Z", // valid datetime, wrong format
1079 "2001-02-03T04:05:0600:00", // valid datetime, timezone too close
1080 "2015-15-15T15:15:15Z", // invalid datetime
1081 "2012-12-12T12:12:12x", // invalid timezone
1082 "2012-123-12T12:12:12Z", // invalid month
1083 "2012-12-77T12:12:12Z", // invalid day
1084 "2012-12-12T26:12:12Z", // invalid hour
1085 "2012-12-12T12:61:12Z", // invalid minute
1086 "2012-12-12T12:12:62Z", // invalid second
1087 "2012-12-12 T12:12:12Z", // space after date
1088 "2012-12-12T12:12:12ZZ", // trailing literal 'Z'
1089 "+802701-12-12T12:12:12Z", // invalid year (out of bounds)
1090 "+ 2012-12-12T12:12:12Z", // invalid space before year
1091 " +82701 - 05 - 6 T 15 : 9 : 60.898989898989 Z", // valid datetime, wrong format
1092 ];
1093 for &s in &invalid {
1094 eprintln!("test_parse_datetime_utc invalid {s:?}");
1095 assert!(s.parse::<DateTime<Utc>>().is_err());
1096 }
1097 }
1098
1099 #[test]
1100 fn test_parse_from_str() {
1101 let edt = FixedOffset::east_opt(570 * 60).unwrap();
1102 let edt0 = FixedOffset::east_opt(0).unwrap();
1103 let wdt = FixedOffset::west_opt(10 * 3600).unwrap();
1104 assert_eq!(
1105 DateTime::parse_from_str("2014-5-7T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
1106 Ok(ymdhms(&edt, 2014, 5, 7, 12, 34, 56))
1107 ); // ignore offset
1108 assert!(DateTime::parse_from_str("20140507000000", "%Y%m%d%H%M%S").is_err()); // no offset
1109 assert!(
1110 DateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT")
1111 .is_err()
1112 );
1113 assert_eq!(
1114 DateTime::parse_from_str("0", "%s").unwrap(),
1115 DateTime::from_timestamp(0, 0).unwrap().fixed_offset()
1116 );
1117
1118 assert_eq!(
1119 "2015-02-18T23:16:9.15Z".parse::<DateTime<FixedOffset>>(),
1120 Ok(ymdhms_milli(&edt0, 2015, 2, 18, 23, 16, 9, 150))
1121 );
1122 assert_eq!(
1123 "2015-02-18T23:16:9.15Z".parse::<DateTime<Utc>>(),
1124 Ok(ymdhms_milli_utc(2015, 2, 18, 23, 16, 9, 150)),
1125 );
1126 assert_eq!(
1127 "2015-02-18T23:16:9.15 UTC".parse::<DateTime<Utc>>(),
1128 Ok(ymdhms_milli_utc(2015, 2, 18, 23, 16, 9, 150))
1129 );
1130 assert_eq!(
1131 "2015-02-18T23:16:9.15UTC".parse::<DateTime<Utc>>(),
1132 Ok(ymdhms_milli_utc(2015, 2, 18, 23, 16, 9, 150))
1133 );
1134
1135 assert_eq!(
1136 "2015-2-18T23:16:9.15Z".parse::<DateTime<FixedOffset>>(),
1137 Ok(ymdhms_milli(&edt0, 2015, 2, 18, 23, 16, 9, 150))
1138 );
1139 assert_eq!(
1140 "2015-2-18T13:16:9.15-10:00".parse::<DateTime<FixedOffset>>(),
1141 Ok(ymdhms_milli(&wdt, 2015, 2, 18, 13, 16, 9, 150))
1142 );
1143 assert!("2015-2-18T23:16:9.15".parse::<DateTime<FixedOffset>>().is_err());
1144
1145 assert_eq!(
1146 "2015-2-18T23:16:9.15Z".parse::<DateTime<Utc>>(),
1147 Ok(ymdhms_milli_utc(2015, 2, 18, 23, 16, 9, 150))
1148 );
1149 assert_eq!(
1150 "2015-2-18T13:16:9.15-10:00".parse::<DateTime<Utc>>(),
1151 Ok(ymdhms_milli_utc(2015, 2, 18, 23, 16, 9, 150))
1152 );
1153 assert!("2015-2-18T23:16:9.15".parse::<DateTime<Utc>>().is_err());
1154
1155 // no test for `DateTime<Local>`, we cannot verify that much.
1156 }
1157
1158 #[test]
1159 fn test_datetime_parse_from_str() {
1160 let dt = ymdhms(&FixedOffset::east_opt(-9 * 60 * 60).unwrap(), 2013, 8, 9, 23, 54, 35);
1161 let parse = DateTime::parse_from_str;
1162
1163 // timezone variations
1164
1165 //
1166 // %Z
1167 //
1168 // wrong timezone format
1169 assert!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %Z").is_err());
1170 // bad timezone data?
1171 assert!(parse("Aug 09 2013 23:54:35 PST", "%b %d %Y %H:%M:%S %Z").is_err());
1172 // bad timezone data
1173 assert!(parse("Aug 09 2013 23:54:35 XXXXX", "%b %d %Y %H:%M:%S %Z").is_err());
1174
1175 //
1176 // %z
1177 //
1178 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %z"), Ok(dt));
1179 assert_eq!(parse("Aug 09 2013 23:54:35 -09 00", "%b %d %Y %H:%M:%S %z"), Ok(dt));
1180 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %z"), Ok(dt));
1181 assert_eq!(parse("Aug 09 2013 23:54:35 -09 : 00", "%b %d %Y %H:%M:%S %z"), Ok(dt));
1182 assert_eq!(parse("Aug 09 2013 23:54:35 --0900", "%b %d %Y %H:%M:%S -%z"), Ok(dt));
1183 assert_eq!(parse("Aug 09 2013 23:54:35 +-0900", "%b %d %Y %H:%M:%S +%z"), Ok(dt));
1184 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00 ", "%b %d %Y %H:%M:%S %z "), Ok(dt));
1185 // trailing newline after timezone
1186 assert!(parse("Aug 09 2013 23:54:35 -09:00\n", "%b %d %Y %H:%M:%S %z").is_err());
1187 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00\n", "%b %d %Y %H:%M:%S %z "), Ok(dt));
1188 // trailing colon
1189 assert!(parse("Aug 09 2013 23:54:35 -09:00:", "%b %d %Y %H:%M:%S %z").is_err());
1190 // trailing colon with space
1191 assert!(parse("Aug 09 2013 23:54:35 -09:00: ", "%b %d %Y %H:%M:%S %z ").is_err());
1192 // trailing colon, mismatch space
1193 assert!(parse("Aug 09 2013 23:54:35 -09:00:", "%b %d %Y %H:%M:%S %z ").is_err());
1194 // wrong timezone data
1195 assert!(parse("Aug 09 2013 23:54:35 -09", "%b %d %Y %H:%M:%S %z").is_err());
1196 assert_eq!(parse("Aug 09 2013 23:54:35 -09::00", "%b %d %Y %H:%M:%S %z"), Ok(dt));
1197 assert_eq!(parse("Aug 09 2013 23:54:35 -0900::", "%b %d %Y %H:%M:%S %z::"), Ok(dt));
1198 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00:00", "%b %d %Y %H:%M:%S %z:00"), Ok(dt));
1199 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00:00 ", "%b %d %Y %H:%M:%S %z:00 "), Ok(dt));
1200
1201 //
1202 // %:z
1203 //
1204 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1205 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1206 assert_eq!(parse("Aug 09 2013 23:54:35 -09 00", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1207 assert_eq!(parse("Aug 09 2013 23:54:35 -09 : 00", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1208 assert_eq!(parse("Aug 09 2013 23:54:35 -09 : 00:", "%b %d %Y %H:%M:%S %:z:"), Ok(dt));
1209 // wrong timezone data
1210 assert!(parse("Aug 09 2013 23:54:35 -09", "%b %d %Y %H:%M:%S %:z").is_err());
1211 assert_eq!(parse("Aug 09 2013 23:54:35 -09::00", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1212 // timezone data hs too many colons
1213 assert!(parse("Aug 09 2013 23:54:35 -09:00:", "%b %d %Y %H:%M:%S %:z").is_err());
1214 // timezone data hs too many colons
1215 assert!(parse("Aug 09 2013 23:54:35 -09:00::", "%b %d %Y %H:%M:%S %:z").is_err());
1216 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00::", "%b %d %Y %H:%M:%S %:z::"), Ok(dt));
1217
1218 //
1219 // %::z
1220 //
1221 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %::z"), Ok(dt));
1222 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %::z"), Ok(dt));
1223 assert_eq!(parse("Aug 09 2013 23:54:35 -09 : 00", "%b %d %Y %H:%M:%S %::z"), Ok(dt));
1224 // mismatching colon expectations
1225 assert!(parse("Aug 09 2013 23:54:35 -09:00:00", "%b %d %Y %H:%M:%S %::z").is_err());
1226 assert_eq!(parse("Aug 09 2013 23:54:35 -09::00", "%b %d %Y %H:%M:%S %::z"), Ok(dt));
1227 assert_eq!(parse("Aug 09 2013 23:54:35 -09::00", "%b %d %Y %H:%M:%S %:z"), Ok(dt));
1228 // wrong timezone data
1229 assert!(parse("Aug 09 2013 23:54:35 -09", "%b %d %Y %H:%M:%S %::z").is_err());
1230 assert_eq!(parse("Aug 09 2013 23:54:35 -09001234", "%b %d %Y %H:%M:%S %::z1234"), Ok(dt));
1231 assert_eq!(parse("Aug 09 2013 23:54:35 -09:001234", "%b %d %Y %H:%M:%S %::z1234"), Ok(dt));
1232 assert_eq!(parse("Aug 09 2013 23:54:35 -0900 ", "%b %d %Y %H:%M:%S %::z "), Ok(dt));
1233 assert_eq!(parse("Aug 09 2013 23:54:35 -0900\t\n", "%b %d %Y %H:%M:%S %::z\t\n"), Ok(dt));
1234 assert_eq!(parse("Aug 09 2013 23:54:35 -0900:", "%b %d %Y %H:%M:%S %::z:"), Ok(dt));
1235 assert_eq!(parse("Aug 09 2013 23:54:35 :-0900:0", "%b %d %Y %H:%M:%S :%::z:0"), Ok(dt));
1236 // mismatching colons and spaces
1237 assert!(parse("Aug 09 2013 23:54:35 :-0900: ", "%b %d %Y %H:%M:%S :%::z::").is_err());
1238 // mismatching colons expectations
1239 assert!(parse("Aug 09 2013 23:54:35 -09:00:00", "%b %d %Y %H:%M:%S %::z").is_err());
1240 assert_eq!(parse("Aug 09 2013 -0900: 23:54:35", "%b %d %Y %::z: %H:%M:%S"), Ok(dt));
1241 assert_eq!(parse("Aug 09 2013 :-0900:0 23:54:35", "%b %d %Y :%::z:0 %H:%M:%S"), Ok(dt));
1242 // mismatching colons expectations mid-string
1243 assert!(parse("Aug 09 2013 :-0900: 23:54:35", "%b %d %Y :%::z %H:%M:%S").is_err());
1244 // mismatching colons expectations, before end
1245 assert!(parse("Aug 09 2013 23:54:35 -09:00:00 ", "%b %d %Y %H:%M:%S %::z ").is_err());
1246
1247 //
1248 // %:::z
1249 //
1250 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %:::z"), Ok(dt));
1251 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %:::z"), Ok(dt));
1252 assert_eq!(parse("Aug 09 2013 23:54:35 -0900 ", "%b %d %Y %H:%M:%S %:::z "), Ok(dt));
1253 // wrong timezone data
1254 assert!(parse("Aug 09 2013 23:54:35 -09", "%b %d %Y %H:%M:%S %:::z").is_err());
1255
1256 //
1257 // %::::z
1258 //
1259 // too many colons
1260 assert!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %::::z").is_err());
1261 // too many colons
1262 assert!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %::::z").is_err());
1263 // too many colons
1264 assert!(parse("Aug 09 2013 23:54:35 -09:00:", "%b %d %Y %H:%M:%S %::::z").is_err());
1265 // too many colons
1266 assert!(parse("Aug 09 2013 23:54:35 -09:00:00", "%b %d %Y %H:%M:%S %::::z").is_err());
1267
1268 //
1269 // %#z
1270 //
1271 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00", "%b %d %Y %H:%M:%S %#z"), Ok(dt));
1272 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %#z"), Ok(dt));
1273 assert_eq!(parse("Aug 09 2013 23:54:35 -09:00 ", "%b %d %Y %H:%M:%S %#z "), Ok(dt));
1274 assert_eq!(parse("Aug 09 2013 23:54:35 -0900 ", "%b %d %Y %H:%M:%S %#z "), Ok(dt));
1275 assert_eq!(parse("Aug 09 2013 23:54:35 -09", "%b %d %Y %H:%M:%S %#z"), Ok(dt));
1276 assert_eq!(parse("Aug 09 2013 23:54:35 -0900", "%b %d %Y %H:%M:%S %#z"), Ok(dt));
1277 assert_eq!(parse("Aug 09 2013 23:54:35 -09:", "%b %d %Y %H:%M:%S %#z"), Ok(dt));
1278 assert_eq!(parse("Aug 09 2013 23:54:35 -09: ", "%b %d %Y %H:%M:%S %#z "), Ok(dt));
1279 assert_eq!(parse("Aug 09 2013 23:54:35+-09", "%b %d %Y %H:%M:%S+%#z"), Ok(dt));
1280 assert_eq!(parse("Aug 09 2013 23:54:35--09", "%b %d %Y %H:%M:%S-%#z"), Ok(dt));
1281 assert_eq!(parse("Aug 09 2013 -09:00 23:54:35", "%b %d %Y %#z%H:%M:%S"), Ok(dt));
1282 assert_eq!(parse("Aug 09 2013 -0900 23:54:35", "%b %d %Y %#z%H:%M:%S"), Ok(dt));
1283 assert_eq!(parse("Aug 09 2013 -090023:54:35", "%b %d %Y %#z%H:%M:%S"), Ok(dt));
1284 assert_eq!(parse("Aug 09 2013 -09:0023:54:35", "%b %d %Y %#z%H:%M:%S"), Ok(dt));
1285 // timezone with partial minutes adjacent hours
1286 assert_ne!(parse("Aug 09 2013 -09023:54:35", "%b %d %Y %#z%H:%M:%S"), Ok(dt));
1287 // bad timezone data
1288 assert!(parse("Aug 09 2013 23:54:35 -09:00:00", "%b %d %Y %H:%M:%S %#z").is_err());
1289 // bad timezone data (partial minutes)
1290 assert!(parse("Aug 09 2013 23:54:35 -090", "%b %d %Y %H:%M:%S %#z").is_err());
1291 // bad timezone data (partial minutes) with trailing space
1292 assert!(parse("Aug 09 2013 23:54:35 -090 ", "%b %d %Y %H:%M:%S %#z ").is_err());
1293 // bad timezone data (partial minutes) mid-string
1294 assert!(parse("Aug 09 2013 -090 23:54:35", "%b %d %Y %#z %H:%M:%S").is_err());
1295 // bad timezone data
1296 assert!(parse("Aug 09 2013 -09:00:00 23:54:35", "%b %d %Y %#z %H:%M:%S").is_err());
1297 // timezone data ambiguous with hours
1298 assert!(parse("Aug 09 2013 -09:00:23:54:35", "%b %d %Y %#z%H:%M:%S").is_err());
1299 }
1300
1301 #[test]
1302 fn test_to_string_round_trip() {
1303 let dt = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
1304 let _dt: DateTime<Utc> = dt.to_string().parse().unwrap();
1305
1306 let ndt_fixed = dt.with_timezone(&FixedOffset::east_opt(3600).unwrap());
1307 let _dt: DateTime<FixedOffset> = ndt_fixed.to_string().parse().unwrap();
1308
1309 let ndt_fixed = dt.with_timezone(&FixedOffset::east_opt(0).unwrap());
1310 let _dt: DateTime<FixedOffset> = ndt_fixed.to_string().parse().unwrap();
1311 }
1312
1313 #[test]
1314 #[cfg(feature = "clock")]
1315 fn test_to_string_round_trip_with_local() {
1316 let ndt = Local::now();
1317 let _dt: DateTime<FixedOffset> = ndt.to_string().parse().unwrap();
1318 }
1319
1320 #[test]
1321 #[cfg(feature = "clock")]
1322 fn test_datetime_format_with_local() {
1323 // if we are not around the year boundary, local and UTC date should have the same year
1324 let dt = Local::now().with_month(5).unwrap();
1325 assert_eq!(dt.format("%Y").to_string(), dt.with_timezone(&Utc).format("%Y").to_string());
1326 }
1327
1328 #[test]
1329 fn test_datetime_is_send_and_copy() {
1330 #[derive(Clone)]
1331 struct Tz {
1332 _not_send: *const i32,
1333 }
1334 impl TimeZone for Tz {
1335 type Offset = Off;
1336
1337 fn from_offset(_: &Self::Offset) -> Self {
1338 unimplemented!()
1339 }
1340 fn offset_from_local_date(&self, _: &NaiveDate) -> crate::MappedLocalTime<Self::Offset> {
1341 unimplemented!()
1342 }
1343 fn offset_from_local_datetime(
1344 &self,
1345 _: &NaiveDateTime,
1346 ) -> crate::MappedLocalTime<Self::Offset> {
1347 unimplemented!()
1348 }
1349 fn offset_from_utc_date(&self, _: &NaiveDate) -> Self::Offset {
1350 unimplemented!()
1351 }
1352 fn offset_from_utc_datetime(&self, _: &NaiveDateTime) -> Self::Offset {
1353 unimplemented!()
1354 }
1355 }
1356
1357 #[derive(Copy, Clone, Debug)]
1358 struct Off(());
1359 impl Offset for Off {
1360 fn fix(&self) -> FixedOffset {
1361 unimplemented!()
1362 }
1363 }
1364
1365 fn _assert_send_copy<T: Send + Copy>() {}
1366 // `DateTime` is `Send + Copy` if the offset is.
1367 _assert_send_copy::<DateTime<Tz>>();
1368 }
1369
1370 #[test]
1371 fn test_subsecond_part() {
1372 let datetime = Utc
1373 .from_local_datetime(
1374 &NaiveDate::from_ymd_opt(2014, 7, 8)
1375 .unwrap()
1376 .and_hms_nano_opt(9, 10, 11, 1234567)
1377 .unwrap(),
1378 )
1379 .unwrap();
1380
1381 assert_eq!(1, datetime.timestamp_subsec_millis());
1382 assert_eq!(1234, datetime.timestamp_subsec_micros());
1383 assert_eq!(1234567, datetime.timestamp_subsec_nanos());
1384 }
1385
1386 // Some targets, such as `wasm32-wasi`, have a problematic definition of `SystemTime`, such as an
1387 // `i32` (year 2035 problem), or an `u64` (no values before `UNIX-EPOCH`).
1388 // See https://github.com/rust-lang/rust/issues/44394.
1389 #[test]
1390 #[cfg(all(feature = "std", not(all(target_arch = "wasm32", target_os = "wasi"))))]
1391 fn test_from_system_time() {
1392 use std::time::{Duration, SystemTime, UNIX_EPOCH};
1393
1394 let nanos = 999_999_000;
1395
1396 let epoch = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap();
1397
1398 // SystemTime -> DateTime<Utc>
1399 assert_eq!(DateTime::<Utc>::from(UNIX_EPOCH), epoch);
1400 assert_eq!(
1401 DateTime::<Utc>::from(UNIX_EPOCH + Duration::new(999_999_999, nanos)),
1402 Utc.from_local_datetime(
1403 &NaiveDate::from_ymd_opt(2001, 9, 9)
1404 .unwrap()
1405 .and_hms_nano_opt(1, 46, 39, nanos)
1406 .unwrap()
1407 )
1408 .unwrap()
1409 );
1410 assert_eq!(
1411 DateTime::<Utc>::from(UNIX_EPOCH - Duration::new(999_999_999, nanos)),
1412 Utc.from_local_datetime(
1413 &NaiveDate::from_ymd_opt(1938, 4, 24)
1414 .unwrap()
1415 .and_hms_nano_opt(22, 13, 20, 1_000)
1416 .unwrap()
1417 )
1418 .unwrap()
1419 );
1420
1421 // DateTime<Utc> -> SystemTime
1422 assert_eq!(SystemTime::from(epoch), UNIX_EPOCH);
1423 assert_eq!(
1424 SystemTime::from(
1425 Utc.from_local_datetime(
1426 &NaiveDate::from_ymd_opt(2001, 9, 9)
1427 .unwrap()
1428 .and_hms_nano_opt(1, 46, 39, nanos)
1429 .unwrap()
1430 )
1431 .unwrap()
1432 ),
1433 UNIX_EPOCH + Duration::new(999_999_999, nanos)
1434 );
1435 assert_eq!(
1436 SystemTime::from(
1437 Utc.from_local_datetime(
1438 &NaiveDate::from_ymd_opt(1938, 4, 24)
1439 .unwrap()
1440 .and_hms_nano_opt(22, 13, 20, 1_000)
1441 .unwrap()
1442 )
1443 .unwrap()
1444 ),
1445 UNIX_EPOCH - Duration::new(999_999_999, nanos)
1446 );
1447
1448 // DateTime<any tz> -> SystemTime (via `with_timezone`)
1449 #[cfg(feature = "clock")]
1450 {
1451 assert_eq!(SystemTime::from(epoch.with_timezone(&Local)), UNIX_EPOCH);
1452 }
1453 assert_eq!(
1454 SystemTime::from(epoch.with_timezone(&FixedOffset::east_opt(32400).unwrap())),
1455 UNIX_EPOCH
1456 );
1457 assert_eq!(
1458 SystemTime::from(epoch.with_timezone(&FixedOffset::west_opt(28800).unwrap())),
1459 UNIX_EPOCH
1460 );
1461 }
1462
1463 #[test]
1464 #[allow(deprecated)]
1465 fn test_datetime_from_local() {
1466 // 2000-01-12T02:00:00Z
1467 let naivedatetime_utc =
1468 NaiveDate::from_ymd_opt(2000, 1, 12).unwrap().and_hms_opt(2, 0, 0).unwrap();
1469 let datetime_utc = DateTime::<Utc>::from_utc(naivedatetime_utc, Utc);
1470
1471 // 2000-01-12T10:00:00+8:00:00
1472 let timezone_east = FixedOffset::east_opt(8 * 60 * 60).unwrap();
1473 let naivedatetime_east =
1474 NaiveDate::from_ymd_opt(2000, 1, 12).unwrap().and_hms_opt(10, 0, 0).unwrap();
1475 let datetime_east = DateTime::<FixedOffset>::from_local(naivedatetime_east, timezone_east);
1476
1477 // 2000-01-11T19:00:00-7:00:00
1478 let timezone_west = FixedOffset::west_opt(7 * 60 * 60).unwrap();
1479 let naivedatetime_west =
1480 NaiveDate::from_ymd_opt(2000, 1, 11).unwrap().and_hms_opt(19, 0, 0).unwrap();
1481 let datetime_west = DateTime::<FixedOffset>::from_local(naivedatetime_west, timezone_west);
1482
1483 assert_eq!(datetime_east, datetime_utc.with_timezone(&timezone_east));
1484 assert_eq!(datetime_west, datetime_utc.with_timezone(&timezone_west));
1485 }
1486
1487 #[test]
1488 #[cfg(feature = "clock")]
1489 fn test_datetime_before_windows_api_limits() {
1490 // dt corresponds to `FILETIME = 147221225472` from issue 651.
1491 // (https://github.com/chronotope/chrono/issues/651)
1492 // This used to fail on Windows for timezones with an offset of -5:00 or greater.
1493 // The API limits years to 1601..=30827.
1494 let dt = NaiveDate::from_ymd_opt(1601, 1, 1).unwrap().and_hms_milli_opt(4, 5, 22, 122).unwrap();
1495 let local_dt = Local.from_utc_datetime(&dt);
1496 dbg!(local_dt);
1497 }
1498
1499 #[test]
1500 #[cfg(feature = "clock")]
1501 fn test_years_elapsed() {
1502 // A bit more than 1 year
1503 let one_year_ago = Utc::now().date_naive() - Days::new(400);
1504 // A bit more than 2 years
1505 let two_year_ago = Utc::now().date_naive() - Days::new(750);
1506
1507 assert_eq!(Utc::now().date_naive().years_since(one_year_ago), Some(1));
1508 assert_eq!(Utc::now().date_naive().years_since(two_year_ago), Some(2));
1509
1510 // If the given DateTime is later than now, the function will always return 0.
1511 let future = Utc::now().date_naive() + Days(100);
1512 assert_eq!(Utc::now().date_naive().years_since(future), None);
1513 }
1514
1515 #[test]
1516 fn test_datetime_add_assign() {
1517 let naivedatetime = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
1518 let datetime = naivedatetime.and_utc();
1519 let mut datetime_add = datetime;
1520
1521 datetime_add += TimeDelta::try_seconds(60).unwrap();
1522 assert_eq!(datetime_add, datetime + TimeDelta::try_seconds(60).unwrap());
1523
1524 let timezone = FixedOffset::east_opt(60 * 60).unwrap();
1525 let datetime = datetime.with_timezone(&timezone);
1526 let datetime_add = datetime_add.with_timezone(&timezone);
1527
1528 assert_eq!(datetime_add, datetime + TimeDelta::try_seconds(60).unwrap());
1529
1530 let timezone = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1531 let datetime = datetime.with_timezone(&timezone);
1532 let datetime_add = datetime_add.with_timezone(&timezone);
1533
1534 assert_eq!(datetime_add, datetime + TimeDelta::try_seconds(60).unwrap());
1535 }
1536
1537 #[test]
1538 #[cfg(feature = "clock")]
1539 fn test_datetime_add_assign_local() {
1540 let naivedatetime = NaiveDate::from_ymd_opt(2022, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
1541
1542 let datetime = Local.from_utc_datetime(&naivedatetime);
1543 let mut datetime_add = Local.from_utc_datetime(&naivedatetime);
1544
1545 // ensure we cross a DST transition
1546 for i in 1..=365 {
1547 datetime_add += TimeDelta::try_days(1).unwrap();
1548 assert_eq!(datetime_add, datetime + TimeDelta::try_days(i).unwrap())
1549 }
1550 }
1551
1552 #[test]
1553 fn test_datetime_sub_assign() {
1554 let naivedatetime = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap().and_hms_opt(12, 0, 0).unwrap();
1555 let datetime = naivedatetime.and_utc();
1556 let mut datetime_sub = datetime;
1557
1558 datetime_sub -= TimeDelta::try_minutes(90).unwrap();
1559 assert_eq!(datetime_sub, datetime - TimeDelta::try_minutes(90).unwrap());
1560
1561 let timezone = FixedOffset::east_opt(60 * 60).unwrap();
1562 let datetime = datetime.with_timezone(&timezone);
1563 let datetime_sub = datetime_sub.with_timezone(&timezone);
1564
1565 assert_eq!(datetime_sub, datetime - TimeDelta::try_minutes(90).unwrap());
1566
1567 let timezone = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1568 let datetime = datetime.with_timezone(&timezone);
1569 let datetime_sub = datetime_sub.with_timezone(&timezone);
1570
1571 assert_eq!(datetime_sub, datetime - TimeDelta::try_minutes(90).unwrap());
1572 }
1573
1574 #[test]
1575 fn test_min_max_getters() {
1576 let offset_min = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1577 let beyond_min = offset_min.from_utc_datetime(&NaiveDateTime::MIN);
1578 let offset_max = FixedOffset::east_opt(2 * 60 * 60).unwrap();
1579 let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);
1580
1581 assert_eq!(format!("{beyond_min:?}"), "-262144-12-31T22:00:00-02:00");
1582 // RFC 2822 doesn't support years with more than 4 digits.
1583 // assert_eq!(beyond_min.to_rfc2822(), "");
1584 #[cfg(feature = "alloc")]
1585 assert_eq!(beyond_min.to_rfc3339(), "-262144-12-31T22:00:00-02:00");
1586 #[cfg(feature = "alloc")]
1587 assert_eq!(
1588 beyond_min.format("%Y-%m-%dT%H:%M:%S%:z").to_string(),
1589 "-262144-12-31T22:00:00-02:00"
1590 );
1591 assert_eq!(beyond_min.year(), -262144);
1592 assert_eq!(beyond_min.month(), 12);
1593 assert_eq!(beyond_min.month0(), 11);
1594 assert_eq!(beyond_min.day(), 31);
1595 assert_eq!(beyond_min.day0(), 30);
1596 assert_eq!(beyond_min.ordinal(), 366);
1597 assert_eq!(beyond_min.ordinal0(), 365);
1598 assert_eq!(beyond_min.weekday(), Weekday::Wed);
1599 assert_eq!(beyond_min.iso_week().year(), -262143);
1600 assert_eq!(beyond_min.iso_week().week(), 1);
1601 assert_eq!(beyond_min.hour(), 22);
1602 assert_eq!(beyond_min.minute(), 0);
1603 assert_eq!(beyond_min.second(), 0);
1604 assert_eq!(beyond_min.nanosecond(), 0);
1605
1606 assert_eq!(format!("{beyond_max:?}"), "+262143-01-01T01:59:59.999999999+02:00");
1607 // RFC 2822 doesn't support years with more than 4 digits.
1608 // assert_eq!(beyond_max.to_rfc2822(), "");
1609 #[cfg(feature = "alloc")]
1610 assert_eq!(beyond_max.to_rfc3339(), "+262143-01-01T01:59:59.999999999+02:00");
1611 #[cfg(feature = "alloc")]
1612 assert_eq!(
1613 beyond_max.format("%Y-%m-%dT%H:%M:%S%.9f%:z").to_string(),
1614 "+262143-01-01T01:59:59.999999999+02:00"
1615 );
1616 assert_eq!(beyond_max.year(), 262143);
1617 assert_eq!(beyond_max.month(), 1);
1618 assert_eq!(beyond_max.month0(), 0);
1619 assert_eq!(beyond_max.day(), 1);
1620 assert_eq!(beyond_max.day0(), 0);
1621 assert_eq!(beyond_max.ordinal(), 1);
1622 assert_eq!(beyond_max.ordinal0(), 0);
1623 assert_eq!(beyond_max.weekday(), Weekday::Tue);
1624 assert_eq!(beyond_max.iso_week().year(), 262143);
1625 assert_eq!(beyond_max.iso_week().week(), 1);
1626 assert_eq!(beyond_max.hour(), 1);
1627 assert_eq!(beyond_max.minute(), 59);
1628 assert_eq!(beyond_max.second(), 59);
1629 assert_eq!(beyond_max.nanosecond(), 999_999_999);
1630 }
1631
1632 #[test]
1633 fn test_min_max_setters() {
1634 let offset_min = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1635 let beyond_min = offset_min.from_utc_datetime(&NaiveDateTime::MIN);
1636 let offset_max = FixedOffset::east_opt(2 * 60 * 60).unwrap();
1637 let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);
1638
1639 assert_eq!(beyond_min.with_year(2020).unwrap().year(), 2020);
1640 assert_eq!(beyond_min.with_year(beyond_min.year()), Some(beyond_min));
1641 assert_eq!(beyond_min.with_month(beyond_min.month()), Some(beyond_min));
1642 assert_eq!(beyond_min.with_month(3), None);
1643 assert_eq!(beyond_min.with_month0(beyond_min.month0()), Some(beyond_min));
1644 assert_eq!(beyond_min.with_month0(3), None);
1645 assert_eq!(beyond_min.with_day(beyond_min.day()), Some(beyond_min));
1646 assert_eq!(beyond_min.with_day(15), None);
1647 assert_eq!(beyond_min.with_day0(beyond_min.day0()), Some(beyond_min));
1648 assert_eq!(beyond_min.with_day0(15), None);
1649 assert_eq!(beyond_min.with_ordinal(beyond_min.ordinal()), Some(beyond_min));
1650 assert_eq!(beyond_min.with_ordinal(200), None);
1651 assert_eq!(beyond_min.with_ordinal0(beyond_min.ordinal0()), Some(beyond_min));
1652 assert_eq!(beyond_min.with_ordinal0(200), None);
1653 assert_eq!(beyond_min.with_hour(beyond_min.hour()), Some(beyond_min));
1654 assert_eq!(
1655 beyond_min.with_hour(23),
1656 beyond_min.checked_add_signed(TimeDelta::try_hours(1).unwrap())
1657 );
1658 assert_eq!(beyond_min.with_hour(5), None);
1659 assert_eq!(beyond_min.with_minute(0), Some(beyond_min));
1660 assert_eq!(beyond_min.with_second(0), Some(beyond_min));
1661 assert_eq!(beyond_min.with_nanosecond(0), Some(beyond_min));
1662
1663 assert_eq!(beyond_max.with_year(2020).unwrap().year(), 2020);
1664 assert_eq!(beyond_max.with_year(beyond_max.year()), Some(beyond_max));
1665 assert_eq!(beyond_max.with_month(beyond_max.month()), Some(beyond_max));
1666 assert_eq!(beyond_max.with_month(3), None);
1667 assert_eq!(beyond_max.with_month0(beyond_max.month0()), Some(beyond_max));
1668 assert_eq!(beyond_max.with_month0(3), None);
1669 assert_eq!(beyond_max.with_day(beyond_max.day()), Some(beyond_max));
1670 assert_eq!(beyond_max.with_day(15), None);
1671 assert_eq!(beyond_max.with_day0(beyond_max.day0()), Some(beyond_max));
1672 assert_eq!(beyond_max.with_day0(15), None);
1673 assert_eq!(beyond_max.with_ordinal(beyond_max.ordinal()), Some(beyond_max));
1674 assert_eq!(beyond_max.with_ordinal(200), None);
1675 assert_eq!(beyond_max.with_ordinal0(beyond_max.ordinal0()), Some(beyond_max));
1676 assert_eq!(beyond_max.with_ordinal0(200), None);
1677 assert_eq!(beyond_max.with_hour(beyond_max.hour()), Some(beyond_max));
1678 assert_eq!(
1679 beyond_max.with_hour(0),
1680 beyond_max.checked_sub_signed(TimeDelta::try_hours(1).unwrap())
1681 );
1682 assert_eq!(beyond_max.with_hour(5), None);
1683 assert_eq!(beyond_max.with_minute(beyond_max.minute()), Some(beyond_max));
1684 assert_eq!(beyond_max.with_second(beyond_max.second()), Some(beyond_max));
1685 assert_eq!(beyond_max.with_nanosecond(beyond_max.nanosecond()), Some(beyond_max));
1686 }
1687
1688 #[test]
1689 fn test_min_max_add_days() {
1690 let offset_min = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1691 let beyond_min = offset_min.from_utc_datetime(&NaiveDateTime::MIN);
1692 let offset_max = FixedOffset::east_opt(2 * 60 * 60).unwrap();
1693 let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);
1694 let max_time = NaiveTime::from_hms_nano_opt(23, 59, 59, 999_999_999).unwrap();
1695
1696 assert_eq!(beyond_min.checked_add_days(Days::new(0)), Some(beyond_min));
1697 assert_eq!(
1698 beyond_min.checked_add_days(Days::new(1)),
1699 Some(offset_min.from_utc_datetime(&(NaiveDate::MIN + Days(1)).and_time(NaiveTime::MIN)))
1700 );
1701 assert_eq!(beyond_min.checked_sub_days(Days::new(0)), Some(beyond_min));
1702 assert_eq!(beyond_min.checked_sub_days(Days::new(1)), None);
1703
1704 assert_eq!(beyond_max.checked_add_days(Days::new(0)), Some(beyond_max));
1705 assert_eq!(beyond_max.checked_add_days(Days::new(1)), None);
1706 assert_eq!(beyond_max.checked_sub_days(Days::new(0)), Some(beyond_max));
1707 assert_eq!(
1708 beyond_max.checked_sub_days(Days::new(1)),
1709 Some(offset_max.from_utc_datetime(&(NaiveDate::MAX - Days(1)).and_time(max_time)))
1710 );
1711 }
1712
1713 #[test]
1714 fn test_min_max_add_months() {
1715 let offset_min = FixedOffset::west_opt(2 * 60 * 60).unwrap();
1716 let beyond_min = offset_min.from_utc_datetime(&NaiveDateTime::MIN);
1717 let offset_max = FixedOffset::east_opt(2 * 60 * 60).unwrap();
1718 let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);
1719 let max_time = NaiveTime::from_hms_nano_opt(23, 59, 59, 999_999_999).unwrap();
1720
1721 assert_eq!(beyond_min.checked_add_months(Months::new(0)), Some(beyond_min));
1722 assert_eq!(
1723 beyond_min.checked_add_months(Months::new(1)),
1724 Some(offset_min.from_utc_datetime(&(NaiveDate::MIN + Months(1)).and_time(NaiveTime::MIN)))
1725 );
1726 assert_eq!(beyond_min.checked_sub_months(Months::new(0)), Some(beyond_min));
1727 assert_eq!(beyond_min.checked_sub_months(Months::new(1)), None);
1728
1729 assert_eq!(beyond_max.checked_add_months(Months::new(0)), Some(beyond_max));
1730 assert_eq!(beyond_max.checked_add_months(Months::new(1)), None);
1731 assert_eq!(beyond_max.checked_sub_months(Months::new(0)), Some(beyond_max));
1732 assert_eq!(
1733 beyond_max.checked_sub_months(Months::new(1)),
1734 Some(offset_max.from_utc_datetime(&(NaiveDate::MAX - Months(1)).and_time(max_time)))
1735 );
1736 }
1737
1738 #[test]
1739 #[should_panic]
1740 fn test_local_beyond_min_datetime() {
1741 let min = FixedOffset::west_opt(2 * 60 * 60).unwrap().from_utc_datetime(&NaiveDateTime::MIN);
1742 let _ = min.naive_local();
1743 }
1744
1745 #[test]
1746 #[should_panic]
1747 fn test_local_beyond_max_datetime() {
1748 let max = FixedOffset::east_opt(2 * 60 * 60).unwrap().from_utc_datetime(&NaiveDateTime::MAX);
1749 let _ = max.naive_local();
1750 }
1751
1752 #[test]
1753 #[cfg(feature = "clock")]
1754 fn test_datetime_sub_assign_local() {
1755 let naivedatetime = NaiveDate::from_ymd_opt(2022, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
1756
1757 let datetime = Local.from_utc_datetime(&naivedatetime);
1758 let mut datetime_sub = Local.from_utc_datetime(&naivedatetime);
1759
1760 // ensure we cross a DST transition
1761 for i in 1..=365 {
1762 datetime_sub -= TimeDelta::try_days(1).unwrap();
1763 assert_eq!(datetime_sub, datetime - TimeDelta::try_days(i).unwrap())
1764 }
1765 }
1766
1767 #[test]
1768 fn test_core_duration_ops() {
1769 use core::time::Duration;
1770
1771 let mut utc_dt = Utc.with_ymd_and_hms(2023, 8, 29, 11, 34, 12).unwrap();
1772 let same = utc_dt + Duration::ZERO;
1773 assert_eq!(utc_dt, same);
1774
1775 utc_dt += Duration::new(3600, 0);
1776 assert_eq!(utc_dt, Utc.with_ymd_and_hms(2023, 8, 29, 12, 34, 12).unwrap());
1777 }
1778
1779 #[test]
1780 #[should_panic]
1781 fn test_core_duration_max() {
1782 use core::time::Duration;
1783
1784 let mut utc_dt = Utc.with_ymd_and_hms(2023, 8, 29, 11, 34, 12).unwrap();
1785 utc_dt += Duration::MAX;
1786 }
1787
1788 #[test]
1789 #[cfg(feature = "clock")]
1790 fn test_datetime_local_from_preserves_offset() {
1791 let naivedatetime = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
1792
1793 let datetime = Local.from_utc_datetime(&naivedatetime);
1794 let offset = datetime.offset().fix();
1795
1796 let datetime_fixed: DateTime<FixedOffset> = datetime.into();
1797 assert_eq!(&offset, datetime_fixed.offset());
1798 assert_eq!(datetime.fixed_offset(), datetime_fixed);
1799 }
1800
1801 #[test]
1802 fn test_datetime_fixed_offset() {
1803 let naivedatetime = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
1804
1805 let datetime = Utc.from_utc_datetime(&naivedatetime);
1806 let fixed_utc = FixedOffset::east_opt(0).unwrap();
1807 assert_eq!(datetime.fixed_offset(), fixed_utc.from_local_datetime(&naivedatetime).unwrap());
1808
1809 let fixed_offset = FixedOffset::east_opt(3600).unwrap();
1810 let datetime_fixed = fixed_offset.from_local_datetime(&naivedatetime).unwrap();
1811 assert_eq!(datetime_fixed.fixed_offset(), datetime_fixed);
1812 }
1813
1814 #[test]
1815 fn test_datetime_to_utc() {
1816 let dt =
1817 FixedOffset::east_opt(3600).unwrap().with_ymd_and_hms(2020, 2, 22, 23, 24, 25).unwrap();
1818 let dt_utc: DateTime<Utc> = dt.to_utc();
1819 assert_eq!(dt, dt_utc);
1820 }
1821
1822 #[test]
1823 fn test_add_sub_months() {
1824 let utc_dt = Utc.with_ymd_and_hms(2018, 9, 5, 23, 58, 0).unwrap();
1825 assert_eq!(utc_dt + Months::new(15), Utc.with_ymd_and_hms(2019, 12, 5, 23, 58, 0).unwrap());
1826
1827 let utc_dt = Utc.with_ymd_and_hms(2020, 1, 31, 23, 58, 0).unwrap();
1828 assert_eq!(utc_dt + Months::new(1), Utc.with_ymd_and_hms(2020, 2, 29, 23, 58, 0).unwrap());
1829 assert_eq!(utc_dt + Months::new(2), Utc.with_ymd_and_hms(2020, 3, 31, 23, 58, 0).unwrap());
1830
1831 let utc_dt = Utc.with_ymd_and_hms(2018, 9, 5, 23, 58, 0).unwrap();
1832 assert_eq!(utc_dt - Months::new(15), Utc.with_ymd_and_hms(2017, 6, 5, 23, 58, 0).unwrap());
1833
1834 let utc_dt = Utc.with_ymd_and_hms(2020, 3, 31, 23, 58, 0).unwrap();
1835 assert_eq!(utc_dt - Months::new(1), Utc.with_ymd_and_hms(2020, 2, 29, 23, 58, 0).unwrap());
1836 assert_eq!(utc_dt - Months::new(2), Utc.with_ymd_and_hms(2020, 1, 31, 23, 58, 0).unwrap());
1837 }
1838
1839 #[test]
1840 fn test_auto_conversion() {
1841 let utc_dt = Utc.with_ymd_and_hms(2018, 9, 5, 23, 58, 0).unwrap();
1842 let cdt_dt = FixedOffset::west_opt(5 * 60 * 60)
1843 .unwrap()
1844 .with_ymd_and_hms(2018, 9, 5, 18, 58, 0)
1845 .unwrap();
1846 let utc_dt2: DateTime<Utc> = cdt_dt.into();
1847 assert_eq!(utc_dt, utc_dt2);
1848 }
1849
1850 #[test]
1851 #[cfg(feature = "clock")]
1852 #[allow(deprecated)]
1853 fn test_test_deprecated_from_offset() {
1854 let now = Local::now();
1855 let naive = now.naive_local();
1856 let utc = now.naive_utc();
1857 let offset: FixedOffset = *now.offset();
1858
1859 assert_eq!(DateTime::<Local>::from_local(naive, offset), now);
1860 assert_eq!(DateTime::<Local>::from_utc(utc, offset), now);
1861 }
1862
1863 #[test]
1864 #[cfg(all(feature = "unstable-locales", feature = "alloc"))]
1865 fn locale_decimal_point() {
1866 use crate::Locale::{ar_SY, nl_NL};
1867 let dt =
1868 Utc.with_ymd_and_hms(2018, 9, 5, 18, 58, 0).unwrap().with_nanosecond(123456780).unwrap();
1869
1870 assert_eq!(dt.format_localized("%T%.f", nl_NL).to_string(), "18:58:00,123456780");
1871 assert_eq!(dt.format_localized("%T%.3f", nl_NL).to_string(), "18:58:00,123");
1872 assert_eq!(dt.format_localized("%T%.6f", nl_NL).to_string(), "18:58:00,123456");
1873 assert_eq!(dt.format_localized("%T%.9f", nl_NL).to_string(), "18:58:00,123456780");
1874
1875 assert_eq!(dt.format_localized("%T%.f", ar_SY).to_string(), "18:58:00.123456780");
1876 assert_eq!(dt.format_localized("%T%.3f", ar_SY).to_string(), "18:58:00.123");
1877 assert_eq!(dt.format_localized("%T%.6f", ar_SY).to_string(), "18:58:00.123456");
1878 assert_eq!(dt.format_localized("%T%.9f", ar_SY).to_string(), "18:58:00.123456780");
1879 }
1880
1881 /// This is an extended test for <https://github.com/chronotope/chrono/issues/1289>.
1882 #[test]
1883 fn nano_roundrip() {
1884 const BILLION: i64 = 1_000_000_000;
1885
1886 for nanos in [
1887 i64::MIN,
1888 i64::MIN + 1,
1889 i64::MIN + 2,
1890 i64::MIN + BILLION - 1,
1891 i64::MIN + BILLION,
1892 i64::MIN + BILLION + 1,
1893 -BILLION - 1,
1894 -BILLION,
1895 -BILLION + 1,
1896 0,
1897 BILLION - 1,
1898 BILLION,
1899 BILLION + 1,
1900 i64::MAX - BILLION - 1,
1901 i64::MAX - BILLION,
1902 i64::MAX - BILLION + 1,
1903 i64::MAX - 2,
1904 i64::MAX - 1,
1905 i64::MAX,
1906 ] {
1907 println!("nanos: {nanos}");
1908 let dt = Utc.timestamp_nanos(nanos);
1909 let nanos2 = dt.timestamp_nanos_opt().expect("value roundtrips");
1910 assert_eq!(nanos, nanos2);
1911 }
1912 }