Dart/Flutter - Get The Last Day of A Month Examples

This tutorial shows you how to get the last day of a month in Dart.

As we already know, each month can have a different number of days. In addition, the number of days in February depends on whether the year is a leap year or not. If you want to get the last day of a month in Dart programming language (also works in Flutter), read the examples below.

Using DateTime

In Dart, it's quite common to store a value that represents a time in a DateTime variable. While Dart doesn't provide a built-in method or property to get the last day of a month, fortunately we can do it using a simple trick.

The idea is if we set the day of a DateTime to 0, it will be set to the last day of the previous month. Therefore, to get the last day of a month, we can create a DateTime instance with the month value set to the next month and the day property set to 0. Then, we can get the day property to get the value of the day in integer.

  DateTime now = DateTime.now();
  int lastday = DateTime(now.year, now.month + 1, 0).day;

To make it easy to get the last day of the month of a DateTime instance, we can create an extension on the DateTime class.

  extension DateTimeExtension on DateTime {

    int get lastDayOfMonth => DateTime(year, month + 1, 0).day;

    DateTime get lastDateOfMonth => DateTime(year, month + 1, 0);
  }

Below is the usage example.

  print(DateTime(2023, 1).lastDayOfMonth); // 31
  print(DateTime(2023, 2).lastDayOfMonth); // 28
  print(DateTime(2020, 2).lastDayOfMonth); // 29

Summary

Despite there is no built-in functionality to get the last day of a month in Dart, it can be done easily by creating a DateTime with the month value set to the next month and the day value set to 0. Therefore, you don't need to create your own calculation.

You can also read about: