Home > OS >  How can I add working days to a specific date (Flutter)?
How can I add working days to a specific date (Flutter)?

Time:08-18

I want to add the calulated working days to a specific date.

For example

I want to add 14 working days

date -> 08.17.2022 (it is input)

newDate -> 09.06.20222 (it is output)

I tried it with the code below but it didn't work as I want. What is my wrong? How can I do that?

Thanks in advance.

       final workingDays = <DateTime>[];
  final currentDate = DateTime.fromMicrosecondsSinceEpoch(
        widget.siparisModel.siparisTarih.microsecondsSinceEpoch);
  final orderDate = currentDate.add(Duration(days: 15));
  DateTime indexDate = currentDate;
  while (indexDate.difference(orderDate).inDays != 0) {
    final isWeekendDay = indexDate.weekday == DateTime.saturday || indexDate.weekday == DateTime.sunday;
    if (!isWeekendDay) {
      workingDays.add(indexDate);
    }
    indexDate = indexDate.add(Duration(days: 15));
  }

CodePudding user response:

You could do something like this:

  var newDate = DateTime(2022, 08, 17); // Copy from some "currentDate"
  var numOfWeekdaysToAdd = 14;

  while (numOfWeekdaysToAdd > 0) {
    do {
      newDate = newDate.add(Duration(days: 1));
    } while (newDate.weekday == DateTime.saturday || newDate.weekday == DateTime.sunday);
    numOfWeekdaysToAdd--;
  }

Working DartPad demo: https://dartpad.dev/?id=6ef6f4306944b350edfb77905239297e

If you want to, you could extend the "weekend-check" and make it more complex to also check for holidays in a specific locale. In that case I'd have a list of holiday-dates, and just add something like holidayDates.contains(newDate)

  • Related