Aswathy Gireesh
Aswathy Gireesh

Reputation: 1

Recurring for month and week in Flutter

I am trying to create a feature where I can transfer money by scheduling, so for that, I need a recurring option for the month and weak, And the problem that I face is, that if a user chooses the 31st of a month every month doesn't have the 31st, so the transaction should happen in that particular month's end date.

for example: If I start recurring date is 31st May 2022 no of transactions: 3 Current Output: Dates of transactions => 1st July 2022, 31st July 2022, 31st August 2022, Correct Output: 30th June 2022, 31st July 2022, 31st August 2022,

Upvotes: 0

Views: 414

Answers (1)

FMorschel
FMorschel

Reputation: 864

Maybe something like I proposed here:

With lastDayOfMonth you could potentially do something like

extension AddMonth on DateTime {
 DateTime addMonths([int amount = 1]) {
   final plusXMonths = DateTime(year, month + amount, day);
   final xMonthsAhead = DateTime(year, month + amount);
   if (xMonthsAhead.lastDayOfMonth.compareTo(plusXMonths).isNegative) {
     return xMonthsAhead.lastDayOfMonth;
   } else {
     return plusXMonths;
   }
 }
}

This proposition is based on this code that I created a PR for:

extension DateTimeLastFirstDay on DateTime {
  /// Returns the Monday of this week
  DateTime get firstDayOfWeek =>
      isUtc ? DateTime.utc(year, month, day + 1 - weekday) : DateTime(year, month, day + 1 - weekday);

  /// Returns the Sunday of this week
  DateTime get lastDayOfWeek =>
      isUtc ? DateTime.utc(year, month, day + 7 - weekday) : DateTime(year, month, day + 7 - weekday);

  /// Returns the first day of this month
  DateTime get firstDayOfMonth => isUtc ? DateTime.utc(year, month, 1) : DateTime(year, month, 1);

  /// Returns the last day of this month (considers leap years)
  DateTime get lastDayOfMonth => isUtc ? DateTime.utc(year, month + 1, 0) : DateTime(year, month + 1, 0);

  /// Returns the first day of this year
  DateTime get firstDayOfYear => isUtc ? DateTime.utc(year, 1, 1) : DateTime(year, 1, 1);

  /// Returns the last day of this year
  DateTime get lastDayOfYear => isUtc ? DateTime.utc(year, 12, 31) : DateTime(year, 12, 31);
}

Using the time package you could create a similar code for weeks.

Upvotes: 0

Related Questions