AS stated in the title: Is there an easy way to get all the days of the week as string(within a list ofcourse) in the users locale?
My suggestion is:
static List<String> getDaysOfWeek([String locale]) {
final now = DateTime.now();
final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
return List.generate(7, (index) => index)
.map((value) => DateFormat(DateFormat.WEEKDAY, locale)
.format(firstDayOfWeek.add(Duration(days: value))))
.toList();
}
The idea is we define the date of the first day in the current week depending on current week day. Then just do loop 7 times starting from calculated date, add 1 day on each iteration and collect the result of DateFormat().format method with pattern DateFormat.WEEKDAY. To increase performance you can use lazy initialization. For example:
/// Returns a list of week days
static List<String> _daysOfWeek;
static List<String> get daysOfWeek {
if (_daysOfWeek == null) {
_daysOfWeek = getDaysOfWeek(); // Here you can specify your locale
}
return _daysOfWeek;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With