How set weekday datetime?

44 views Asked by At

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?

3

There are 3 answers

0
Affan Minhas On

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');
}
0
Irfan Ganatra On
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;
  }
0
pcba-dev On

You can create an extension on DateTime to be able to use it directly on objects:

extension DateTimeWeekday on DateTime {
  DateTime setWeekday(final int weekday) {
    final int current = this.weekday;

    // If the day of the week is already past the current value, set it to the next week's day.
    final int desired = current <= weekday ? weekday : weekday + 7;

    final int diff = desired - current;
    return this.add(Duration(days: diff));
  }
}