Dart get date of next friday

Viewed 1163

Im trying to make an app that counts down the time untill the next friday, but therefore I need the date of the next friday. Any help is deeply appreciated!

2 Answers

Solution

extension DateTimeExtension on DateTime {
  DateTime next(int day) {
    return this.add(
      Duration(
        days: (day - this.weekday) % DateTime.daysPerWeek,
      ),
    );
  }
}

Testing

void main() {
  var today = DateTime.now();
  print(today);
 
  print(today.next(DateTime.friday));
  print(today.next(DateTime.friday).weekday == DateTime.friday);
  
  // Works as expected when the next day is after sunday
  print(today.next(DateTime.monday));
  print(today.next(DateTime.monday).weekday == DateTime.monday);
}

Output

2020-06-24 18:47:40.318
2020-06-26 18:47:40.318
true
2020-06-29 18:47:40.318
true

See this for more information on DateTime.

I added some minor adjustments to the code above(answer posted by davideliseo)

The code above had an issue where it couldn't find the next week's day, but returned the day that was passed into the function.

Example: my DateTime is a Saturday. I Expect the next Saturday in the calendar to be returned NOT the same Saturday that was started with.

Also, I included a previous function because It could be helpful.

extension DateTimeExtension on DateTime {
  DateTime next(int day) {
    if (day == this.weekday)
      return this.add(Duration(days: 7));
    else {
      return this.add(
        Duration(
          days: (day - this.weekday) % DateTime.daysPerWeek,
        ),
      );
    }
  }

  DateTime previous(int day) {
    if (day == this.weekday)
      return this.subtract(Duration(days: 7));
    else {
      return this.subtract(
        Duration(
          days: (this.weekday - day) % DateTime.daysPerWeek,
        ),
      );
    }
  }
}
Related