user6097845
user6097845

Reputation: 1437

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

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

Upvotes: 1

Views: 646

Answers (2)

Thiago Fontes
Thiago Fontes

Reputation: 375

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))));
  }
}

Upvotes: 2

user18309290
user18309290

Reputation: 8370

Use DateFormat class.

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

Upvotes: 1

Related Questions