Skip to main content

waft_material/
date.rs

1//! Flutter counterpart: material_ui's `date.dart`.
2//!
3//! The calendar arithmetic the date pickers share: [`DateUtils`], the [`CalendarDelegate`] a
4//! picker asks for dates, and the two modes and the range value the pickers pass around. Dates
5//! are local [`DateTime`](waft_foundation::DateTime)s, as Dart's `DateTime(year, month, day)`
6//! makes them, so a "day" here is a calendar day in the local time zone, and what makes one or
7//! reads one's fields takes the [`App`] whose platform gives the zone, as Dart's reach the VM.
8
9use std::fmt;
10use std::time::Duration;
11
12use waft_foundation::{App, DateTime};
13use waft_services::TextInputFormatterRef;
14
15use crate::material_localizations::MaterialLocalizations;
16
17/// A delegate that handles all of the calendar operations a date picker needs: formatting,
18/// parsing and the arithmetic on months and days.
19///
20/// Dart's `CalendarDelegate<T extends DateTime>` is generic over a subclass of `DateTime`.
21/// Rust has no subclasses of [`DateTime`], so a delegate here always works on [`DateTime`]
22/// values; a non-Gregorian calendar maps its dates onto them.
23pub trait CalendarDelegate: fmt::Debug {
24    /// Returns a [`DateTime`] representing the current moment.
25    fn now(&self, app: &App) -> DateTime;
26
27    /// Returns a [`DateTime`] with the date of the original, but time set to midnight.
28    fn date_only(&self, app: &App, date: &DateTime) -> DateTime;
29
30    /// Returns a [`DateTimeRange`] with the dates of the original, but times set to midnight.
31    fn dates_only(&self, app: &App, range: &DateTimeRange) -> DateTimeRange {
32        DateTimeRange::new(
33            self.date_only(app, &range.start),
34            self.date_only(app, &range.end),
35        )
36    }
37
38    /// Returns true if the two [`DateTime`] objects have the same day, month, and year, or are
39    /// both null.
40    fn is_same_day(&self, app: &App, date_a: Option<&DateTime>, date_b: Option<&DateTime>) -> bool {
41        date_a.map(|date| (date.year(app), date.month(app), date.day(app)))
42            == date_b.map(|date| (date.year(app), date.month(app), date.day(app)))
43    }
44
45    /// Returns true if the two [`DateTime`] objects have the same month and year, or are both
46    /// null.
47    fn is_same_month(
48        &self,
49        app: &App,
50        date_a: Option<&DateTime>,
51        date_b: Option<&DateTime>,
52    ) -> bool {
53        date_a.map(|date| (date.year(app), date.month(app)))
54            == date_b.map(|date| (date.year(app), date.month(app)))
55    }
56
57    /// Determines the number of months between two [`DateTime`] objects.
58    fn month_delta(&self, app: &App, start_date: &DateTime, end_date: &DateTime) -> i32;
59
60    /// Returns a [`DateTime`] with the added number of months and the day set to 1 and time
61    /// set to midnight.
62    fn add_months_to_month_date(
63        &self,
64        app: &App,
65        month_date: &DateTime,
66        months_to_add: i32,
67    ) -> DateTime;
68
69    /// Returns a [`DateTime`] with the added number of days and time set to midnight.
70    fn add_days_to_date(&self, app: &App, date: &DateTime, days: i32) -> DateTime;
71
72    /// Computes the offset from the first day of the week that the first day of the `month`
73    /// falls on.
74    fn first_day_offset(
75        &self,
76        app: &App,
77        year: i32,
78        month: i32,
79        localizations: &dyn MaterialLocalizations,
80    ) -> i32;
81
82    /// Returns the number of days in a month, according to the proleptic Gregorian calendar.
83    fn get_days_in_month(&self, year: i32, month: i32) -> i32;
84
85    /// Returns a [`DateTime`] with the given `year` and `month`, on the first day of the month.
86    fn get_month(&self, app: &App, year: i32, month: i32) -> DateTime;
87
88    /// Returns a [`DateTime`] with the given `year`, `month` and `day`.
89    fn get_day(&self, app: &App, year: i32, month: i32, day: i32) -> DateTime;
90
91    /// Formats the month and the year of the given [`DateTime`].
92    fn format_month_year(
93        &self,
94        app: &App,
95        date: &DateTime,
96        localizations: &dyn MaterialLocalizations,
97    ) -> String;
98
99    /// Formats the given `year` as a year.
100    fn format_year(
101        &self,
102        app: &App,
103        year: i32,
104        localizations: &dyn MaterialLocalizations,
105    ) -> String {
106        localizations.format_year(app, &DateTime::new(app, year, 1, 1))
107    }
108
109    /// Formats the given [`DateTime`] as a medium-length date.
110    fn format_medium_date(
111        &self,
112        app: &App,
113        date: &DateTime,
114        localizations: &dyn MaterialLocalizations,
115    ) -> String;
116
117    /// Formats the month and day of the given [`DateTime`], in a short form.
118    fn format_short_month_day(
119        &self,
120        app: &App,
121        date: &DateTime,
122        localizations: &dyn MaterialLocalizations,
123    ) -> String;
124
125    /// Formats the given [`DateTime`] as a short date.
126    fn format_short_date(
127        &self,
128        app: &App,
129        date: &DateTime,
130        localizations: &dyn MaterialLocalizations,
131    ) -> String;
132
133    /// Formats the given [`DateTime`] as a full date.
134    fn format_full_date(
135        &self,
136        app: &App,
137        date: &DateTime,
138        localizations: &dyn MaterialLocalizations,
139    ) -> String;
140
141    /// Formats the given [`DateTime`] as a compact date.
142    fn format_compact_date(
143        &self,
144        app: &App,
145        date: &DateTime,
146        localizations: &dyn MaterialLocalizations,
147    ) -> String;
148
149    /// Parses the given input string as a compact date.
150    fn parse_compact_date(
151        &self,
152        app: &App,
153        input_string: Option<&str>,
154        localizations: &dyn MaterialLocalizations,
155    ) -> Option<DateTime>;
156
157    /// The help text displayed in the input date picker.
158    fn date_help_text(&self, localizations: &dyn MaterialLocalizations) -> String;
159
160    /// The formatters that restrict what a user may type when entering dates by keyboard.
161    fn keyboard_input_formatters(
162        &self,
163        _localizations: &dyn MaterialLocalizations,
164    ) -> Option<Vec<TextInputFormatterRef>> {
165        None
166    }
167}
168
169/// A [`CalendarDelegate`] for the Gregorian calendar, which is what [`DateUtils`] computes in.
170#[derive(Clone, Copy, Debug, Default)]
171pub struct GregorianCalendarDelegate;
172
173impl CalendarDelegate for GregorianCalendarDelegate {
174    fn now(&self, _app: &App) -> DateTime {
175        DateTime::now()
176    }
177
178    fn date_only(&self, app: &App, date: &DateTime) -> DateTime {
179        DateUtils::date_only(app, date)
180    }
181
182    fn month_delta(&self, app: &App, start_date: &DateTime, end_date: &DateTime) -> i32 {
183        DateUtils::month_delta(app, start_date, end_date)
184    }
185
186    fn add_months_to_month_date(
187        &self,
188        app: &App,
189        month_date: &DateTime,
190        months_to_add: i32,
191    ) -> DateTime {
192        DateUtils::add_months_to_month_date(app, month_date, months_to_add)
193    }
194
195    fn add_days_to_date(&self, app: &App, date: &DateTime, days: i32) -> DateTime {
196        DateUtils::add_days_to_date(app, date, days)
197    }
198
199    fn first_day_offset(
200        &self,
201        app: &App,
202        year: i32,
203        month: i32,
204        localizations: &dyn MaterialLocalizations,
205    ) -> i32 {
206        DateUtils::first_day_offset(app, year, month, localizations)
207    }
208
209    fn get_days_in_month(&self, year: i32, month: i32) -> i32 {
210        DateUtils::get_days_in_month(year, month)
211    }
212
213    fn get_month(&self, app: &App, year: i32, month: i32) -> DateTime {
214        DateTime::new(app, year, month, 1)
215    }
216
217    fn get_day(&self, app: &App, year: i32, month: i32, day: i32) -> DateTime {
218        DateTime::new(app, year, month, day)
219    }
220
221    fn format_month_year(
222        &self,
223        app: &App,
224        date: &DateTime,
225        localizations: &dyn MaterialLocalizations,
226    ) -> String {
227        localizations.format_month_year(app, date)
228    }
229
230    fn format_medium_date(
231        &self,
232        app: &App,
233        date: &DateTime,
234        localizations: &dyn MaterialLocalizations,
235    ) -> String {
236        localizations.format_medium_date(app, date)
237    }
238
239    fn format_short_month_day(
240        &self,
241        app: &App,
242        date: &DateTime,
243        localizations: &dyn MaterialLocalizations,
244    ) -> String {
245        localizations.format_short_month_day(app, date)
246    }
247
248    fn format_short_date(
249        &self,
250        app: &App,
251        date: &DateTime,
252        localizations: &dyn MaterialLocalizations,
253    ) -> String {
254        localizations.format_short_date(app, date)
255    }
256
257    fn format_full_date(
258        &self,
259        app: &App,
260        date: &DateTime,
261        localizations: &dyn MaterialLocalizations,
262    ) -> String {
263        localizations.format_full_date(app, date)
264    }
265
266    fn format_compact_date(
267        &self,
268        app: &App,
269        date: &DateTime,
270        localizations: &dyn MaterialLocalizations,
271    ) -> String {
272        localizations.format_compact_date(app, date)
273    }
274
275    fn parse_compact_date(
276        &self,
277        app: &App,
278        input_string: Option<&str>,
279        localizations: &dyn MaterialLocalizations,
280    ) -> Option<DateTime> {
281        localizations.parse_compact_date(app, input_string)
282    }
283
284    fn date_help_text(&self, localizations: &dyn MaterialLocalizations) -> String {
285        localizations.date_help_text()
286    }
287}
288
289/// Utility functions for working with dates.
290pub struct DateUtils;
291
292impl DateUtils {
293    /// Returns a [`DateTime`] with the date of the original, but time set to midnight.
294    pub fn date_only(app: &App, date: &DateTime) -> DateTime {
295        DateTime::new(app, date.year(app), date.month(app), date.day(app))
296    }
297
298    /// Returns a [`DateTimeRange`] with the dates of the original, but with times set to
299    /// midnight.
300    ///
301    /// See also: [`date_only`](Self::date_only), which does the same thing for a single date.
302    pub fn dates_only(app: &App, range: &DateTimeRange) -> DateTimeRange {
303        DateTimeRange::new(
304            Self::date_only(app, &range.start),
305            Self::date_only(app, &range.end),
306        )
307    }
308
309    /// Returns true if the two [`DateTime`] objects have the same day, month, and year, or are
310    /// both null.
311    pub fn is_same_day(app: &App, date_a: Option<&DateTime>, date_b: Option<&DateTime>) -> bool {
312        GregorianCalendarDelegate.is_same_day(app, date_a, date_b)
313    }
314
315    /// Returns true if the two [`DateTime`] objects have the same month and year, or are both
316    /// null.
317    pub fn is_same_month(app: &App, date_a: Option<&DateTime>, date_b: Option<&DateTime>) -> bool {
318        GregorianCalendarDelegate.is_same_month(app, date_a, date_b)
319    }
320
321    /// Determines the number of months between two [`DateTime`] objects.
322    ///
323    /// For example:
324    ///
325    /// ```
326    /// # use waft_foundation::{AppCell, DateTime};
327    /// # use waft_material::DateUtils;
328    /// # let cell = AppCell::new();
329    /// # let app = cell.borrow();
330    /// let date1 = DateTime::new(&app, 2019, 6, 15);
331    /// let date2 = DateTime::new(&app, 2020, 1, 15);
332    /// let difference = DateUtils::month_delta(&app, &date1, &date2);
333    /// assert_eq!(difference, 7);
334    /// ```
335    ///
336    /// The days are not taken into account, so the difference is always an integer number of
337    /// months.
338    pub fn month_delta(app: &App, start_date: &DateTime, end_date: &DateTime) -> i32 {
339        (end_date.year(app) - start_date.year(app)) * 12 + end_date.month(app)
340            - start_date.month(app)
341    }
342
343    /// Returns a [`DateTime`] that is `month_date` with the added number of months and the day
344    /// set to 1 and time set to midnight.
345    ///
346    /// For example:
347    ///
348    /// ```
349    /// # use waft_foundation::{AppCell, DateTime};
350    /// # use waft_material::DateUtils;
351    /// # let cell = AppCell::new();
352    /// # let app = cell.borrow();
353    /// let date = DateTime::new(&app, 2019, 1, 15);
354    /// let next_month = DateUtils::add_months_to_month_date(&app, &date, 1);
355    /// assert_eq!(next_month, DateTime::new(&app, 2019, 2, 1));
356    /// ```
357    ///
358    /// `month_date` is assumed to already be on the first of the month.
359    pub fn add_months_to_month_date(
360        app: &App,
361        month_date: &DateTime,
362        months_to_add: i32,
363    ) -> DateTime {
364        DateTime::new(
365            app,
366            month_date.year(app),
367            month_date.month(app) + months_to_add,
368            1,
369        )
370    }
371
372    /// Returns a [`DateTime`] with the added number of days and time set to midnight.
373    pub fn add_days_to_date(app: &App, date: &DateTime, days: i32) -> DateTime {
374        DateTime::new(app, date.year(app), date.month(app), date.day(app) + days)
375    }
376
377    /// Computes the offset from the first day of the week that the first day of the `month`
378    /// falls on.
379    ///
380    /// For example, September 1, 2017 falls on a Friday, which in the calendar localized for
381    /// United States English appears as:
382    ///
383    /// ```text
384    /// S M T W T F S
385    /// _ _ _ _ _ 1 2
386    /// ```
387    ///
388    /// The offset for the first day of the months is the number of leading blanks in the
389    /// calendar, i.e. 5.
390    ///
391    /// The same date localized for the Russian calendar has a different offset, because the
392    /// first day of week is Monday rather than Sunday:
393    ///
394    /// ```text
395    /// M T W T F S S
396    /// _ _ _ _ 1 2 3
397    /// ```
398    ///
399    /// So the offset is 4, rather than 5.
400    ///
401    /// This code consolidates the following:
402    ///
403    /// - [`DateTime::weekday`] provides a 1-based index into days of week, with 1 falling on
404    ///   Monday.
405    /// - [`MaterialLocalizations::first_day_of_week_index`] provides a 0-based index into the
406    ///   [`MaterialLocalizations::narrow_weekdays`] list.
407    /// - [`MaterialLocalizations::narrow_weekdays`] list provides localized names of days of
408    ///   week, always starting with Sunday and ending with Saturday.
409    pub fn first_day_offset(
410        app: &App,
411        year: i32,
412        month: i32,
413        localizations: &dyn MaterialLocalizations,
414    ) -> i32 {
415        // 0-based day of week for the month and year, with 0 representing Monday.
416        let weekday_from_monday = DateTime::new(app, year, month, 1).weekday(app) - 1;
417
418        // 0-based start of week depending on the locale, with 0 representing Sunday.
419        let first_day_of_week_index = localizations.first_day_of_week_index();
420
421        // firstDayOfWeekIndex recomputed to be Monday-based, in order to compare with
422        // weekdayFromMonday.
423        let first_day_of_week_index = (first_day_of_week_index - 1).rem_euclid(7);
424
425        // Number of days between the first day of week appearing on the calendar, and the day
426        // corresponding to the first of the month.
427        (weekday_from_monday - first_day_of_week_index).rem_euclid(7)
428    }
429
430    /// Returns the number of days in a month, according to the proleptic Gregorian calendar.
431    ///
432    /// This applies the leap year logic introduced by the Gregorian reforms of 1582. It will
433    /// not give valid results for dates prior to that time.
434    pub fn get_days_in_month(year: i32, month: i32) -> i32 {
435        if month == DateTime::FEBRUARY {
436            let is_leap_year = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
437            return if is_leap_year { 29 } else { 28 };
438        }
439        const DAYS_IN_MONTH: [i32; 12] = [31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
440        DAYS_IN_MONTH[(month - 1) as usize]
441    }
442}
443
444/// Whether `a`'s calendar day comes before `b`'s: how the pickers' date checks compare the days
445/// [`CalendarDelegate::date_only`] gives. Local midnights are in the order of their dates, so the
446/// dates' fields order them.
447pub(crate) fn is_day_before(app: &App, a: &DateTime, b: &DateTime) -> bool {
448    (a.year(app), a.month(app), a.day(app)) < (b.year(app), b.month(app), b.day(app))
449}
450
451/// Initial display mode of the date picker dialog.
452///
453/// Date picker UI mode for either showing a list of available years or a monthly calendar
454/// initially in the dialog shown by calling [`showDatePicker`](crate::ShowDatePicker).
455#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
456pub enum DatePickerEntryMode {
457    /// User picks a date from calendar grid. Can switch to [`Input`](Self::Input) by pressing
458    /// a button in the dialog.
459    Calendar,
460
461    /// User can input the date with a text field. Can switch to [`Calendar`](Self::Calendar)
462    /// by pressing a button in the dialog.
463    Input,
464
465    /// User can only pick a date from calendar grid. Switching to
466    /// [`Input`](Self::Input) is disabled.
467    CalendarOnly,
468
469    /// User can only input the date with a text field. Switching to
470    /// [`Calendar`](Self::Calendar) is disabled.
471    InputOnly,
472}
473
474/// Initial display of a calendar date picker.
475///
476/// Either a grid of available years or a monthly calendar.
477#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
478pub enum DatePickerMode {
479    /// Choosing a month and day.
480    Day,
481
482    /// Choosing a year.
483    Year,
484}
485
486/// Represents a range of dates, i.e. the span of time from [`start`](Self::start) to
487/// [`end`](Self::end).
488///
489/// The range includes the start and end dates, so with `start` and `end` on the same day the
490/// range covers one day.
491///
492/// Dart's `DateTimeRange<T extends DateTime>` is generic over a subclass of `DateTime`;
493/// see [`CalendarDelegate`].
494#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
495pub struct DateTimeRange {
496    /// The start of the range of dates.
497    pub start: DateTime,
498
499    /// The end of the range of dates.
500    pub end: DateTime,
501}
502
503impl DateTimeRange {
504    /// Creates a date range for the given start and end [`DateTime`].
505    ///
506    /// Dart's `DateTimeRange({required start, required end})`.
507    pub fn new(start: DateTime, end: DateTime) -> DateTimeRange {
508        debug_assert!(!start.is_after(&end), "start must not be after end");
509        DateTimeRange { start, end }
510    }
511
512    /// Returns a [`Duration`] of the time between [`start`](Self::start) and
513    /// [`end`](Self::end).
514    ///
515    /// See [`DateTime::difference`] in Dart; here the difference of the two instants.
516    pub fn duration(&self) -> Duration {
517        Duration::from_micros(
518            (self.end.microseconds_since_epoch() - self.start.microseconds_since_epoch()) as u64,
519        )
520    }
521}
522
523impl DateTimeRange {
524    /// Dart's `toString`: the two dates, each read in its time zone.
525    pub fn to_string(&self, app: &App) -> String {
526        format!(
527            "{} - {}",
528            self.start.to_string(app),
529            self.end.to_string(app)
530        )
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use waft_foundation::AppCell;
537
538    use super::*;
539    use crate::material_localizations::DefaultMaterialLocalizations;
540
541    /// Not in Flutter's file: in a zone with daylight saving, a day is the local calendar day,
542    /// so the day the clocks spring forward is 23 hours long and still starts at midnight.
543    #[test]
544    fn date_utils_count_local_calendar_days_across_a_change_of_offset() {
545        use std::rc::Rc;
546        use waft_embedder::{PlatformRef, SignedDuration};
547        use waft_test::{TestPlatform, TestTimeZone};
548        /// 2026-03-29T01:00:00Z: clocks in Central Europe go from 2:00 to 3:00.
549        const SPRING_FORWARD: i64 = 1_774_746_000;
550        let central_europe = TestTimeZone::new(|seconds| {
551            if seconds >= SPRING_FORWARD {
552                (SignedDuration::from_hours(2), "CEST".to_string())
553            } else {
554                (SignedDuration::from_hours(1), "CET".to_string())
555            }
556        });
557        let platform: PlatformRef = Rc::new(TestPlatform::new().with_time_zone(central_europe));
558        let cell = AppCell::with_platform(platform);
559        let app = cell.borrow();
560
561        let late_evening = DateTime::new_with_time(&app, 2026, 3, 28, 23, 30, 0, 0, 0);
562        let day = DateUtils::date_only(&app, &late_evening);
563        assert_eq!((day.day(&app), day.hour(&app)), (28, 0));
564        let next = DateUtils::add_days_to_date(&app, &day, 1);
565        let after = DateUtils::add_days_to_date(&app, &day, 2);
566        assert_eq!((next.day(&app), next.hour(&app)), (29, 0));
567        assert_eq!((after.day(&app), after.hour(&app)), (30, 0));
568        assert_eq!(
569            after.microseconds_since_epoch() - next.microseconds_since_epoch(),
570            23 * 60 * 60 * 1_000_000,
571            "the day the clocks go forward has 23 hours"
572        );
573        assert!(DateUtils::is_same_day(
574            &app,
575            Some(&late_evening),
576            Some(&day)
577        ));
578    }
579
580    #[test]
581    fn date_utils_date_only_drops_the_time() {
582        let cell = AppCell::new();
583        let app = cell.borrow();
584        let date = DateTime::new_with_time(&app, 2019, 6, 15, 13, 45, 30, 0, 0);
585        assert_eq!(
586            DateUtils::date_only(&app, &date),
587            DateTime::new(&app, 2019, 6, 15)
588        );
589    }
590
591    #[test]
592    fn date_utils_dates_only_drops_the_times_of_a_range() {
593        let cell = AppCell::new();
594        let app = cell.borrow();
595        let range = DateTimeRange::new(
596            DateTime::new_with_time(&app, 2019, 6, 15, 13, 0, 0, 0, 0),
597            DateTime::new_with_time(&app, 2019, 6, 20, 1, 0, 0, 0, 0),
598        );
599        let dates = DateUtils::dates_only(&app, &range);
600        assert_eq!(dates.start, DateTime::new(&app, 2019, 6, 15));
601        assert_eq!(dates.end, DateTime::new(&app, 2019, 6, 20));
602    }
603
604    #[test]
605    fn date_utils_is_same_day_and_month_compare_the_calendar_fields() {
606        let cell = AppCell::new();
607        let app = cell.borrow();
608        let morning = DateTime::new_with_time(&app, 2019, 6, 15, 1, 0, 0, 0, 0);
609        let evening = DateTime::new_with_time(&app, 2019, 6, 15, 23, 0, 0, 0, 0);
610        let next_day = DateTime::new(&app, 2019, 6, 16);
611        let next_year = DateTime::new(&app, 2020, 6, 15);
612        assert!(DateUtils::is_same_day(&app, Some(&morning), Some(&evening)));
613        assert!(!DateUtils::is_same_day(
614            &app,
615            Some(&morning),
616            Some(&next_day)
617        ));
618        assert!(!DateUtils::is_same_day(
619            &app,
620            Some(&morning),
621            Some(&next_year)
622        ));
623        assert!(DateUtils::is_same_day(&app, None, None));
624        assert!(!DateUtils::is_same_day(&app, Some(&morning), None));
625        assert!(DateUtils::is_same_month(
626            &app,
627            Some(&morning),
628            Some(&next_day)
629        ));
630        assert!(!DateUtils::is_same_month(
631            &app,
632            Some(&morning),
633            Some(&next_year)
634        ));
635        assert!(DateUtils::is_same_month(&app, None, None));
636    }
637
638    #[test]
639    fn date_utils_month_delta_counts_whole_months() {
640        let cell = AppCell::new();
641        let app = cell.borrow();
642        let date1 = DateTime::new(&app, 2019, 6, 15);
643        let date2 = DateTime::new(&app, 2020, 1, 15);
644        assert_eq!(DateUtils::month_delta(&app, &date1, &date2), 7);
645        assert_eq!(DateUtils::month_delta(&app, &date2, &date1), -7);
646    }
647
648    #[test]
649    fn date_utils_adds_months_and_days_across_year_ends() {
650        let cell = AppCell::new();
651        let app = cell.borrow();
652        let december = DateTime::new(&app, 2019, 12, 1);
653        assert_eq!(
654            DateUtils::add_months_to_month_date(&app, &december, 1),
655            DateTime::new(&app, 2020, 1, 1)
656        );
657        assert_eq!(
658            DateUtils::add_months_to_month_date(&app, &DateTime::new(&app, 2020, 1, 1), -1),
659            december
660        );
661        assert_eq!(
662            DateUtils::add_days_to_date(&app, &DateTime::new(&app, 2019, 12, 31), 1),
663            DateTime::new(&app, 2020, 1, 1)
664        );
665        assert_eq!(
666            DateUtils::add_days_to_date(&app, &DateTime::new(&app, 2020, 3, 1), -1),
667            DateTime::new(&app, 2020, 2, 29)
668        );
669    }
670
671    #[test]
672    fn date_utils_get_days_in_month_follows_the_gregorian_leap_rule() {
673        assert_eq!(DateUtils::get_days_in_month(2019, 2), 28);
674        assert_eq!(DateUtils::get_days_in_month(2020, 2), 29);
675        assert_eq!(DateUtils::get_days_in_month(1900, 2), 28);
676        assert_eq!(DateUtils::get_days_in_month(2000, 2), 29);
677        assert_eq!(DateUtils::get_days_in_month(2019, 1), 31);
678        assert_eq!(DateUtils::get_days_in_month(2019, 4), 30);
679        assert_eq!(DateUtils::get_days_in_month(2019, 12), 31);
680    }
681
682    #[test]
683    fn date_utils_first_day_offset_counts_the_blanks_before_the_first() {
684        // September 1, 2017 is a Friday, and English weeks start on Sunday: five blanks.
685        let cell = AppCell::new();
686        let app = cell.borrow();
687        let english = DefaultMaterialLocalizations;
688        assert_eq!(DateUtils::first_day_offset(&app, 2017, 9, &english), 5);
689    }
690
691    #[test]
692    fn date_time_range_has_the_duration_between_its_dates() {
693        let cell = AppCell::new();
694        let app = cell.borrow();
695        let range = DateTimeRange::new(
696            DateTime::new(&app, 2019, 6, 15),
697            DateTime::new(&app, 2019, 6, 20),
698        );
699        assert_eq!(range.duration(), Duration::from_secs(5 * 24 * 60 * 60));
700        assert_eq!(
701            range.to_string(&app),
702            "2019-06-15 00:00:00.000 - 2019-06-20 00:00:00.000"
703        );
704    }
705
706    #[test]
707    #[should_panic]
708    fn date_time_range_asserts_that_start_is_not_after_end() {
709        let cell = AppCell::new();
710        let app = cell.borrow();
711        DateTimeRange::new(
712            DateTime::new(&app, 2019, 6, 20),
713            DateTime::new(&app, 2019, 6, 15),
714        );
715    }
716
717    #[test]
718    fn the_gregorian_delegate_builds_months_and_days() {
719        let cell = AppCell::new();
720        let app = cell.borrow();
721        let delegate = GregorianCalendarDelegate;
722        assert_eq!(
723            delegate.get_month(&app, 2019, 3),
724            DateTime::new(&app, 2019, 3, 1)
725        );
726        assert_eq!(
727            delegate.get_day(&app, 2019, 3, 4),
728            DateTime::new(&app, 2019, 3, 4)
729        );
730        assert_eq!(delegate.get_days_in_month(2020, 2), 29);
731    }
732}