previousMonth static method

DateTime previousMonth(
  1. DateTime m
)

Implementation

static DateTime previousMonth(DateTime m) {
  int year = m.year;
  int month = m.month;
  int day = m.day;

  // Decrease the month
  month--;

  // If month goes below January, switch to December of the previous year
  if (month < 1) {
    month = 12;
    year--;
  }

  // Handle cases where the day might not exist in the previous month (e.g., March 31st)
  while (day > DateTime(year, month + 1, 0).day) {
    day--;
  }

  return DateTime(year, month, day);
}