From 2052741ab3524ba7507b8d6f407ce5fc304900d2 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Tue, 20 Jun 2017 11:32:40 -0700 Subject: [PATCH] Use a lookup table to calculate the number of days in a month (#10860) Fixes https://github.com/flutter/flutter/issues/10541 --- .../flutter/lib/src/material/date_picker.dart | 16 +++++++++++++--- .../flutter/test/material/date_picker_test.dart | 9 +++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/flutter/lib/src/material/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index 14cb455277..7fcca7c469 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -220,14 +220,24 @@ class DayPicker extends StatelessWidget { }).toList(growable: false); } + // Do not use this directly - call getDaysInMonth instead. + static const List _kDaysInMonth = const [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + static int getDaysInMonth(int year, int month) { + if (month == DateTime.FEBRUARY) { + final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); + if (isLeapYear) + return 29; + } + return _kDaysInMonth[month - 1]; + } + @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final int year = displayedMonth.year; final int month = displayedMonth.month; - // Dart's Date time constructor is very forgiving and will understand - // month 13 as January of the next year. :) - final int daysInMonth = new DateTime(year, month + 1).difference(new DateTime(year, month)).inDays; + final int daysInMonth = getDaysInMonth(year, month); // This assumes a start day of SUNDAY, but could be changed. final int firstWeekday = new DateTime(year, month).weekday % 7; final List labels = []; diff --git a/packages/flutter/test/material/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index 38f1513736..a50d0c9334 100644 --- a/packages/flutter/test/material/date_picker_test.dart +++ b/packages/flutter/test/material/date_picker_test.dart @@ -329,4 +329,13 @@ void main() { }); }); }); + + test('days in month', () { + expect(DayPicker.getDaysInMonth(2017, 10), 31); + expect(DayPicker.getDaysInMonth(2017, 6), 30); + expect(DayPicker.getDaysInMonth(2017, 2), 28); + expect(DayPicker.getDaysInMonth(2016, 2), 29); + expect(DayPicker.getDaysInMonth(2000, 2), 29); + expect(DayPicker.getDaysInMonth(1900, 2), 28); + }); }