Home > OS >  Dart get the name of the day by its index: day 0 = Monday, day 1 = Tuesday etc
Dart get the name of the day by its index: day 0 = Monday, day 1 = Tuesday etc

Time:09-13

Is there an easy way in Dart to get the name of the day by its index (taking localization into account)?
day 0 = Monday
day 1 = Tuesday
...

I can keep a list of names, but I guess it would be better to use Dart's Date utilities

CodePudding user response:

For that you can start at any random date that is a Sunday and increment the days using date format to get the localized name of the day, here's an example code that prints all the days of the week given an index number:

import 'package:intl/intl.dart';


void main() {
  final sundayDate = DateTime.utc(2022, DateTime.july, 3);
  
  print('Prints the names of all days:');
  for(int i = 0; i< 7; i  ) {
    print(DateFormat('EEEE').format(sundayDate.add(Duration(days: i))));
  }
}

CodePudding user response:

Use DateFormat class.

print(DateFormat.EEEE().format(DateTime.now()));
  • Related