Home > Software engineering >  Flutter check last day in the month (List of datetime)
Flutter check last day in the month (List of datetime)

Time:10-10

I have a List of different DateTime where for each month of the year there are from 7-15 days with an interval of a couple of days. For example: 01.07, 04.07, 09.07, 14.07, 20.07..., 04.08, 10.08 Question: How do I check if the date is the last for the given month? For example, the date 23.07 may be the last date for the month number 07. ThanksLike this

I need to get a function to check. As input I get a DateTime which is augmented by a Bloc, so I need a check function.

CodePudding user response:

Just add one to the date, and see if it's in the next month:

void main(List<String> arguments) {
  for (final w
      in '2022-01-01 2022-01-30 2022-01-31' ' 2022-02-01 2022-02-28 2024-02-28'
          .split(' ')) {
    // print(w);
    final wd = DateTime.parse(w);
    final isLastDay = isLastDayOfMonth(wd);
    print('$w is last day of month? $isLastDay');
  }
}

bool isLastDayOfMonth(DateTime when) {
  return DateTime(when.year, when.month, when.day   1).day == 1;
}

### output:

2022-01-01 is last day of month? false
2022-01-30 is last day of month? false
2022-01-31 is last day of month? true
2022-02-01 is last day of month? false
2022-02-28 is last day of month? true
2024-02-28 is last day of month? false

CodePudding user response:

I would filter for the month, sort the list and take the first entry:

void main() {
  List<DateTime> list = [DateTime(2000,06,23), DateTime(2000,06,21),DateTime(2000,06,22)];
  list = list.where((date) => (date.month == 6)).toList();
  list.sort((a,b) => b.day.compareTo(a.day));
  print(list[0]);
}
  • Related