Dart: how do I get first day of week for current locale?

Viewed 7841

It can be done in Java by

com.ibm.icu.util.Calendar.getInstance(Locale alocale).getFirstDayOfWeek()

Is there an equivalent way to get it in Dart?

6 Answers

This thing worked for me

DateTime today = DateTime.now();             
_firstDayOfTheweek = today.subtract(new Duration(days: today.weekday));

With Flutter you can use just:

MaterialLocalizations.of(context).firstDayOfWeekIndex;

To get first day of week, and last day of week:

 print("today is day: ${DateTime.now().weekday}");
print(
    "monday is day: ${DateTime.now().subtract(Duration(days: DateTime.now().weekday - 1))}");
print(
    "sunday is day: ${DateTime.now().add(Duration(days: DateTime.now().weekday - 1))}");

After a long long long search, I found jiffy that solves my problem. You can use it with Intl and get what you want.

Just initialize it in your main.dart

void main() async {
  Intl.defaultLocale = Intl.systemLocale;   // Define the default locale as System Locale
  await Jiffy.locale(Intl.defaultLocale);   // Define Jiffy locale
  runApp(MyApp());
}

And then, you can use the Jiffy function to get start and end of week

print(Jiffy(date).startOf(Units.WEEK)); 
print(Jiffy(date).endOf(Units.WEEK));

Ref: https://pub.dev/packages/jiffy

I couldn't figure out how to make it work. It would be nice Bob, if you could share your solution.

Here is mine for use in Flutter:

GlobalMaterialLocalizations.delegate
        .load(locale)
        .then((MaterialLocalizations materialLocalizations)
    {
        print("${materialLocalizations.firstDayOfWeekIndex}");
    });
Related