Debian Codegraph @

src/delta.rs

raw
1 //! Contains utility functions for shifting Date objects.
2 use chrono::Datelike;
3
4 /// Returns true if the year is a leap-year, as naively defined in the Gregorian calendar.
5 #[inline]
6 pub fn is_leap_year(year: i32) -> bool {
7 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
8 }
9
10 // If the day lies within the month, this function has no effect. Otherwise, it shifts
11 // day backwards to the final day of the month.
12 // XXX: No attempt is made to handle days outside the 1-31 range.
13 #[inline]
14 fn normalise_day(year: i32, month: u32, day: u32) -> u32 {
15 if day <= 28 {
16 day
17 } else if month == 2 {
18 28 + is_leap_year(year) as u32
19 } else if day == 31 && (month == 4 || month == 6 || month == 9 || month == 11) {
20 30
21 } else {
22 day
23 }
24 }
25
26 /// Shift a date by the given number of months.
27 /// Ambiguous month-ends are shifted backwards as necessary.
28 pub fn shift_months<D: Datelike>(date: D, months: i32) -> D {
29 shift_months_opt(date, months).unwrap()
30 }
31
32 /// Same as [`shift_months`] except fallible on unresolvable dates/times.
33 ///
34 /// Returns `None` rather than panicking when shift results in an ambiguous or non-existing
35 /// date/time (e.g. in a DST transition).
36 pub fn shift_months_opt<D: Datelike>(date: D, months: i32) -> Option<D> {
37 let mut year = date.year() + (date.month() as i32 + months) / 12;
38 let mut month = (date.month() as i32 + months) % 12;
39 let mut day = date.day();
40
41 if month < 1 {
42 year -= 1;
43 month += 12;
44 }
45
46 day = normalise_day(year, month as u32, day);
47
48 // This is slow but guaranteed to succeed (short of interger overflow)
49 if day <= 28 {
50 date.with_day(day)?
51 .with_month(month as u32)?
52 .with_year(year)
53 } else {
54 date.with_day(1)?
55 .with_month(month as u32)?
56 .with_year(year)?
57 .with_day(day)
58 }
59 }
60
61 /// Shift a date by the given number of years.
62 /// Ambiguous month-ends are shifted backwards as necessary.
63 pub fn shift_years<D: Datelike>(date: D, years: i32) -> D {
64 shift_years_opt(date, years).unwrap()
65 }
66
67 /// Same as [`shift_years`] except fallible on unresolvable dates/times.
68 ///
69 /// Returns `None` rather than panicking when shift results in an ambiguous or non-existing
70 /// date/time (e.g. in a DST transition).
71 pub fn shift_years_opt<D: Datelike>(date: D, years: i32) -> Option<D> {
72 shift_months_opt(date, years * 12)
73 }
74
75 /// Shift the date to have the given day. Returns None if the day is not in the range 1-31.
76 ///
77 /// Ambiguous month-ends are shifted backwards as necessary.
78 /// For example:
79 /// ```rust
80 /// # use chrono::NaiveDate;
81 /// # use chronoutil::with_day;
82 /// let start = NaiveDate::from_ymd_opt(2020, 2, 1).unwrap();
83 /// assert_eq!(with_day(start, 31), NaiveDate::from_ymd_opt(2020, 2, 29));
84 /// assert_eq!(with_day(start, 42), None);
85 /// ```
86 pub fn with_day<D: Datelike>(date: D, day: u32) -> Option<D> {
87 if day == 0 || day > 31 {
88 None
89 } else {
90 date.with_day(normalise_day(date.year(), date.month(), day))
91 }
92 }
93
94 /// Shift the date to have the given month. Returns None if the month is out of range.
95 ///
96 /// Ambiguous month-ends are shifted backwards as necessary.
97 /// For example:
98 /// ```rust
99 /// # use chrono::NaiveDate;
100 /// # use chronoutil::with_month;
101 /// let start = NaiveDate::from_ymd_opt(2020, 1, 31).unwrap();
102 /// assert_eq!(with_month(start, 2), NaiveDate::from_ymd_opt(2020, 2, 29));
103 /// assert_eq!(with_month(start, 13), None);
104 /// ```
105 pub fn with_month<D: Datelike>(date: D, month: u32) -> Option<D> {
106 if month == 0 || month > 12 {
107 None
108 } else {
109 let delta = month as i32 - date.month() as i32;
110 Some(shift_months(date, delta))
111 }
112 }
113
114 /// Similar to [`with_month`] except _also_ fallible on unresolvable dates/times.
115 ///
116 /// In addition to returning `None` when the month arg is out of range, also returns `None` rather
117 /// than panicking when shift results in an ambiguous or non-existing date/time (e.g. in a DST
118 /// transition).
119 pub fn with_month_opt<D: Datelike>(date: D, month: u32) -> Option<D> {
120 if month == 0 || month > 12 {
121 None
122 } else {
123 let delta = month as i32 - date.month() as i32;
124 shift_months_opt(date, delta)
125 }
126 }
127
128 /// Shift the date to have the given year.
129 ///
130 /// Ambiguous month-ends are shifted backwards as necessary.
131 /// For example:
132 /// ```rust
133 /// # use chrono::NaiveDate;
134 /// # use chronoutil::with_year;
135 /// let start = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap();
136 /// assert_eq!(with_year(start, 2021), NaiveDate::from_ymd_opt(2021, 2, 28).unwrap());
137 /// ```
138 pub fn with_year<D: Datelike>(date: D, year: i32) -> D {
139 with_year_opt(date, year).unwrap()
140 }
141
142 /// Same as [`with_year`] except fallible on unresolvable dates/times.
143 ///
144 /// Returns `None` rather than panicking when shift results in an ambiguous or non-existing
145 /// date/time (e.g. in a DST transition).
146 pub fn with_year_opt<D: Datelike>(date: D, year: i32) -> Option<D> {
147 let delta = year - date.year();
148 shift_years_opt(date, delta)
149 }
150
151 #[cfg(test)]
152 mod tests {
153 use std::collections::HashSet;
154
155 use chrono::{
156 naive::{NaiveDate, NaiveDateTime, NaiveTime},
157 LocalResult, TimeZone,
158 };
159
160 use super::*;
161
162 #[test]
163 fn test_leap_year_cases() {
164 let _leap_years: Vec<i32> = vec![
165 1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956,
166 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012,
167 2016, 2020,
168 ];
169 let leap_years_1900_to_2020: HashSet<i32> = _leap_years.into_iter().collect();
170
171 for year in 1900..2021 {
172 assert_eq!(is_leap_year(year), leap_years_1900_to_2020.contains(&year))
173 }
174 }
175
176 #[test]
177 fn test_shift_months() {
178 let base = NaiveDate::from_ymd_opt(2020, 1, 31).unwrap();
179
180 assert_eq!(
181 shift_months(base, 0),
182 NaiveDate::from_ymd_opt(2020, 1, 31).unwrap()
183 );
184 assert_eq!(
185 shift_months(base, 1),
186 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
187 );
188 assert_eq!(
189 shift_months(base, 2),
190 NaiveDate::from_ymd_opt(2020, 3, 31).unwrap()
191 );
192 assert_eq!(
193 shift_months(base, 3),
194 NaiveDate::from_ymd_opt(2020, 4, 30).unwrap()
195 );
196 assert_eq!(
197 shift_months(base, 4),
198 NaiveDate::from_ymd_opt(2020, 5, 31).unwrap()
199 );
200 assert_eq!(
201 shift_months(base, 5),
202 NaiveDate::from_ymd_opt(2020, 6, 30).unwrap()
203 );
204 assert_eq!(
205 shift_months(base, 6),
206 NaiveDate::from_ymd_opt(2020, 7, 31).unwrap()
207 );
208 assert_eq!(
209 shift_months(base, 7),
210 NaiveDate::from_ymd_opt(2020, 8, 31).unwrap()
211 );
212 assert_eq!(
213 shift_months(base, 8),
214 NaiveDate::from_ymd_opt(2020, 9, 30).unwrap()
215 );
216 assert_eq!(
217 shift_months(base, 9),
218 NaiveDate::from_ymd_opt(2020, 10, 31).unwrap()
219 );
220 assert_eq!(
221 shift_months(base, 10),
222 NaiveDate::from_ymd_opt(2020, 11, 30).unwrap()
223 );
224 assert_eq!(
225 shift_months(base, 11),
226 NaiveDate::from_ymd_opt(2020, 12, 31).unwrap()
227 );
228 assert_eq!(
229 shift_months(base, 12),
230 NaiveDate::from_ymd_opt(2021, 1, 31).unwrap()
231 );
232 assert_eq!(
233 shift_months(base, 13),
234 NaiveDate::from_ymd_opt(2021, 2, 28).unwrap()
235 );
236
237 assert_eq!(
238 shift_months(base, -1),
239 NaiveDate::from_ymd_opt(2019, 12, 31).unwrap()
240 );
241 assert_eq!(
242 shift_months(base, -2),
243 NaiveDate::from_ymd_opt(2019, 11, 30).unwrap()
244 );
245 assert_eq!(
246 shift_months(base, -3),
247 NaiveDate::from_ymd_opt(2019, 10, 31).unwrap()
248 );
249 assert_eq!(
250 shift_months(base, -4),
251 NaiveDate::from_ymd_opt(2019, 9, 30).unwrap()
252 );
253 assert_eq!(
254 shift_months(base, -5),
255 NaiveDate::from_ymd_opt(2019, 8, 31).unwrap()
256 );
257 assert_eq!(
258 shift_months(base, -6),
259 NaiveDate::from_ymd_opt(2019, 7, 31).unwrap()
260 );
261 assert_eq!(
262 shift_months(base, -7),
263 NaiveDate::from_ymd_opt(2019, 6, 30).unwrap()
264 );
265 assert_eq!(
266 shift_months(base, -8),
267 NaiveDate::from_ymd_opt(2019, 5, 31).unwrap()
268 );
269 assert_eq!(
270 shift_months(base, -9),
271 NaiveDate::from_ymd_opt(2019, 4, 30).unwrap()
272 );
273 assert_eq!(
274 shift_months(base, -10),
275 NaiveDate::from_ymd_opt(2019, 3, 31).unwrap()
276 );
277 assert_eq!(
278 shift_months(base, -11),
279 NaiveDate::from_ymd_opt(2019, 2, 28).unwrap()
280 );
281 assert_eq!(
282 shift_months(base, -12),
283 NaiveDate::from_ymd_opt(2019, 1, 31).unwrap()
284 );
285 assert_eq!(
286 shift_months(base, -13),
287 NaiveDate::from_ymd_opt(2018, 12, 31).unwrap()
288 );
289
290 assert_eq!(
291 shift_months(base, 1265),
292 NaiveDate::from_ymd_opt(2125, 6, 30).unwrap()
293 );
294 }
295
296 #[test]
297 fn test_shift_months_with_overflow() {
298 let base = NaiveDate::from_ymd_opt(2020, 12, 31).unwrap();
299
300 assert_eq!(shift_months(base, 0), base);
301 assert_eq!(
302 shift_months(base, 1),
303 NaiveDate::from_ymd_opt(2021, 1, 31).unwrap()
304 );
305 assert_eq!(
306 shift_months(base, 2),
307 NaiveDate::from_ymd_opt(2021, 2, 28).unwrap()
308 );
309 assert_eq!(
310 shift_months(base, 12),
311 NaiveDate::from_ymd_opt(2021, 12, 31).unwrap()
312 );
313 assert_eq!(
314 shift_months(base, 18),
315 NaiveDate::from_ymd_opt(2022, 6, 30).unwrap()
316 );
317
318 assert_eq!(
319 shift_months(base, -1),
320 NaiveDate::from_ymd_opt(2020, 11, 30).unwrap()
321 );
322 assert_eq!(
323 shift_months(base, -2),
324 NaiveDate::from_ymd_opt(2020, 10, 31).unwrap()
325 );
326 assert_eq!(
327 shift_months(base, -10),
328 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
329 );
330 assert_eq!(
331 shift_months(base, -12),
332 NaiveDate::from_ymd_opt(2019, 12, 31).unwrap()
333 );
334 assert_eq!(
335 shift_months(base, -18),
336 NaiveDate::from_ymd_opt(2019, 6, 30).unwrap()
337 );
338 }
339
340 #[test]
341 fn test_shift_months_datetime() {
342 let date = NaiveDate::from_ymd_opt(2020, 1, 31).unwrap();
343 let o_clock = NaiveTime::from_hms_opt(1, 2, 3).unwrap();
344
345 let base = NaiveDateTime::new(date, o_clock);
346
347 assert_eq!(
348 shift_months(base, 0).date(),
349 NaiveDate::from_ymd_opt(2020, 1, 31).unwrap()
350 );
351 assert_eq!(
352 shift_months(base, 1).date(),
353 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
354 );
355 assert_eq!(
356 shift_months(base, 2).date(),
357 NaiveDate::from_ymd_opt(2020, 3, 31).unwrap()
358 );
359 assert_eq!(shift_months(base, 0).time(), o_clock);
360 assert_eq!(shift_months(base, 1).time(), o_clock);
361 assert_eq!(shift_months(base, 2).time(), o_clock);
362 }
363
364 #[test]
365 fn test_shift_months_datetime_tz() {
366 let tz = &chrono_tz::Australia::Melbourne;
367
368 let base = tz.with_ymd_and_hms(2020, 1, 31, 1, 2, 3).single().unwrap();
369
370 assert_eq!(
371 shift_months(base, 0),
372 tz.with_ymd_and_hms(2020, 1, 31, 1, 2, 3).single().unwrap()
373 );
374 assert_eq!(
375 shift_months(base, 1),
376 tz.with_ymd_and_hms(2020, 2, 29, 1, 2, 3).single().unwrap()
377 );
378 assert_eq!(
379 shift_months(base, 2),
380 tz.with_ymd_and_hms(2020, 3, 31, 1, 2, 3).single().unwrap()
381 );
382
383 assert_eq!(
384 shift_months_opt(base, 0).unwrap(),
385 tz.with_ymd_and_hms(2020, 1, 31, 1, 2, 3).single().unwrap()
386 );
387 assert_eq!(
388 shift_months_opt(base, 1).unwrap(),
389 tz.with_ymd_and_hms(2020, 2, 29, 1, 2, 3).single().unwrap()
390 );
391 assert_eq!(
392 shift_months_opt(base, 2).unwrap(),
393 tz.with_ymd_and_hms(2020, 3, 31, 1, 2, 3).single().unwrap()
394 );
395 }
396
397 #[test]
398 #[should_panic]
399 fn test_shift_months_datetime_to_dst_backward_transition() {
400 let dst_tz = &chrono_tz::Australia::Melbourne;
401
402 // On Apr 5th 2020 after 02:59:59, clocks were wound back to 02:00:00 making 02:00::00 to
403 // 02:59:59 ambiguous.
404 // <https://www.timeanddate.com/time/change/australia/melbourne?year=2020>
405 if let LocalResult::Single(base) = dst_tz.with_ymd_and_hms(2020, 3, 5, 2, 00, 0) {
406 shift_months(base, 1); // panics
407 }
408 }
409
410 #[test]
411 fn test_shift_months_opt_datetime_to_dst_backward_transition() {
412 let dst_tz = &chrono_tz::Australia::Melbourne;
413
414 let base = dst_tz
415 .with_ymd_and_hms(2020, 3, 5, 2, 00, 0)
416 .single()
417 .unwrap();
418 assert_eq!(None, shift_months_opt(base, 1))
419 }
420
421 #[test]
422 #[should_panic]
423 fn test_shift_months_datetime_to_dst_forward_transition() {
424 let dst_tz = &chrono_tz::Australia::Melbourne;
425
426 // On Oct 4th 2020 after 01:59:59, clocks were advanced to 03:00:00 making 02:00:00 to
427 // 02:59:59 non-existent.
428 // <https://www.timeanddate.com/time/change/australia/melbourne?year=2020>
429 if let LocalResult::Single(base) = dst_tz.with_ymd_and_hms(2020, 9, 4, 2, 00, 0) {
430 shift_months(base, 1); // panics
431 }
432 }
433
434 #[test]
435 fn test_shift_months_opt_datetime_to_dst_forward_transition() {
436 let dst_tz = &chrono_tz::Australia::Melbourne;
437
438 let base = dst_tz
439 .with_ymd_and_hms(2020, 9, 4, 2, 00, 0)
440 .single()
441 .unwrap();
442 assert_eq!(None, shift_months_opt(base, 1))
443 }
444
445 #[test]
446 fn test_shift_years() {
447 let base = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap();
448
449 assert_eq!(
450 shift_years(base, 0),
451 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
452 );
453 assert_eq!(
454 shift_years(base, 1),
455 NaiveDate::from_ymd_opt(2021, 2, 28).unwrap()
456 );
457 assert_eq!(
458 shift_years(base, 4),
459 NaiveDate::from_ymd_opt(2024, 2, 29).unwrap()
460 );
461 assert_eq!(
462 shift_years(base, 80),
463 NaiveDate::from_ymd_opt(2100, 2, 28).unwrap()
464 );
465 assert_eq!(
466 shift_years(base, -1),
467 NaiveDate::from_ymd_opt(2019, 2, 28).unwrap()
468 );
469 assert_eq!(
470 shift_years(base, -4),
471 NaiveDate::from_ymd_opt(2016, 2, 29).unwrap()
472 );
473 assert_eq!(
474 shift_years(base, -20),
475 NaiveDate::from_ymd_opt(2000, 2, 29).unwrap()
476 );
477 assert_eq!(
478 shift_years(base, -120),
479 NaiveDate::from_ymd_opt(1900, 2, 28).unwrap()
480 );
481 }
482
483 #[test]
484 fn test_with_month() {
485 let base = NaiveDate::from_ymd_opt(2020, 1, 31).unwrap();
486
487 assert_eq!(with_month(base, 0), None);
488 assert_eq!(with_month(base, 1), Some(base));
489 assert_eq!(
490 with_month(base, 2).unwrap(),
491 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
492 );
493 assert_eq!(
494 with_month(base, 3).unwrap(),
495 NaiveDate::from_ymd_opt(2020, 3, 31).unwrap()
496 );
497 assert_eq!(
498 with_month(base, 4).unwrap(),
499 NaiveDate::from_ymd_opt(2020, 4, 30).unwrap()
500 );
501 assert_eq!(
502 with_month(base, 5).unwrap(),
503 NaiveDate::from_ymd_opt(2020, 5, 31).unwrap()
504 );
505 assert_eq!(
506 with_month(base, 6).unwrap(),
507 NaiveDate::from_ymd_opt(2020, 6, 30).unwrap()
508 );
509 assert_eq!(
510 with_month(base, 7).unwrap(),
511 NaiveDate::from_ymd_opt(2020, 7, 31).unwrap()
512 );
513 assert_eq!(
514 with_month(base, 8).unwrap(),
515 NaiveDate::from_ymd_opt(2020, 8, 31).unwrap()
516 );
517 assert_eq!(
518 with_month(base, 9).unwrap(),
519 NaiveDate::from_ymd_opt(2020, 9, 30).unwrap()
520 );
521 assert_eq!(
522 with_month(base, 10).unwrap(),
523 NaiveDate::from_ymd_opt(2020, 10, 31).unwrap()
524 );
525 assert_eq!(
526 with_month(base, 11).unwrap(),
527 NaiveDate::from_ymd_opt(2020, 11, 30).unwrap()
528 );
529 assert_eq!(
530 with_month(base, 12).unwrap(),
531 NaiveDate::from_ymd_opt(2020, 12, 31).unwrap()
532 );
533 assert_eq!(with_month(base, 13), None);
534
535 assert_eq!(
536 with_month(NaiveDate::from_ymd_opt(2021, 1, 31).unwrap(), 2),
537 Some(NaiveDate::from_ymd_opt(2021, 2, 28).unwrap())
538 );
539
540 // Backwards shifts work too
541 assert_eq!(
542 with_month(NaiveDate::from_ymd_opt(2021, 2, 15).unwrap(), 1),
543 Some(NaiveDate::from_ymd_opt(2021, 1, 15).unwrap())
544 );
545 }
546
547 #[test]
548 fn test_with_month_opt() {
549 let tz = &chrono_tz::Australia::Melbourne;
550
551 let base = tz.with_ymd_and_hms(2020, 1, 31, 0, 0, 0).single().unwrap();
552
553 assert_eq!(with_month(base, 0), None);
554 assert_eq!(with_month(base, 1), Some(base));
555 assert_eq!(
556 with_month(base, 2).unwrap(),
557 tz.with_ymd_and_hms(2020, 2, 29, 0, 0, 0).single().unwrap()
558 );
559 assert_eq!(
560 with_month(base, 3).unwrap(),
561 tz.with_ymd_and_hms(2020, 3, 31, 0, 0, 0).single().unwrap()
562 );
563 assert_eq!(
564 with_month(base, 12).unwrap(),
565 tz.with_ymd_and_hms(2020, 12, 31, 0, 0, 0).single().unwrap()
566 );
567 assert_eq!(with_month(base, 13), None);
568
569 // Backwards shifts work too
570 assert_eq!(
571 with_month(
572 tz.with_ymd_and_hms(2021, 2, 15, 0, 0, 0).single().unwrap(),
573 1
574 ),
575 Some(tz.with_ymd_and_hms(2021, 1, 15, 0, 0, 0).single().unwrap())
576 );
577 }
578
579 #[test]
580 fn test_with_year() {
581 let base = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap();
582
583 assert_eq!(
584 with_year(base, 2024),
585 NaiveDate::from_ymd_opt(2024, 2, 29).unwrap()
586 );
587 assert_eq!(
588 with_year(base, 2021),
589 NaiveDate::from_ymd_opt(2021, 2, 28).unwrap()
590 );
591 assert_eq!(
592 with_year(base, 2020),
593 NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()
594 );
595 assert_eq!(
596 with_year(base, 2019),
597 NaiveDate::from_ymd_opt(2019, 2, 28).unwrap()
598 );
599 assert_eq!(
600 with_year(base, 2016),
601 NaiveDate::from_ymd_opt(2016, 2, 29).unwrap()
602 );
603 }
604 }