Skip to content

Commit 72bd651

Browse files
jason-simmonsgspencergoog
authored andcommitted
Use a lookup table to calculate the number of days in a month (flutter#10860)
Fixes flutter#10541
1 parent c45d856 commit 72bd651

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

packages/flutter/lib/src/material/date_picker.dart

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -220,14 +220,24 @@ class DayPicker extends StatelessWidget {
220220
}).toList(growable: false);
221221
}
222222

223+
// Do not use this directly - call getDaysInMonth instead.
224+
static const List<int> _kDaysInMonth = const <int>[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
225+
226+
static int getDaysInMonth(int year, int month) {
227+
if (month == DateTime.FEBRUARY) {
228+
final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
229+
if (isLeapYear)
230+
return 29;
231+
}
232+
return _kDaysInMonth[month - 1];
233+
}
234+
223235
@override
224236
Widget build(BuildContext context) {
225237
final ThemeData themeData = Theme.of(context);
226238
final int year = displayedMonth.year;
227239
final int month = displayedMonth.month;
228-
// Dart's Date time constructor is very forgiving and will understand
229-
// month 13 as January of the next year. :)
230-
final int daysInMonth = new DateTime(year, month + 1).difference(new DateTime(year, month)).inDays;
240+
final int daysInMonth = getDaysInMonth(year, month);
231241
// This assumes a start day of SUNDAY, but could be changed.
232242
final int firstWeekday = new DateTime(year, month).weekday % 7;
233243
final List<Widget> labels = <Widget>[];

packages/flutter/test/material/date_picker_test.dart

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,4 +329,13 @@ void main() {
329329
});
330330
});
331331
});
332+
333+
test('days in month', () {
334+
expect(DayPicker.getDaysInMonth(2017, 10), 31);
335+
expect(DayPicker.getDaysInMonth(2017, 6), 30);
336+
expect(DayPicker.getDaysInMonth(2017, 2), 28);
337+
expect(DayPicker.getDaysInMonth(2016, 2), 29);
338+
expect(DayPicker.getDaysInMonth(2000, 2), 29);
339+
expect(DayPicker.getDaysInMonth(1900, 2), 28);
340+
});
332341
}

0 commit comments

Comments
 (0)