Reputation: 1224
I'm trying to calculate the number of days between a range excluding weekends. The code that I've come up with right now excludes only Saturdays but not Sundays. For instance, my code returns 1 instead of 0 when the start and end dates are 24-SEP-2022(Saturday) and 25-SEP-2022(Sunday). Similarly, 25-SEP-2022(Sunday) and 26-SEP-2022(Monday) returns 2 when they should have returned 1.
Here is my code:
String method(String start, String end) {
int a = 1;
DateTime startDate = DateTime.parse(start);
DateTime endDate = DateTime.parse(end);
while (startDate.isBefore(endDate)) {
startDate = startDate.add(const Duration(days: 1));
if (startDate.weekday != DateTime.saturday &&
startDate.weekday != DateTime.sunday) {
a++;
}
}
print('COUNT: $start :: $end $a');
return a.toString();
}
Any help would be appreciated!
Upvotes: 2
Views: 510
Reputation: 53
You did not pay attention to a
! You have initiated a = 1
, but in this case it has to be 0
. because of that it always returns one more day.
Upvotes: 1