previousMonth method

DateTime previousMonth()

Returns a DateTime instance representing the exact date of the previous month.

Example:

DateTime currentDate = DateTime(2024, 1, 8);
DateTime previousMonthDate = currentDate.previousMonth;
print(previousMonthDate);  // Output: 2023-12-08 00:00:00

The previousMonth extension calculates and returns a new DateTime instance with the same day and time as the original date but adjusted to the exact date of the previous month.

Implementation

DateTime previousMonth() {
  final previousYear = month == 1 ? year - 1 : year;
  final previousMonthValue = month == 1 ? 12 : month - 1;
  return DateTime(
    previousYear,
    previousMonthValue,
    day,
    hour,
    minute,
    second,
    millisecond,
    microsecond,
  );
}