Home > Mobile >  How do I get the days and date of the current week in dart?
How do I get the days and date of the current week in dart?

Time:10-25

I can't seem to find a way to get the current week's days name and days date, for example for this week I am looking for a way to get this result:

  List days = [
    {"label": "Mon", "day": "18"},
    {"label": "Tue", "day": "19"},
    {"label": "Wed", "day": "20"},
    {"label": "Thu", "day": "21"},
    {"label": "Fri", "day": "22"},
    {"label": "Sat", "day": "23"},
    {"label": "Sun", "day": "24"},
  ];

Took me a while but this is the best I could come up with. If someone has a better idea do share it, thanks.

import 'package:intl/intl.dart';

List getWeekDayList = [
  {"label": "Mon", "day": getDateOfWeekDay('monday')},
  {"label": "Tue", "day": getDateOfWeekDay('tuesday')},
  {"label": "Wed", "day": getDateOfWeekDay('wednesday')},
  {"label": "Thu", "day": getDateOfWeekDay('thursday')},
  {"label": "Fri", "day": getDateOfWeekDay('friday')},
  {"label": "Sat", "day": getDateOfWeekDay('saturday')},
  {"label": "Sun", "day": getDateOfWeekDay('sunday')},
];

DateTime weekdayOf(DateTime time, int weekday) =>
    time.add(Duration(days: weekday - time.weekday));

String getDateOfWeekDay(String weekday) {
  final now = DateTime.now();
  final df = DateFormat.d();
  final int dayToGet = weekdayToNum[weekday]!;
  return df.format(weekdayOf(now, dayToGet));
}

int getCurrentWeekDayInt() {
  return DateTime.now().weekday - 1;
}

var weekdayToNum = {
  'monday': 1,
  'tuesday': 2,
  'wednesday': 3,
  'thursday': 4,
  'friday': 5,
  'saturday': 6,
  'sunday': 7
};

CodePudding user response:

There are two problems we need to solve to implement what you ask.

The first is: Figure out the name of each weekday, we can use a list for that:


List<String> weekdayNames = [
  'Mon',
  'Tue',
  'Wed',
  'Thu',
  'Fri',
  'Sat',
  'Sun',
];

The second, figure out how many days ago it was Monday, we can use the weekday property for that

int monOffset = now.weekday-1

With those two out of the way, The label of your object would be equal to the index of the day in the names list, and the day property would be equal to the current day - mondayOffset the weekday we want to check

Here is the full code for generating the list:

void main() {
  List<String> weekdayNames = [
    'Mon',
    'Tue',
    'Wed',
    'Thu',
    'Fri',
    'Sat',
    'Sun',
  ];
  
  DateTime now = DateTime.now();
  int monOffset = now.weekday-1;
  
  List<Map<String, dynamic>> days = List.generate(
    7, 
    (index) => 
      {
        'label': weekdayNames[index], 
        'day': now.day-monOffset index
      }
  );
  
  print(days);
}
  •  Tags:  
  • dart
  • Related