skip to Main Content

How can I set the day of the week I need for the date? Using DateTime or Jiffy? It is also possible to use another library if you cannot use these.

For example, on Kotlin with Joda DateTime, I can do this:

scheduleDate.withField(DateTimeFieldType.dayOfWeek(), 3) // set weekday Wednesday

Is it possible to do the same on Flutter?

2

Answers


  1. I think it can be approach like this way:

    import 'package:flutter/material.dart';
    
    DateTime setDateForDayOfWeek(DateTime date, int desiredDayOfWeek) {
      int difference = desiredDayOfWeek - date.weekday;
      
      /// Adjust the difference if it's negative
      if (difference < 0) {
        difference += 7;
      }
      
      return date.add(Duration(days: difference));
    }
    
    void main() {
      DateTime currentDate = DateTime.now();
      
      /// Setting the desired day of the week (e.g., Wednesday = 3)
      int desiredDayOfWeek = 3;
      
      DateTime desiredDate = setDateForDayOfWeek(currentDate, desiredDayOfWeek);
      
      print('Desired Date: $desiredDate');
    }
    
    Login or Signup to reply.
  2. List<DateTime> weekDates(DateTime? fromDate) {
        final result = [];
    
    
        final DateTime currentDate = fromDate == null ? DateTime.now() : fromDate;
    
    
        DateTime firstDay=fromDate!.subtract(Duration(days: fromDate.weekday-1));
    
        for(int x=0;x<=6;x++)
        {
          DateTime currentDate=firstDay.add(Duration(days: x));
    
          result.add(currentDate);
           
          
        }
    
    
    
        return result;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search