I am making an app where I need to fetch recent transactions,
Here I want to load all transaction of current month other last two months Transactions
here I don't mean to calculate in days...like 60 days current month days because its making complicated for testing leap year...
What I want is simple,
Today its 14th Jan 2023 so I want all data of Jan-23,Dec-22,Nov-22
here is my code for current month previous month, but not happy with such basic code...need advance level code so that I can update based on Number of months requirement
List<TransactionModel> get showRecentTransactions {
int year=DateTime.now().year;
int month=DateTime.now().month;
if(month==1)
{
return _transactions.where((element) => element.date.year==DateTime.now().year && element.date.month==DateTime.now().month || element.date.month==12 && element.date.year==year-1).toList();
}
else
{
return _transactions.where((element) => element.date.year==DateTime.now().year && element.date.month==DateTime.now().month || element.date.month==month-1 && element.date.year==year).toList();
}
}
CodePudding user response:
You can try this way:
List<String> get showRecentTransactions {
DateTime now = DateTime.now();
late DateTime lastMonth;
late DateTime secondLastMonth;
if (now.month == 2) {
lastMonth = DateTime(now.year, 1, 10);
secondLastMonth = DateTime(now.year - 1, 12, 10);
} else if (now.month == 1) {
lastMonth = DateTime(now.year - 1, 12, 10);
secondLastMonth = DateTime(now.year - 1, 11, 10);
} else {
lastMonth = DateTime(now.year, now.month - 1, 10);
secondLastMonth = DateTime(now.year, now.month - 2, 10);
}
return _transactions
.where((element) =>
(element.date.year == now.year &&
element.date.month == now.month) ||
(element.date.year == lastMonth.year &&
element.date.month == lastMonth.month) ||
(element.date.year == secondLastMonth.year &&
element.date.month == secondLastMonth.month))
.toList();
}