datetimedart

How to get start of or end of week in dart


How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday


Solution

  • You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:

    void main() {
      final date = DateTime.parse('2019-10-08 15:43:03.887');
      
      print('Date: $date');
      print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
      print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
    }
    
    DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
    

    UPDATE

    Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)